code
stringlengths 1
13.8M
|
---|
library("arulesSequences")
data(zaki)
zaki.txt <-
read_baskets(con = system.file("misc", "zaki.txt",
package = "arulesSequences"),
info = c("sequenceID","eventID","SIZE"))
all.equal(zaki, zaki.txt)
s1 <- cspade(zaki, parameter = list(support = 0.4),
control = list(verbose =TRUE))
s1
s2 <- cspade(zaki, parameter = list(support = 0.4, maxsize = 2, maxlen = 2))
s2
nitems(s1)
nitems(s1, itemsets = TRUE)
nitems(s2)
nitems(s2, itemsets = TRUE)
labels(s1, setSep = "->", seqStart = "", seqEnd = "")
summary(s1)
inspect(s1)
data.frame(items = itemLabels(s1),
counts = itemFrequency(s1))
data.frame(items = itemLabels(s2),
counts = itemFrequency(s2))
data.frame(itemsets = itemLabels(s2, itemsets = TRUE),
counts = itemFrequency(s2, itemsets = TRUE))
as(s2, "data.frame")
sequenceInfo(s2) <- sequenceInfo(s2)
sequenceInfo(s2)
itemInfo(s2) <- itemInfo(s2)
itemInfo(s2)
t <- itemTable(s2)
rownames(t) <-
itemLabels(s2)[as.integer(rownames(t))]
t
t <- itemTable(s2, itemsets = TRUE)
rownames(t) <-
itemLabels(s2, itemsets = TRUE)[as.integer(rownames(t))]
t
d1 <- as(s1, "data.frame")
d1$size <- size(s1)
d1$length <- size(s1, type = "length")
d1$ritems <- ritems(s1, "max")
d1$maximal <- is.maximal(s1)
d1
as(s1@elements, "data.frame")
d1[s1 %in% c("D", "F"), 1:2]
d1[s1 %ain% c("D", "F"), 1:2]
d1[s1 %pin% "D", 1:2]
as(subset(s1, x %ain% c("D", "F")), "data.frame")
as(subset(s1, support == 1), "data.frame")
match(s2,s1)
match(s1,s2)
s <- unique(c(s1,s2))
match(s1, s)
all.equal(s1, s)
all.equal(s1, c(s[1], s1[-1]))
all.equal(quality(s1)$support, support(s1, zaki))
r1 <- ruleInduction(s1, confidence = 0.5)
r1
r2 <- ruleInduction(s2, confidence = 0.5)
r2
labels(r1, itemSep = "->", setStart = "", setEnd = "")
summary(r1)
inspect(r1)
as(r2, "data.frame")
as(subset(r2, lhs(x) %in% c("B", "F")), "data.frame")
as(subset(r2, lhs(x) %ain% c("B", "F")), "data.frame")
as(subset(r2, confidence == 1), "data.frame")
match(r2, r1)
match(r1, r2)
r <- unique(c(r1, r2))
match(r1, r)
all.equal(r1, r)
s <- as(r2, "sequences")
match(s, s2)
all.equal(r1, c(r1[1], r1[-1]))
z <- as(zaki, "timedsequences")
all.equal(z, c(z[1], z[-1]))
z <- cspade(zaki, parameter = list(support = 0.4, maxwin = 5),
control = list(verbose =TRUE))
identical(s1, z)
s1 <- cspade(zaki, parameter = list(support = 0.4),
control = list(verbose =TRUE, tidLists = TRUE))
summary(tidLists(s1))
transactionInfo(tidLists(s1))
z <- supportingTransactions(s1, zaki)
all.equal(tidLists(s1[1:4, ]), z[1:4, ])
z <- support(s1, zaki, control = list(parameter = list()))
all.equal(z, quality(s1)$support)
z <- as(as(zaki, "timedsequences"), "sequences")
z <- support(s1, z, control = list(parameter = list()))
all.equal(z, quality(s1)$support)
z <- quality(s1)$support
z <- z > apply(is.subset(s1, proper = TRUE), 1L, function(x)
suppressWarnings(max(z[x])))
all.equal(z, is.closed(s1))
r <- ruleInduction(s2[size(s2) > 1L], zaki, confidence = 0.5)
all.equal(as(r2, "data.frame"), as(r, "data.frame"))
k <- rhs(r1) %ain% "A"
z <- quality(r1)$confidence[k]
z <- z <= apply(is.superset(lhs(r1)[k], proper = TRUE), 1L, function(x)
suppressWarnings(max(z[x])))
all.equal(z, is.redundant(r1)[k]) |
test_that("Inference for Multiplex networks", {
if (Sys.info()['sysname'] != "Windows") {
set.seed(2)
npc <- 30
Q <- 3
n <- npc * Q
Z<-diag(Q)%x%matrix(1,npc,1)
P<-matrix(runif(Q*Q),Q,Q)
A<-1*(matrix(runif(n*n),n,n)<Z%*%P%*%t(Z))
type <- "simple"
netA <- defineSBM(A,"bernoulli",type = "simple",directed=TRUE,dimLabels=c("Actor"))
B <- 1*(matrix(runif(n*n),n,n)<Z%*%P%*%t(Z))
netB <- defineSBM(B,"bernoulli",type = "simple",dimLabels=c("Actor"))
myMultiplex <- MultiplexSBM_fit$new(list(netA,netB))
netC <- defineSBM(B,"poisson",type = "simple",dimLabels=c("Actor"))
expect_equal(myMultiplex$directed, c(TRUE,TRUE))
expect_equal(myMultiplex$nbNetworks,2)
expect_equal(myMultiplex$dependentNetwork,FALSE)
expect_equal(MultiplexSBM_fit$new(list(netA,netB), TRUE)$dependentNetwork,TRUE)
expect_error(MultiplexSBM_fit$new(list(netA,netC), TRUE))
expect_error(MultiplexSBM_fit$new(list(netA,netB,netB), TRUE))
currentOptions <- list(
verbosity = 1,
nbBlocksRange = list(c(1,10)),
nbCores = 2,
maxiterVE = 100,
maxiterVEM = 100,
initBM = TRUE
)
myMultiplexFitindep <- MultiplexSBM_fit$new(list(netA,netB,netC))
myMultiplexFitindep$optimize(estimOptions = currentOptions)
expect_equal(length(myMultiplexFitindep$connectParam),3)
myMultiplexFitdep <- MultiplexSBM_fit$new(list(netA,netB),dependentNet = TRUE)
currentOptions <- list(
verbosity = 3,
plot = TRUE,
explorFactor = 1.5,
nbBlocksRange = c(4,Inf),
nbCores = 2,
fast = TRUE
)
myMultiplexFitdep$optimize(estimOptions = currentOptions)
myMultiplexFitdep$probMemberships
expect_equal(class(myMultiplexFitdep$memberships),"list")
expect_equal(length(myMultiplexFitdep$connectParam),4)
expect_equal(myMultiplexFitdep$dependentNetwork,TRUE)
set.seed(2)
npc1 <- 30
npc2 <- 20
Q1 <- 2
Q2 <- 3
n1 <- npc1 * Q1
n2 <- npc2 * Q2
Z1 <-diag(Q1)%x%matrix(1,npc1,1)
Z2 <-diag(Q2)%x%matrix(1,npc2,1)
P<-matrix(runif(Q1*Q2),Q1,Q2)
A<-1*(matrix(runif(n1*n2),n1,n2)<Z1%*%P%*%t(Z2))
netA <- defineSBM(A,"bernoulli",type = "bipartite",directed=TRUE,dimLabels=c("Actor","Object"))
B <- 1*(matrix(runif(n1*n2),n1,n2)<Z1%*%P%*%t(Z2))
netB <- defineSBM(B,"bernoulli",type = "bipartite",dimLabels=c("Actor","Object"))
myMultiplexFitindep <- MultiplexSBM_fit$new(list(netA,netB))
currentOptions <- list(
verbosity = 1,
nbBlocksRange = list(c(1,10),c(1,10)),
nbCores = 2,
maxiterVE = 100,
maxiterVEM = 100,
initBM = FALSE
)
names(currentOptions$nbBlocksRange) = c("Actor","Object")
myMultiplexFitindep$optimize(currentOptions)
expect_equal(length(myMultiplexFitindep$connectParam),2)
}
}) |
context("taskscheduler-examples")
test_that("taskscheduleR examples can be scheduled as expected", {
skip_on_cran()
myscript <- system.file("extdata", "helloworld.R", package = "taskscheduleR")
expect_warning(taskscheduler_create(taskname = "myfancyscript", rscript = myscript,
schedule = "ONCE", starttime = format(Sys.time() + 62, "%H:%M")), NA)
expect_warning(tasks <- taskscheduler_ls(), NA)
expect_warning(taskscheduler_delete(taskname = "myfancyscript"), NA)
})
test_that("taskscheduler_ls returns a data.frame", {
skip_on_cran()
expect_is(taskscheduler_ls(), "data.frame")
}) |
.applyAR2seg <- function(varargin) {
seg = varargin$seg
out = varargin$out
rules = varargin$rules
PSTR = varargin$PSTR
sI = grep(seg, rules@rhs@itemInfo[, 1])
cn_status = rep(NA, length(rules))
for (cn_ in unique(out[!is.na(out)])) {
eqI = intersect(grep(paste0(" ", cn_), rules@rhs@itemInfo[, 1]), sI)
if (!isempty(eqI)) {
cn_status[rules@rhs@data[eqI, ]] = cn_
}
}
cmap = matrix(F, length(rules), ncol(out))
colnames(cmap) = colnames(out)
for (i in 1:length(rules)) {
seg1_EQ = rules@lhs@itemInfo[rules@lhs@data[, i], ]
cI = sapply(seg1_EQ, .testARstatement, out)
cI = apply(cI, 1, all)
cI[is.na(cI)] = F
cmap[i, names(cI)] = cI
}
cellsWithRules = c()
for (cell in colnames(out)) {
for (cn_ in unique(cn_status)) {
eq_ii = which(cmap[, cell] & cn_status == cn_)
if (!isempty(eq_ii)) {
cellsWithRules = c(cellsWithRules, cell)
}
PSTR[as.character(cn_), cell] = sum(quality(rules[eq_ii])$confidence)
}
}
cellsWithRules = unique(cellsWithRules)
return(PSTR)
} |
`re.timeSeries` <-
function(x,...) {
if(!requireNamespace('timeSeries', quietly=TRUE)) {
timeSeries <- function(...) message("package 'timeSeries' is required")
} else {
timeSeries <- timeSeries::timeSeries
}
x.attr <- attributes(x)
xx <- structure(x,dimnames=x.attr$dimnames,index=x.attr$index)
original.attr <- attributes(x)[!names(attributes(x)) %in%
c("dim","dimnames","index","class")]
for(i in names(original.attr)) {
attr(xx,i) <- NULL
}
timeSeries(coredata(xx),charvec=as.POSIXct(format(index(x)),tz="GMT"),format=x.attr$format,
zone=x.attr$FinCenter,FinCenter=x.attr$FinCenter,
recordIDs=x.attr$recordIDs,title=x.attr$title,
documentation=x.attr$documentation,...)
}
`as.xts.timeSeries` <-
function(x,dateFormat="POSIXct",FinCenter,recordIDs,title,documentation,..., .RECLASS=FALSE) {
if(missing(FinCenter))
FinCenter <- x@FinCenter
if(missing(recordIDs))
recordIDs <- x@recordIDs
if(missing(title))
title <- x@title
if(missing(documentation))
documentation <- x@documentation
indexBy <- structure(x@positions, class=c("POSIXct","POSIXt"), tzone=FinCenter)
order.by <- do.call(paste('as',dateFormat,sep='.'),list(as.character(indexBy)))
if(.RECLASS) {
xts(as.matrix([email protected]),
order.by=order.by,
format=x@format,
FinCenter=FinCenter,
recordIDs=recordIDs,
title=title,
documentation=documentation,
.CLASS='timeSeries',
.CLASSnames=c('FinCenter','recordIDs','title','documentation','format'),
.RECLASS=TRUE,
...)
} else {
xts(as.matrix([email protected]),
order.by=order.by,
...)
}
}
as.timeSeries.xts <- function(x, ...) {
if(!requireNamespace('timeSeries', quietly=TRUE)) {
timeSeries <- function(...) message("package 'timeSeries' is required")
} else {
timeSeries <- timeSeries::timeSeries
}
timeSeries(data=coredata(x), charvec=as.character(index(x)), ...)
}
`xts.as.timeSeries` <- function(x,...) {} |
library("aroma.affymetrix")
verbose <- Arguments$getVerbose(-50, timestamp=TRUE)
dataSet <- "Affymetrix-CytoSampleData"
chipType <- "Cytogenetics_Array"
cdf <- AffymetrixCdfFile$byChipType(chipType)
print(cdf)
csR <- AffymetrixCelSet$byName(dataSet, cdf=cdf)
print(csR)
acc <- AllelicCrosstalkCalibration(csR)
print(acc)
csC <- process(acc, verbose=verbose)
print(csC)
for (what in c("input", "output")) {
toPNG(getFullName(acc), tags=c("allelePairs", what), aspectRatio=0.7, {
plotAllelePairs(acc, array=1, what=what, verbose=verbose)
})
}
plm <- AvgSnpPlm(csC, mergeStrands=TRUE)
print(plm)
if (length(findUnitsTodo(plm)) > 0) {
units <- fitCnProbes(plm, verbose=verbose)
str(units)
units <- fit(plm, verbose=verbose)
str(units)
}
ces <- getChipEffectSet(plm)
print(ces)
dsList <- exportTotalAndFracB(ces, verbose=verbose)
print(dsList)
cns <- CbsModel(dsList$total)
print(cns)
ce <- ChromosomeExplorer(cns, zooms=2^(0:5))
print(ce)
process(ce, chromosomes=c(19, 22, 23), verbose=verbose) |
hyperbFit <- function(x, freq = NULL, paramStart = NULL,
startMethod = c("Nelder-Mead","BFGS"),
startValues = c("BN","US","FN","SL","MoM"),
criterion = "MLE",
method = c("Nelder-Mead","BFGS","nlm",
"L-BFGS-B","nlminb","constrOptim"),
plots = FALSE, printOut = FALSE,
controlBFGS = list(maxit = 200),
controlNM = list(maxit = 1000), maxitNLM = 1500,
controlLBFGSB = list(maxit = 200),
controlNLMINB = list(),
controlCO = list(), ...) {
startValues <- match.arg(startValues)
startMethod <- match.arg(startMethod)
method <- match.arg(method)
xName <- paste(deparse(substitute(x), 500), collapse = "\n")
if (!is.null(freq)) {
if (length(freq) != length(x))
stop("vectors x and freq are not of the same length")
x <- rep(x, freq)
}
x <- as.numeric(na.omit(x))
startInfo <- hyperbFitStart(x, startValues = startValues,
paramStart = paramStart,
startMethodSL = startMethod,
startMethodMoM = startMethod, ...)
paramStart <- startInfo$paramStart
paramStart <- as.numeric(hyperbChangePars(2, 1, param = paramStart))
if (!(method %in% c("L-BFGS-B","nlminb","constrOptim"))){
paramStart <- c(paramStart[1], log(paramStart[2]),
paramStart[3], log(paramStart[4]))
}
svName <- startInfo$svName
breaks <- startInfo$breaks
empDens <- startInfo$empDens
midpoints <- startInfo$midpoints
eps <- 1e-10
if (criterion == "MLE") {
if (!(method %in% c("L-BFGS-B","nlminb","constrOptim"))){
llfunc <- function(param) {
KNu <- besselK(exp(param[4]), nu = 1)
hyperbDens <- (2*exp(param[2])* sqrt(1 + param[3]^2)*KNu)^(-1)*
exp(-exp(param[4])* (sqrt(1 + param[3]^2)*
sqrt(1 + ((x - param[1])/exp(param[2]))^2) -
param[3]*(x - param[1])/exp(param[2])))
return(-sum(log(hyperbDens)))
}
} else {
llfunc <- function(param) {
if (param[1] <= eps | param[4] <= eps) return(1e99)
KNu <- besselK(param[4], nu = 1)
hyperbDens <- (2*param[2]* sqrt(1 + param[3]^2)*KNu)^(-1)*
exp(-param[4]* (sqrt(1 + param[3]^2)*
sqrt(1 + ((x - param[1])/param[2])^2) -
param[3]*(x - param[1])/param[2]))
return(-sum(log(hyperbDens)))
}
}
output <- numeric(7)
ind <- 1:4
if (method == "BFGS") {
cat("paramStart =", paramStart[1],paramStart[2],paramStart[3],
paramStart[4],"\n")
opOut <- optim(paramStart, llfunc, NULL, method = "BFGS",
control = controlBFGS, ...)
}
if (method == "Nelder-Mead") {
opOut <- optim(paramStart, llfunc, NULL, method = "Nelder-Mead",
control = controlNM, ...)
}
if (method == "nlm") {
ind <- c(2, 1, 5, 4)
opOut <- nlm(llfunc, paramStart, iterlim = maxitNLM, ...)
}
if (method == "L-BFGS-B") {
cat("paramStart =", paramStart[1],paramStart[2],paramStart[3],
paramStart[4],"\n")
cat("Starting loglikelihood = ", llfunc(paramStart), " \n")
opOut <- optim(par = paramStart, llfunc, NULL,
method = "L-BFGS-B",
lower = c(-Inf,eps,-Inf,eps),
control = controlLBFGSB, ...)
}
if (method == "nlminb") {
ind <- c(1, 2, 3)
cat("paramStart =", paramStart[1],paramStart[2],paramStart[3],
paramStart[4],"\n")
cat("Starting loglikelihood = ", llfunc(paramStart), " \n")
opOut <- nlminb(start = paramStart, llfunc, NULL,
lower = c(-Inf,eps,-Inf,eps),
control = controlNLMINB, ...)
}
if (method == "constrOptim") {
cat("paramStart =", paramStart[1],paramStart[2],paramStart[3],
paramStart[4],"\n")
cat("Starting loglikelihood = ", llfunc(paramStart), " \n")
cat("Feasible?\n")
print((paramStart%*%diag(c(0,1,0,1))- c(0,0,0,0)) >= 0)
opOut <- constrOptim(theta = paramStart, llfunc, NULL,
ui = diag(c(0,1,0,1)), ci = c(-1e+99,0,-1e+99,0),
control = controlCO, ...)
}
param <- as.numeric(opOut[[ind[1]]])[1:4]
if (!(method %in% c("L-BFGS-B","nlminb","constrOptim"))){
param <- hyperbChangePars(1, 2,
param = c(param[1], exp(param[2]), param[3], exp(param[4])))
} else {
param <- hyperbChangePars(1, 2, param = param)
}
names(param) <- c("mu", "delta", "alpha", "beta")
maxLik <- -(as.numeric(opOut[[ind[2]]]))
conv <- as.numeric(opOut[[ind[4]]])
iter <- as.numeric(opOut[[ind[3]]])[1]
}
if (!(method %in% c("L-BFGS-B","nlminb","constrOptim"))){
paramStart <- hyperbChangePars(1, 2,
param = c(paramStart[1], exp(paramStart[2]),
paramStart[3], exp(paramStart[4])))
} else {
paramStart <- hyperbChangePars(1, 2, param = paramStart)
}
fitResults <- list(param = param, maxLik = maxLik, criterion = criterion,
method = method, conv = conv, iter = iter,
obs = x, obsName = xName, paramStart = paramStart,
svName = svName, startValues = startValues,
breaks = breaks, midpoints = midpoints,
empDens = empDens)
class(fitResults) <- c("hyperbFit", "distFit")
if (printOut)
print(fitResults, ...)
if (plots)
plot.hyperbFit(fitResults, ...)
return(fitResults)
}
print.hyperbFit <-
function(x, digits = max(3, getOption("digits") - 3), ...) {
if (! "hyperbFit" %in% class(x))
stop("Object must belong to class hyperbFit")
cat("\nData: ", x$obsName, "\n")
cat("Parameter estimates:\n")
print.default(format(x$param, digits = digits),
print.gap = 2, quote = FALSE)
cat("Likelihood: ", x$maxLik, "\n")
cat("criterion : ", x$criterion , "\n")
cat("Method: ", x$method, "\n")
cat("Convergence code: ", x$conv, "\n")
cat("Iterations: ", x$iter, "\n")
invisible(x)
}
plot.hyperbFit <- function(x, which = 1:4,
plotTitles = paste(c("Histogram of ",
"Log-Histogram of ",
"Q-Q Plot of ",
"P-P Plot of "),
x$obsName, sep = ""),
ask = prod(par("mfcol")) < length(which) &
dev.interactive(), ...) {
if (! "hyperbFit" %in% class(x))
stop("Object must belong to class hyperbFit")
if (ask) {
op <- par(ask = TRUE)
on.exit(par(op))
}
par(mar = c(6, 4, 4, 2) + 0.1)
show <- rep(FALSE, 4)
show[which] <- TRUE
param <- x$param
breaks <- x$breaks
empDens <- x$empDens
mipoints <- x$midpoints
obs <- x$obs
obsName <- x$obsName
hypDens <- function(x)
dhyperb(x, param = param)
logHypDens <- function(x)
log(dhyperb(x, param = param))
ymax <- 1.06 * max(hypDens(seq(min(breaks), max(breaks), 0.1)),
empDens, na.rm = TRUE)
if (show[1]) {
hist.default(obs, breaks, right = FALSE, freq = FALSE, ylim = c(0, ymax),
main = plotTitles[1], ...)
curve(hypDens, min(breaks) - 1, max(breaks) + 1, add = TRUE, ylab = NULL)
title(sub = paste("param = (",
round(param[1], 3), ", ", round(param[2], 3), ", ",
round(param[3], 3), ", ", round(param[4], 3), ")", sep = ""))
}
if (show[2]) {
logHist(obs, breaks, include.lowest = TRUE, right = FALSE,
main = plotTitles[2], ...)
curve(logHypDens, min(breaks) - 1, max(breaks) + 1, add = TRUE,
ylab = NULL, xlab = NULL)
title(sub = paste("param = (",
round(param[1], 3), ", ", round(param[2], 3), ", ",
round(param[3], 3), ", ", round(param[4], 3), ")", sep = ""))
}
if (show[3])
qqhyperb(obs, param = param, main = plotTitles[3], ...)
if (show[4])
pphyperb(obs, param = param, main = plotTitles[4], ...)
invisible()
}
coef.hyperbFit <- function(object, ...) {
object$param
}
vcov.hyperbFit <- function(object, ...) {
obs <- object$obs
param <- object$param
hessian <- hyperbHessian(obs, param, hessianMethod= "exact",
whichParam = 2)
varcov <- solve(hessian)
varcov
} |
test_that("getLastChildTaxon works", {
expect_equal(as.numeric(prop.table(table(grepl("^Hap", getLastChildTaxon("suborder")$taxon)))), c(0.25,0.75))
}) |
context("Testing suberbPlot")
test_that("PRELIMINARY TESTS (1/4)", {
options(superb.feedback = 'none')
library(grid)
library(gridExtra)
plt <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean", plotStyle="bar" )
expect_equal( "ggplot" %in% class(plt), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("PRELIMINARY TESTS (2/4)", {
options(superb.feedback = 'none')
library(grid)
g0 <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean",
adjustments = list(purpose = "difference"), plotStyle="bar"
)
g1 <- g0 + xlab("Dose") + ylab("Tooth Growth") + labs(title="adsf") +
theme_light(base_size=20) + annotation_custom(grid.text("allo",x=.5,y=.5,gp=gpar(fontsize=20, col="grey")))
g2 <- g1 + theme(axis.text.x = element_text(size=30, colour="red") ) + coord_cartesian(ylim=c(5,45))
expect_equal( "ggplot" %in% class(g2), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("PRELIMINARY TESTS (3/4)", {
options(superb.feedback = 'none')
res <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"),
variables = "len", showPlot=FALSE )
expect_output( str(res), "data.frame")
options(superb.feedback = c('design','warnings','summary'))
})
test_that("PRELIMINARY TESTS (4/4)", {
options(superb.feedback = 'none')
p <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean", plotStyle="line" )
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 1a: 3 groupes inpependants", {
options(superb.feedback = c('none'))
dta1a <- GRD( BSFactors = "Group(3)", Population = list( mean=10, stddev = 5) )
p <- superbPlot(dta1a, BSFactor = "Group", variables = "DV",
statistic = "mean", errorbar = "SE", plotStyle="line")
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 1b: factorielle a grps independants; 3 x 2", {
options(superb.feedback = c('none'))
dta1b <- GRD( BSFactors = "Group(3): Sex(2)", Population = list( mean=10, stddev = 5))
p <- superbPlot(dta1b, BSFactor = c("Group","Sex"), variables = "DV",
statistic = "mean", errorbar = "SE" )
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 2a: 1 facteur a 3 mesures repetees; (3)", {
options(superb.feedback = c('warnings'))
dta2a <- GRD( WSFactors = "Moment(3)", SubjectsPerGroup = 5, Population = list( mean=10, stddev = 5))
expect_message( p <- superbPlot(dta2a, WSFactor = "moment(3)",
adjustments=list(decorrelation="CA"),
errorbar = "CI", plotStyle="line",
variables = c("DV.1","DV.2","DV.3")
))
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 2b: 2 facteurs a mesures repetees; (3 x 2)", {
options(superb.feedback = "none")
dta2b <- GRD( WSFactors = "Moment(3): Dose(2)", SubjectsPerGroup = 5, Population = list( mean=10, stddev = 5, rho = .80))
p <- superbPlot(dta2b, WSFactor = c("moment(3)","Dose(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic="mean", errorbar = "CI", gamma = 0.90, plotStyle = "line",
adjustments = list(purpose="difference", decorrelation="CM"),
errorbarParams = list(position = position_dodge(width = .15)),
pointParams = list(position = position_dodge(width = .15)),
)
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c("design","warnings") )
})
test_that("test 3: scheme mixte; 3 x (3)", {
options(superb.feedback = c('warnings'))
dta3 <- GRD( BSFactors = "Group(3)", WSFactors = "Moment(3)",
SubjectsPerGroup = 5, Population = list( mean=10, stddev = 5),
Effects = list("Moment" = slope(5))
)
expect_message( p <- superbPlot(dta3, WSFactor = "Moment(3)", BSFactor = "Group",
variables = c("DV.1","DV.2","DV.3"),
statistic = "mean", errorbar = "SE", plotStyle="line",
adjustments = list(purpose="single", decorrelation="CM")
))
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 4a: scheme a trois facteurs, 2 etant between 3 x 3 x (3)", {
options(superb.feedback = c('design','warnings'))
dta4a <- GRD( BSFactors = "Group(3) : Dose(3)", WSFactors = "Moment(3)",
SubjectsPerGroup = 4, Population = list( mean=10, stddev = 5),
Effects = list("Moment" = slope(5))
)
p <- superbPlot(dta4a, BSFactor = c("Group","Dose"), WSFactor = "Moment(3)",
variables = c("DV.1","DV.2","DV.3"), plotStyle = "line",
statistic = "mean", errorbar = "SE",
adjustments = list(purpose="difference", decorrelation="none"),
factorOrder = c("Dose","Group","Moment"), showPlot = T)
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 5a: scheme a quatre facteurs; 5 x 4 (3 x 2)", {
options(superb.feedback = "none")
dta5a <- GRD( BSFactors = "Group(5) : Dose(4)", WSFactors = "Moment(3):Hand(2)",
Population = list( mean=10, stddev = 5, rho = .90),
Effects = list("Moment" = slope(5), "Hand" = slope(10)) )
p <- superbPlot(dta5a, plotStyle="line",
WSFactor = c("Moment(3)","Hand(2)"),
BSFactor= c("Group","Dose"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "mean", errorbar = "CI", gamma = .9999,
adjustments = list(purpose="difference", decorrelation="CM")
)
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c("design","warnings") )
})
test_that("test 6: Some data", {
options(superb.feedback = c('none'))
dta6 <- GRD( WSFactors = "Moment(3):Hand(2)",
Effects = list("Moment" = slope(5), "Hand" = slope(3)),
SubjectsPerGroup = 6,
Population = list (mean = 20, stddev = 5, rho = 0.8) )
expect_output( str(dta6), "data.frame")
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6a: factorOrder", {
options(superb.feedback = "none")
library(gridExtra)
dta6 <- GRD( WSFactors = "Moment(3):Hand(2)",
Effects = list("Moment" = slope(5), "Hand" = slope(3)),
SubjectsPerGroup = 6,
Population = list (mean = 20, stddev = 5, rho = 0.8) )
p1 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "mean", errorbar = "SE", factorOrder = c("Moment", "Hand") )
p2 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "mean", errorbar = "SE", factorOrder = c("Hand","Moment") )
p <- grid.arrange(p1,p2,ncol=2)
expect_equal( "ggplot" %in% class(p1), TRUE)
expect_equal( "ggplot" %in% class(p2), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6b: adjustments CA vs CM vs LM", {
options(superb.feedback = "none")
library(gridExtra)
dta6 <- GRD( WSFactors = "Moment(3):Hand(2)",
Effects = list("Moment" = slope(5), "Hand" = slope(3)),
SubjectsPerGroup = 6,
Population = list (mean = 20, stddev = 5, rho = 0.8) )
p1 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
adjustments = list(purpose="difference", decorrelation="CA") )+
coord_cartesian( ylim = c(8,30) ) + labs(title="CA")
p2 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
adjustments = list(purpose="difference", decorrelation="CM") )+
coord_cartesian( ylim = c(8,30) ) + labs(title="CM")
p3 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
adjustments = list(purpose="difference", decorrelation="LM") )+
coord_cartesian( ylim = c(8,30) ) + labs(title="LM")
p <- grid.arrange(p1,p2,p3,ncol=3)
expect_equal( "ggplot" %in% class(p1), TRUE)
expect_equal( "ggplot" %in% class(p2), TRUE)
expect_equal( "ggplot" %in% class(p3), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6c: statistics of central tendency mean, median and gmean", {
options(superb.feedback = "none")
library(gridExtra)
dta6 <- GRD( WSFactors = "Moment(3):Hand(2)",
Effects = list("Moment" = slope(5), "Hand" = slope(3)),
SubjectsPerGroup = 6,
Population = list (mean = 20, stddev = 5, rho = 0.8) )
p1 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "mean", errorbar = "CI" ) +
coord_cartesian( ylim = c(8,30) ) + labs(title="mean")
p2 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "median", errorbar = "CI" ) +
coord_cartesian( ylim = c(8,30) ) + labs(title="median")
p3 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "gmean", errorbar = "CI" ) +
coord_cartesian( ylim = c(8,30) ) + labs(title="geometric mean")
p <- grid.arrange(p1,p2,p3,ncol=3)
expect_equal( "ggplot" %in% class(p1), TRUE)
expect_equal( "ggplot" %in% class(p2), TRUE)
expect_equal( "ggplot" %in% class(p3), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6d: statistics of dispersion sd and MAD", {
options(superb.feedback = "none")
library(gridExtra)
dta6 <- GRD( WSFactors = "Moment(3):Hand(2)",
Effects = list("Moment" = slope(5), "Hand" = slope(3)),
SubjectsPerGroup = 6,
Population = list (mean = 20, stddev = 5, rho = 0.8) )
p1 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "sd", errorbar = "CI" )
p2 <- superbPlot(dta6,
WSFactor = c("Moment(3)","Hand(2)"),
variables = c("DV.1.1","DV.2.1","DV.3.1","DV.1.2","DV.2.2","DV.3.2"),
statistic = "MAD", errorbar = "CI" )
p <- grid.arrange(p1,p2,ncol=2)
expect_equal( "ggplot" %in% class(p1), TRUE)
expect_equal( "ggplot" %in% class(p2), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6e: adding ggplot options", {
options(superb.feedback = 'none')
p1 <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean", errorbar = "CI", gamma = .999,
adjustments = list(purpose = "difference") )
p2 <- p1 +
xlab("Dose per day") + ylab("Tooth Growth after study") +
theme_light(base_size=14 )
expect_equal( "ggplot" %in% class(p2), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6f: adding ggplot options to the error bars, to the points", {
options(superb.feedback = 'none')
p <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean", errorbar = "CI", gamma = .999,
adjustments = list(purpose = "difference"),
errorbarParams = list(width = .2, size = 3, colour = "gray"),
barParams = list(linetype = 3, colour = "black", size = .5)
)
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("test 6g: adding ggplot options to the error bars, to the points (bis)", {
options(superb.feedback = 'none')
p <- superbPlot(ToothGrowth, BSFactor = c("dose","supp"), variables = "len",
statistic = "mean", errorbar = "CI", gamma = .999,
adjustments = list(purpose = "difference"),
plotStyle = "line",
errorbarParams = list(width = .02, size = 0.1, colour = "gray"),
pointParams = list(colour = "gray", size = 10.5)
)
expect_equal( "ggplot" %in% class(p), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Explorations for ICC", {
options(superb.feedback = c('warnings'))
library(gridExtra)
dta99 <- GRD( WSFactors = "Moment(3)", SubjectsPerGroup = 15,
Population = list( mean=20, stddev = 5),
Effects = list("Moment" = slope(3) ) )
dta99$myclus <- sort(rep(1:5, 3))
dta99$DV.1 <- dta99$DV.1 + 10 * dta99$myclus
dta99$DV.2 <- dta99$DV.2 + 10 * dta99$myclus
dta99$DV.3 <- dta99$DV.3 + 10 * dta99$myclus
expect_message( noncluster <- superbPlot(dta99, WSFactor = "moment(3)",
adjustments = list(decorrelation="CM"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="Without cluster information") + coord_cartesian( ylim = c(40,60) ) )
expect_message( yescluster <- superbPlot(dta99, WSFactor = "moment(3)",
adjustments = list(decorrelation="CM", samplingDesign = "CRS"),
clusterColumn = "myclus",
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with cluster information") + coord_cartesian( ylim = c(40,60) ) )
p <- grid.arrange(noncluster, yescluster, ncol=2)
expect_equal( "ggplot" %in% class(noncluster), TRUE)
expect_equal( "ggplot" %in% class(yescluster), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Verifying CA and popSize ", {
options(superb.feedback = c('warnings'))
library(gridExtra)
dta3 <- GRD( BSFactors = "Group(2)", WSFactors = "Moment(3)",
SubjectsPerGroup = 5, Population = list (mean = 20, stddev = 5, rho = 0.8),
Effects = list("Moment" = slope(5)) )
expect_message( p1 <- superbPlot(dta3, WSFactor = "Moment(3)", BSFactor = "Group",
variables = c("DV.1","DV.2","DV.3"),
statistic = "mean", errorbar = "SE",
adjustments = list(purpose="single", decorrelation="CM", popSize = Inf )
) + labs(title="Infinite populations") )
expect_message( p2 <- superbPlot(dta3, WSFactor = "Moment(3)", BSFactor = "Group",
variables = c("DV.1","DV.2","DV.3"),
statistic = "mean", errorbar = "SE",
adjustments = list(purpose="single", decorrelation="CM", popSize = c(Inf,6) )
) + labs(title="population of 6 in grp 2") )
p <- grid.arrange(p1,p2,ncol=2)
expect_equal( "ggplot" %in% class(p1), TRUE)
expect_equal( "ggplot" %in% class(p2), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Testing pre and post processing", {
options(superb.feedback = c('warnings'))
library(ggplot2)
library(gridExtra)
dta9 <- GRD( WSFactors = "Moment(3)", SubjectsPerGroup = 5,
Population = list( mean=20, stddev = 5),
Effects = list("Moment" = slope(3) ) )
expect_message(
truecm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="CM"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="With decorrelation = CM")
)
altcm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="none"),
preprocessfct = "subjectCenteringTransform",
postprocessfct = c("biasCorrectionTransform"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with pre and post processing")
pcm <- grid.arrange(truecm,altcm,ncol=2)
expect_message(
truelm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="LM"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with decorrelation = LM")
)
altlm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="none"),
preprocessfct = "subjectCenteringTransform",
postprocessfct = c("biasCorrectionTransform","poolSDTransform"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with pre and post processing")
plm <- grid.arrange(truelm,altlm,ncol=2)
expect_message(
truecmvslm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="LM"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with decorrelation = LM")
)
expect_message( altcmvslm <- superbPlot(dta9, WSFactor = "moment(3)",
adjustments=list(decorrelation="CM"),
postprocessfct = c("poolSDTransform"),
errorbar = "CI", showPlot=T,
variables = c("DV.1","DV.2","DV.3")
)+ labs(title="with decorrelation = CM and pooling")
)
pcmvslm <- grid.arrange(truecmvslm,altcmvslm,ncol=2)
expect_equal( "ggplot" %in% class(truecm), TRUE)
expect_equal( "ggplot" %in% class(altcm), TRUE)
expect_equal( "ggplot" %in% class(truelm), TRUE)
expect_equal( "ggplot" %in% class(altlm), TRUE)
expect_equal( "ggplot" %in% class(truecmvslm), TRUE)
expect_equal( "ggplot" %in% class(altcmvslm), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Many tests with TMB1964r", {
options(superb.feedback = c('none'))
library(ggplot2)
mee = TMB1964r[TMB1964r$Language == "English"|TMB1964r$Language == "French",]
mp <- function(style, ...) {
superbPlot(mee,
WSFactor = "T(7)",
BSFactor = c("Condition","Sex"),
variables = c("T1","T2","T3","T4","T5","T6","T7"),
adjustments = list(purpose="difference", decorrelation="CM"),
plotStyle = style,
...
)
}
plt1 <- mp("bar",
errorbarParams = list(size=0.75, position = position_dodge(.95) ),
barParams = list(size=0.5)
) +
scale_colour_manual( name = "asdf",
labels = c("Context 0", "Context 2", "Context 4", "Context 8"),
values = c("blue", "black", "purple", "red")) +
scale_fill_manual( name = "asdf",
labels = c("Context 0", "Context 2", "Context 4", "Context 8"),
values = c("blue", "black", "purple", "red")) +
theme_bw(base_size = 16) +
labs(x = "Exposure duration (ms)", y = "Mean of correct responses" )+
scale_x_discrete(labels=c("1" = "16.67", "2" = "33.33",
"3"="50.00", "4" = "66.67", "5"="83.33", "6"="100.00", "7"="116.67"))
plt2 <- mp("line",
errorbarParams = list(size=0.75, width = 0.2, position = position_dodge(.5) ),
pointParams = list(size=2.5, position = position_dodge(.5)),
lineParams = list(size=0.25)
)
plt3 <- mp("point",
errorbarParams = list(position = position_dodge(.5) ),
pointParams = list(size=2.5, position = position_dodge(.5))
)
plt4 <- mp("pointjitter",
errorbarParams = list(position = position_dodge(.5) ),
pointParams = list(size=3.5, position = position_dodge(.5)),
jitterParams = list(size = 0.5)
)
plt5 <- mp("pointjitterviolin",
errorbarParams = list(position = position_dodge(.5) ),
pointParams = list(size=3.5, position = position_dodge(.5)),
jitterParams = list(size = 0.5),
violinParams = list(alpha =0.7)
)
expect_equal( "ggplot" %in% class(plt1), TRUE)
expect_equal( "ggplot" %in% class(plt2), TRUE)
expect_equal( "ggplot" %in% class(plt3), TRUE)
expect_equal( "ggplot" %in% class(plt4), TRUE)
expect_equal( "ggplot" %in% class(plt5), TRUE)
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Heterogeneous variances", {
options(superb.feedback = c('none'))
dta <- GRD(
BSFactors = "dif(3) : grp (2)",
WSFactors="day(1,2)",
SubjectsPerGroup = 3,
Population=list(
mean = 100,
scores = "rnorm(1, mean = GM, sd = 100 * (grp-1) +0.1)"
)
)
options(superb.feedback = c('warnings'))
expect_message(
superbPlot(dta,
BSFactor = c("dif","grp"),
WSFactor = "day(2)",
variables = c("DV.1","DV.2"),
adjustment = list( purpose = "difference") )
)
plt <- superbPlot(dta,
BSFactor = c("dif","grp"),
WSFactor = "day(2)",
variables = c("DV.1","DV.2"),
adjustment = list( purpose = "tryon") )
expect_equal( "ggplot" %in% class(plt), TRUE )
options(superb.feedback = c('design','warnings','summary'))
})
test_that("Tryon vs. difference", {
options(superb.feedback = c('warnings'))
dta <-GRD( BSFactors="grp(3)",
RenameDV = "score",
Population=list(
mean = 100,
scores = "rnorm(1, mean = GM, sd = 10 * grp)"
),
SubjectsPerGroup = 50,
Effects = list("grp" = slope(15) )
)
expect_message(plt1 <- superbPlot(dta,
BSFactor = "grp", plotStyle="line",
variables = "score",
errorbarParams = list(color="blue",position = position_nudge(-0.1) ),
adjustments = list( purpose = "difference") ) +
labs(title="(blue) Difference-adjusted 95% confidence intervals\n(red) Tryon 95% confidence intervals") +
coord_cartesian( ylim = c(65,135) ) +
theme(panel.background = element_rect(fill = "transparent"),
plot.background = element_rect(fill = "transparent", color = "white"))
)
plt2 <- superbPlot(dta,
BSFactor = c("grp"), plotStyle="line",
variables = "score",
errorbarParams = list(color="red",position = position_nudge(+0.1) ),
adjustments = list( purpose = "tryon") ) +
labs(title="(blue) Difference-adjusted 95% confidence intervals\n(red) Tryon 95% confidence intervals") +
coord_cartesian( ylim = c(65,135) ) +
theme(panel.background = element_rect(fill = "transparent"),
plot.background = element_rect(fill = "transparent", color = "white"))
plt1g <- ggplotGrob(plt1)
plt2g <- ggplotGrob(plt2)
plt <- ggplot() +
annotation_custom(grob=plt1g) +
annotation_custom(grob=plt2g)
expect_equal( "ggplot" %in% class(plt), TRUE)
options(superb.feedback = c('design','warnings','summary'))
}) |
semana.absoluta <- function(i.semana, i.semana.inicio) {
return((i.semana <= 53 - i.semana.inicio) * (i.semana + i.semana.inicio - 1) + (i.semana > 53 - i.semana.inicio) * (i.semana + i.semana.inicio - 53))
} |
effecube <- function(paravec,dati,m){
tauno<-dati[,1]
freq<-dati[,2]
return(-sum(freq*tauno*log(betar(m,paravec[1],paravec[2]))))
} |
fix_factor_levels = function(data, levels, ...) {
UseMethod("fix_factor_levels")
}
fix_factor_levels.data.table = function(data, levels, ...) {
levels = levels[intersect(names(levels), names(data))]
iwalk(levels, function(lvls, id, data) {
x = data[[id]]
if (!identical(levels(x), lvls)) {
set(data, j = id, value = factor(x, levels = lvls, ordered = is.ordered(x)))
}
}, data = data)
data[]
}
fix_factor_levels.Matrix = function(data, levels, ...) {
levels = levels[intersect(names(levels), names(data))]
if (length(levels)) {
stop("Factor handling in Matrix data is not supported")
}
data
} |
seriesAccel <- function(x)
{
diff(x, diff=2L, na.pad=TRUE) > 0
}
seriesDecel <- function(x)
{
diff(x, diff=2L, na.pad=TRUE) < 0
}
seriesIncr <- function(x, thresh=0, diff.=1L)
{
diff(x, diff=diff., na.pad=TRUE) > thresh
}
seriesDecr <- function(x, thresh=0, diff.=1L)
{
diff(x, diff=diff., na.pad=TRUE) < thresh
}
`seriesHi` <-
function(x) {
UseMethod("seriesHi")
}
`seriesHi.default` <-
function(x) {
if(!is.null(dim(x)[2])) {
if(dim(x)[2]==1) {
return(x[which(max(x)==as.numeric(x))])
} else {
return(x[which(max(Hi(x))==as.numeric(Hi(x)))])
}
}
max(x,na.rm=TRUE)
}
`seriesHi.timeSeries` <-
function(x) {
x.Data <- x@Data
if(!is.null(dim(x)[2])) {
if(dim(x)[2]==1) {
return(x[which(max(as.numeric(x.Data))==as.numeric(x.Data))])
} else {
return(x[which(max(as.numeric(Hi(x)@Data))==as.numeric(Hi(x)@Data))])
}
}
}
`seriesHi.ts` <-
function(x) {
if(!is.null(dim(x)[2])) {
return(x[which(max(Hi(x),na.rm=TRUE)==Hi(x)),])
}
max(x,na.rm=TRUE)
}
`seriesLo` <-
function(x) {
UseMethod("seriesLo")
}
`seriesLo.default` <-
function(x) {
if(!is.null(dim(x)[2])) {
if(dim(x)[2]==1) {
return(x[which(min(x)==as.numeric(x))])
} else {
return(x[which(min(Lo(x))==as.numeric(Lo(x)))])
}
}
min(x,na.rm=TRUE)
}
`seriesLo.timeSeries` <-
function(x) {
x.Data <- x@Data
if(!is.null(dim(x)[2])) {
if(dim(x)[2]==1) {
return(x[which(min(as.numeric(x.Data))==as.numeric(x.Data))])
} else {
return(x[which(min(as.numeric(Lo(x)@Data))==as.numeric(Lo(x)@Data))])
}
}
}
`seriesLo.ts` <-
function(x) {
if(!is.null(dim(x)[2])) {
return(x[which(min(Lo(x),na.rm=TRUE)==Lo(x)),])
}
min(x,na.rm=TRUE)
}
`is.OHLC` <-
function (x)
{
if(all(has.Op(x), has.Hi(x), has.Lo(x), has.Cl(x)))
{
TRUE
} else FALSE
}
`is.HLC` <-
function(x)
{
all(has.Hi(x),has.Lo(x),has.Cl(x))
}
is.OHLCV <- function(x)
{
all(has.Op(x),has.Hi(x),has.Lo(x),has.Cl(x),has.Vo(x))
}
`has.OHLC` <-
function(x,which=FALSE)
{
if(which) {
c(has.Op(x,1),has.Hi(x,1),has.Lo(x,1),has.Cl(x,1))
} else {
c(has.Op(x),has.Hi(x),has.Lo(x),has.Cl(x))
}
}
has.OHLCV <- function(x,which=FALSE)
{
if(which) {
c(has.Op(x,1),has.Hi(x,1),has.Lo(x,1),has.Cl(x,1),has.Vo(x,1))
} else {
c(has.Op(x),has.Hi(x),has.Lo(x),has.Cl(x),has.Vo(x))
}
}
`has.HLC` <-
function(x,which=FALSE)
{
if(which) {
c(has.Hi(x,1),has.Lo(x,1),has.Cl(x,1))
} else {
c(has.Hi(x),has.Lo(x),has.Cl(x))
}
}
`HLC` <-
function(x)
{
if(is.HLC(x))
return(x[,has.HLC(x,1)])
NULL
}
`OHLC` <-
function(x)
{
if(is.OHLC(x))
return(x[,has.OHLC(x,1)])
NULL
}
OHLCV <- function(x)
{
if(is.OHLCV(x))
return(x[,has.OHLCV(x,1)])
NULL
}
`Op` <-
function(x)
{
if(has.Op(x))
return(x[,grep('Open',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "Open"')
}
`has.Op` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Op")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('Open',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`Hi` <-
function(x)
{
if(has.Hi(x))
return(x[,grep('High',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "High"')
}
`has.Hi` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Hi")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('High',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`Lo` <-
function(x)
{
if(has.Lo(x))
return(x[,grep('Low',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "Low"')
}
`has.Lo` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Lo")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('Low',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`Cl` <-
function(x)
{
if(has.Cl(x))
return(x[,grep('Close',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "Close"')
}
`has.Cl` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Cl")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('Close',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`Vo` <-
function(x)
{
if(has.Vo(x))
return(x[,grep('Volume',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "Volume"')
}
`has.Vo` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Vo")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('Volume',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`Ad` <-
function(x)
{
if(has.Ad(x))
return(x[,grep('Adjusted',colnames(x),ignore.case=TRUE)])
stop('subscript out of bounds: no column name containing "Adjusted"')
}
`has.Ad` <-
function(x,which=FALSE)
{
colAttr <- attr(x, "Ad")
if(!is.null(colAttr))
return(if(which) colAttr else TRUE)
loc <- grep('Adjusted',colnames(x),ignore.case=TRUE)
if(!identical(loc,integer(0))) {
return(if(which) loc else TRUE)
} else FALSE
}
`OpCl` <-
function(x)
{
xx <- Delt(Op(x),Cl(x))
colnames(xx) <- paste("OpCl",deparse(substitute(x)),sep='.')
xx
}
`OpOp` <-
function(x)
{
xx <- Delt(Op(x))
colnames(xx) <- paste("OpOp",deparse(substitute(x)),sep='.')
xx
}
`ClCl` <-
function(x)
{
xx <- Delt(Cl(x))
colnames(xx) <- paste("ClCl",deparse(substitute(x)),sep='.')
xx
}
`OpLo` <-
function(x)
{
xx <- Delt(Op(x),Lo(x))
colnames(xx) <- paste("OpLo",deparse(substitute(x)),sep='.')
xx
}
`OpHi` <-
function(x)
{
xx <- Delt(Op(x),Hi(x))
colnames(xx) <- paste("OpHi",deparse(substitute(x)),sep='.')
xx
}
`LoHi` <-
function(x)
{
xx <- Delt(Lo(x),Hi(x))
colnames(xx) <- paste("LoHi",deparse(substitute(x)),sep='.')
xx
}
`LoCl` <-
function(x)
{
xx <- Delt(Lo(x),Cl(x))
colnames(xx) <- paste("LoCl",deparse(substitute(x)),sep='.')
xx
}
`HiCl` <-
function(x)
{
xx <- Delt(Hi(x),Cl(x))
colnames(xx) <- paste("HiCl",deparse(substitute(x)),sep='.')
xx
}
`Next` <-
function(x,k=1)
{
UseMethod("Next")
}
`Next.data.frame` <-
function(x,k=1)
{
if(k<0||k!=as.integer(k)||length(k)>1) stop("k must be a non-negative integer")
if(k==0) return(x);
new.x <- as.data.frame(c(x[-(0:k),],rep(NA,k)))
rownames(new.x) <- rownames(x)
colnames(new.x) <- "Next"
return(new.x)
}
`Next.quantmod.OHLC` <-
function(x,k=1)
{
if(k<0||k!=as.integer(k)||length(k)>1) stop("k must be a non-negative integer")
if(k==0) return(x);
new.x <- as.matrix(c(as.numeric(x[-(0:k),]),rep(NA,k)))
x.index <- index(x)
new.x <- zoo(new.x,x.index)
colnames(new.x) <- "Next"
return(new.x)
}
`Next.zoo` <- Next.quantmod.OHLC
`Next.numeric` <-
function(x,k=1)
{
if(k<0||k!=as.integer(k)||length(k)>1) stop("k must be a non-negative integer")
if(k==0) return(x);
new.x <- as.matrix(c(as.numeric(x[-(0:k)]),rep(NA,k)))
colnames(new.x) <- "Next"
return(new.x)
}
`Lag` <-
function(x,k=1)
{
UseMethod("Lag")
}
`Lag.data.frame`<-
function(x,k=1)
{
new.x <- sapply(as.list(k), function(k.e) {
if(k.e<0||k.e!=as.integer(k.e)) stop("k must be a non-negative integer")
if(k.e==0) return(x);
c(rep(NA,k.e),x[-((nrow(x)-k.e+1):nrow(x)),])
}
)
rownames(new.x) <- rownames(x)
colnames(new.x) <- paste("Lag.",k,sep="")
return(new.x)
}
`Lag.quantmod.OHLC` <-
function(x,k=1)
{
new.x <- sapply(as.list(k), function(k.e) {
if(k.e<0||k.e!=as.integer(k.e)) stop("k must be a non-negative integer")
if(k.e==0) return(coredata(x));
c(rep(NA,k.e),x[-((length(x)-k.e+1):length(x))])
}
)
x.index <- index(x)
if(inherits(x,'xts')) {
new.x <- xts(new.x,x.index)
} else {
new.x <- zoo(new.x,x.index)
}
dim(new.x) <- c(NROW(new.x),length(k))
colnames(new.x) <- paste("Lag.",k,sep="")
return(new.x)
}
`Lag.zoo` <- `Lag.xts` <- Lag.quantmod.OHLC
`Lag.numeric` <-
function(x,k=1)
{
new.x <- sapply(as.list(k), function(k.e) {
if(k.e<0||k.e!=as.integer(k.e)) stop("k must be a non-negative integer")
if(k.e==0) return(x);
c(rep(NA,k.e),x[-((length(x)-k.e+1):length(x))])
}
)
dim(new.x) <- c(NROW(new.x),length(k))
colnames(new.x) <- paste("Lag.",k,sep="")
return(new.x)
}
`Lag.default`<-
function(x,k=1)
{
if(is.character(x)) stop("x must be a time series or numeric vector")
lag(x,k)
}
Delt_ <-
function(x1,x2=NULL,k=0,type=c('arithmetic','log'))
{
x1 <- try.xts(x1, error=FALSE)
type <- match.arg(type[1],c('log','arithmetic'))
if(length(x2)!=length(x1) && !is.null(x2)) stop('x1 and x2 must be of same length');
if(is.null(x2)){
x2 <- x1
if(length(k) < 2) {
k <- max(1,k)
}
}
dim(x2) <- NULL
if(type=='log') {
xx <- lapply(k, function(K.) {
log(unclass(x2)/lag(x1,K.))
})
} else {
xx <- lapply(k, function(K.) {
unclass(x2)/lag(x1,K.)-1
})
}
xx <- do.call("cbind", xx)
colnames(xx) <- paste("Delt",k,type,sep=".")
reclass(xx,x1)
}
`Delt` <-
function(x1,x2=NULL,k=0,type=c('arithmetic','log'))
{
x1 <- try.xts(x1, error=FALSE)
type <- match.arg(type[1],c('log','arithmetic'))
if(length(x2)!=length(x1) && !is.null(x2)) stop('x1 and x2 must be of same length');
if(is.null(x2)){
x2 <- x1
if(length(k) < 2) {
k <- max(1,k)
}
}
dim(x2) <- NULL
if(type=='log') {
xx <- lapply(k, function(K.) {
log(unclass(x2)/Lag(x1,K.))
})
} else {
xx <- lapply(k, function(K.) {
unclass(x2)/Lag(x1,K.)-1
})
}
xx <- do.call("cbind", xx)
colnames(xx) <- paste("Delt",k,type,sep=".")
reclass(xx,x1)
}
.Delt <- function(x1, x2 = NULL, k = 0, type=c("arithmetic","log")) {
x1 <- try.xts(x1, error=FALSE)
type <- match.arg(type[1], c("arithmetic","log"))
if(length(x2) != length(x1) && !is.null(x2))
stop("x1 and x2 must be of the same length")
if(is.null(x2)) {
x2 <- x1
if(length(k) < 2) {
k <- max(1,k)
}
}
if(type=="log") {
xx <- lapply(k, function(K) log(x2/lag(x1, K)))
}
else {
xx <- lapply(k, function(K) (x2 - lag(x1,K)) / lag(x1,K))
}
xx <- do.call(cbind,xx)
colnames(xx) <- paste("Delt",k,type,sep=".")
reclass(xx,x1)
} |
get_contrasts <- function(model,
variable,
newdata = insight::get_data(model),
type = "response",
step_size = 1,
normalize_dydx = FALSE,
numDeriv_method = NULL,
...) {
scall <- substitute(newdata)
if (is.call(scall) && as.character(scall)[1] %in% c("datagrid", "typical", "counterfactual")) {
lcall <- as.list(scall)
if (!any(c("model", "data") %in% names(lcall))) {
lcall <- c(lcall, list("model" = model))
newdata <- eval.parent(as.call(lcall))
}
}
newdata <- sanity_newdata(model, newdata)
if (!"rowid" %in% colnames(newdata)) {
newdata$rowid <- seq_len(nrow(newdata))
}
if (is.factor(newdata[[variable]]) || isTRUE(attr(newdata[[variable]], "factor"))) {
get_contrasts_fun <- get_contrasts_factor
} else if (is.logical(newdata[[variable]])) {
get_contrasts_fun <- get_contrasts_logical
} else if (is.character(newdata[[variable]])) {
get_contrasts_fun <- get_contrasts_character
} else if (is.numeric(newdata[[variable]])) {
get_contrasts_fun <- get_contrasts_numeric
} else {
stop(sprintf("Cannot compute contrasts for variable %s of class %s",
variable,
class(newdata[[variable]])))
}
out <- get_contrasts_fun(model = model,
variable = variable,
newdata = newdata,
type = type,
step_size = step_size,
normalize_dydx = normalize_dydx,
...)
if (!"group" %in% colnames(out)) {
out$group <- "main_marginaleffect"
}
return(out)
}
get_contrasts_logical <- function(model,
newdata,
variable,
type = "response",
...) {
baseline <- newdata
baseline[[variable]] <- FALSE
pred_false <- get_predict(model,
newdata = baseline,
type = type,
...)
baseline[[variable]] <- TRUE
pred_true <- get_predict(model = model,
newdata = baseline,
type = type,
...)
baseline$estimate <- pred_true$predicted - pred_false$predicted
baseline$term <- variable
baseline$contrast <- "TRUE - FALSE"
pred <- baseline[, c("rowid", "term", "contrast", "estimate")]
row.names(pred) <- NULL
if ("posterior_draws" %in% names(attributes(pred_false))) {
attr(pred, "posterior_draws") <- attr(pred_true, "posterior_draws") - attr(pred_false, "posterior_draws")
}
return(pred)
}
get_contrasts_factor <- function(model,
newdata,
variable,
type = "response",
...) {
baseline <- newdata
pred_list <- list()
if (is.factor(baseline[[variable]])) {
levs <- levels(baseline[[variable]])
} else {
original_data <- insight::get_data(model)
if (is.factor(original_data[[variable]])) {
levs <- levels(original_data[[variable]])
} else {
levs <- sort(unique(original_data[[variable]]))
}
}
baseline[[variable]] <- factor(levs[1], levels = levs)
baseline_prediction <- get_predict(model,
newdata = baseline,
type = type,
...)
draws_list <- list()
for (i in 2:length(levs)) {
baseline[[variable]] <- factor(levs[i], levels = levs)
incremented_prediction <- get_predict(model = model,
newdata = baseline,
type = type,
...)
incremented_prediction$term <- variable
incremented_prediction$contrast <- sprintf("%s - %s", levs[i], levs[1])
incremented_prediction$estimate <- incremented_prediction$predicted -
baseline_prediction$predicted
incremented_prediction$predicted <- NULL
pred_list[[i]] <- incremented_prediction
if ("posterior_draws" %in% names(attributes(baseline_prediction))) {
draws_list[[i]] <- attr(incremented_prediction, "posterior_draws") -
attr(baseline_prediction, "posterior_draws")
}
}
pred <- do.call("rbind", pred_list)
draws <- do.call("rbind", draws_list)
cols <- intersect(colnames(pred), c("rowid", "group", "term", "contrast", "estimate"))
row.names(pred) <- NULL
attr(pred, "posterior_draws") <- draws
return(pred)
}
get_contrasts_character <- function(model,
newdata,
variable,
type = "response",
...) {
tmp <- insight::get_data(model)
levs <- sort(unique(tmp[[variable]]))
baseline <- newdata
pred_list <- list()
baseline_prediction <- get_predict(model,
newdata = baseline,
type = type,
...)
draws_list <- list()
for (i in 2:length(levs)) {
pred <- baseline
pred[[variable]] <- levs[i]
incremented_prediction <- get_predict(model = model,
newdata = pred,
type = type,
...)
contr <- as.vector(incremented_prediction$predicted) -
as.vector(baseline_prediction$predicted)
if ("posterior_draws" %in% names(attributes(baseline_prediction))) {
draws_list[[i]] <- attr(incremented_prediction, "posterior_draws") -
attr(baseline_prediction, "posterior_draws")
}
pred$term <- variable
pred$contrast <- sprintf("%s - %s", levs[i], levs[1])
pred$estimate <- contr
pred_list[[i - 1]] <- pred[, c("rowid", "term", "contrast", "estimate")]
}
pred <- do.call("rbind", pred_list)
draws <- do.call("rbind", draws_list)
pred <- pred[, c("rowid", "term", "contrast", "estimate")]
row.names(pred) <- NULL
attr(pred, "posterior_draws") <- draws
return(pred)
}
get_contrasts_numeric <- function(model,
newdata,
variable,
type = "response",
step_size = 1,
normalize_dydx = FALSE,
return_data = FALSE,
...) {
baseline <- newdata
pred_baseline <- get_predict(model,
newdata = baseline,
type = type,
...)
baseline[[variable]] <- baseline[[variable]] + step_size
pred_increment <- get_predict(model,
newdata = baseline,
type = type,
...)
contr <- as.vector(pred_increment$predicted) - as.vector(pred_baseline$predicted)
pred_increment$term <- variable
if (isTRUE(normalize_dydx)) {
contr <- contr / step_size
pred_increment$contrast <- "dydx"
pred_increment$estimate <- contr
} else {
pred_increment$contrast <- sprintf("+%s", step_size)
pred_increment$estimate <- contr
}
pred_increment$predicted <- NULL
out <- pred_increment
if (!isTRUE(return_data)) {
cols <- intersect(colnames(out), c("rowid", "term", "group", "variable", "term", "contrast", "estimate", "conf.low", "conf.high"))
out <- out[, cols]
} else {
out <- merge(out, newdata, all.x = TRUE)
}
if ("posterior_draws" %in% names(attributes(pred_increment))) {
draws <- attr(pred_increment, "posterior_draws") - attr(pred_baseline, "posterior_draws")
if (isTRUE(normalize_dydx)) {
attr(out, "posterior_draws") <- draws / step_size
} else {
attr(out, "posterior_draws") <- draws
}
}
return(out)
} |
MCEstimator <- function(x, ParamFamily, criterion, crit.name,
startPar = NULL,
Infos, trafo = NULL, penalty = 1e20, validity.check = TRUE,
asvar.fct, na.rm = TRUE, ..., .withEvalAsVar = TRUE,
nmsffx = "", .with.checkEstClassForParamFamily = TRUE){
es.call <- match.call()
dots <- match.call(expand.dots = FALSE)$"..."
completecases <- complete.cases(x)
if(na.rm) x <- na.omit(x)
if(!is.numeric(x))
stop(gettext("'x' has to be a numeric vector"))
if(!is(ParamFamily, "ParamFamily"))
stop(gettext("'ParamFamily' has to be of class 'ParamFamily'"))
if(!is.function(criterion))
stop(gettext("'criterion' has to be a function"))
argList <- c(list(x = x, PFam = ParamFamily, criterion = criterion,
startPar = startPar, penalty = penalty))
if(missing(validity.check)) validity.check <- TRUE
argList$validity.check <- validity.check
if(missing(Infos)) Infos <- NULL
argList <- c(argList, Infos = Infos)
argList <- c(argList, check.validity = validity.check )
if(missing(crit.name)) crit.name <- ""
argList <- c(argList, crit.name = crit.name)
if(!is.null(dots)) argList <- c(argList, dots)
res0 <- do.call(mceCalc, argList)
asv <- if("FisherInfo" %in% slotNames(ParamFamily)){
function(ParamFamily, param)
distr::solve(FisherInfo(ParamFamily, param = param))
}else NULL
argList <- c(list(res0, PFam = ParamFamily,
trafo = trafo,
res.name = paste("Minimum", crit.name,
"estimate", sep=" ", collapse=""),
call = quote(es.call),
.withEvalAsVar=.withEvalAsVar,
check.validity = validity.check))
if(!is.null(asv)) argList <- c(argList, asvar.fct = asv)
if(!is.null(dots)) argList <- c(argList, dots)
argList <- c(argList, x = x)
if(any(nmsffx!="")) argList <- c(argList, nmsffx = nmsffx)
res <- do.call(.process.meCalcRes, argList)
res@completecases <- completecases
if(.with.checkEstClassForParamFamily)
res <- .checkEstClassForParamFamily(ParamFamily,res)
return(res)
} |
tendril_cx <- function(data, Treatments) {
data <- data[order(data$StartDay, decreasing = FALSE),]
StartDay <- NULL
old.day <- NULL
mod <- NULL
angsum <- NULL
data$old.day <- c(0, data$StartDay[1:(length(data$StartDay)-1)])
data <- transform(data,
mod = StartDay - old.day,
dir = ifelse(
data$Treat == Treatments[1],
-1 * data$rot.factor,
1 * data$rot.factor
)
)
data <- transform(data, k = as.numeric(mod != 0))
temp <- stats::aggregate(dir ~ StartDay, data = data, sum)
data <- merge(data, temp, by = "StartDay")
data$angsum <- cumsum(data$dir.y * data$k)
data <- transform(data,
cx = complex(modulus = mod,
argument = (pi/2 + angsum * pi/180)))
data$cx <- cumsum(data$cx)
return(data)
} |
`ensemble.bioclim.object` <- function(
x=NULL, p=NULL, fraction=0.9,
quantiles=TRUE,
species.name="Species001",
factors=NULL
)
{
if(is.null(x) == T) {stop("value for parameter x is missing (data.frame or RasterStack object)")}
if(inherits(x, "RasterStack")==F && inherits(x, "data.frame")==F) {stop("x should be a data.frame or RasterStack object")}
if(fraction < 0 || fraction > 1) {stop("fraction should be in range 0-1")}
factors <- as.character(factors)
cutoff <- qnorm(0.5+fraction/2)
probs <- c(0.5-fraction/2, 0.5+fraction/2)
if(inherits(x, "RasterStack")==T && is.null(p)==F) {
clim.values <- data.frame(raster::extract(x, y=p))
if (length(names(x)) == 1) {
xdouble <- raster::stack(x, x)
clim.values <- raster::extract(x=xdouble, y=p)
clim.values <- data.frame(clim.values)
clim.values <- clim.values[, 1, drop=F]
}
names(clim.values) <- names(x)
x <- clim.values
}
if(inherits(x, "data.frame") == F) {
vars <- names(x)
if (length(factors) > 0) {for (i in 1:length(factors)) {vars <- vars[which(names(x) != factors[i])]}}
nv <- length(vars)
lower.limitsq <- upper.limitsq <- lower.limits <- upper.limits <- minima <- maxima <- clim.sd <- clim.median <- clim.mean <- numeric(length=nv)
names(lower.limitsq) <- names(upper.limitsq) <- names(lower.limits) <- names(upper.limits) <- names(minima) <- names(maxima) <- names(clim.sd) <- names(clim.median) <- names(clim.mean) <- vars
for (i in 1:nv) {
vari <- vars[which(vars == names(x)[i])]
raster.focus <- x[[which(vars == names(x)[i])]]
raster::setMinMax(raster.focus)
meanV <- raster::cellStats(raster.focus, 'mean')
sdV <- raster::cellStats(raster.focus, 'sd')
minV <- raster::minValue(raster.focus)
maxV <- raster::maxValue(raster.focus)
lowerV <- as.numeric(raster::quantile(raster.focus, probs=probs[1], na.rm=T))
upperV <- as.numeric(raster::quantile(raster.focus, probs=probs[2], na.rm=T))
medianV <- as.numeric(raster::quantile(raster.focus, probs=0.5, na.rm=T))
lower.limitsq[which(names(lower.limitsq) == vari)] <- lowerV
upper.limitsq[which(names(upper.limitsq) == vari)] <- upperV
clim.mean[which(names(clim.mean) == vari)] <- meanV
clim.sd[which(names(clim.sd) == vari)] <- sdV
minima[which(names(minima) == vari)] <- minV
maxima[which(names(maxima) == vari)] <- maxV
clim.median[which(names(clim.median) == vari)] <- medianV
}
}else{
clim.values <- x
for (i in 1:length(names(clim.values))) {if (is.factor(clim.values[, i]) == T) {factors <- c(factors, names(clim.values)[i])} }
factors <- unique(factors)
if (length(factors) > 0) {for (i in 1:length(factors)) {clim.values <- clim.values[, which(names(clim.values) != factors[i]), drop=F]}}
clim.mean <- apply(clim.values, 2, "mean", na.rm=T)
clim.sd <- apply(clim.values, 2, "sd", na.rm=T)
lower.limitsq <- upper.limitsq <- lower.limits <- upper.limits <- minima <- maxima <- clim.median <- numeric(length=length(clim.mean))
names(lower.limitsq) <- names(upper.limitsq) <- names(lower.limits) <- names(upper.limits) <- names(minima) <- names(maxima) <- names(clim.median) <- names(clim.values)
minima <- apply(clim.values, 2, "min", na.rm=T)
maxima <- apply(clim.values, 2, "max", na.rm=T)
lower.limitsq <- apply(clim.values, 2, "quantile", probs[1], na.rm=T)
upper.limitsq <- apply(clim.values, 2, "quantile", probs[2], na.rm=T)
clim.median <- apply(clim.values, 2, "quantile", 0.5, na.rm=T)
}
if (quantiles == F){
lower.limits <- clim.mean - cutoff*clim.sd
upper.limits <- clim.mean + cutoff*clim.sd
}else{
lower.limits <- lower.limitsq
upper.limits <- upper.limitsq
}
for (i in 1:length(lower.limits)) {
if (lower.limits[i] < minima[i]) {
cat(paste("\n", "WARNING: lower limit of ", lower.limits[i], " for ", names(lower.limits)[i], " was smaller than minimum of ", minima[i], sep = ""))
cat(paste("\n", "lower limit therefore replaced by quantile value of ", lower.limitsq[i], "\n", sep = ""))
lower.limits[i] <- lower.limitsq[i]
}
if (upper.limits[i] > maxima[i]) {
cat(paste("\n", "WARNING: upper limit of ", upper.limits[i], " for ", names(upper.limits)[i], " was larger than maximum of ", maxima[i], sep = ""))
cat(paste("\n", "upper limit therefore replaced by quantile value of ", upper.limitsq[i], "\n", sep = ""))
upper.limits[i] <- upper.limitsq[i]
}
}
return(list(lower.limits=lower.limits, upper.limits=upper.limits, minima=minima, maxima=maxima,
means=clim.mean, medians=clim.median, sds=clim.sd, cutoff=cutoff, fraction=fraction, species.name=species.name))
}
`ensemble.bioclim` <- function(
x=NULL, bioclim.object=NULL,
RASTER.object.name=bioclim.object$species.name, RASTER.stack.name = x@title,
RASTER.format="raster",
KML.out=TRUE, KML.blur=10, KML.maxpixels=100000,
CATCH.OFF=FALSE
)
{
.BiodiversityR <- new.env()
if(is.null(x) == T) {stop("value for parameter x is missing (RasterStack object)")}
if(inherits(x, "RasterStack") == F) {stop("x is not a RasterStack object")}
if (is.null(bioclim.object) == T) {stop("value for parameter bioclim.object is missing (hint: use the ensemble.bioclim.object function)")}
if (KML.out==T && raster::isLonLat(x)==F) {
cat(paste("\n", "NOTE: not possible to generate KML files as Coordinate Reference System (CRS) of stack ", x@title , " is not longitude and latitude", "\n", sep = ""))
KML.out <- FALSE
}
predict.bioclim <- function(object=bioclim.object, newdata=newdata) {
lower.limits <- object$lower.limits
upper.limits <- object$upper.limits
minima <- object$minima
maxima <- object$maxima
newdata <- newdata[, which(names(newdata) %in% names(lower.limits)), drop=F]
result <- as.numeric(rep(NA, nrow(newdata)))
varnames <- names(newdata)
nvars <- ncol(newdata)
for (i in 1:nrow(newdata)) {
datai <- newdata[i,,drop=F]
resulti <- 1
j <- 0
while (resulti > 0 && j <= (nvars-1)) {
j <- j+1
focal.var <- varnames[j]
if (resulti == 1) {
lowerj <- lower.limits[which(names(lower.limits) == focal.var)]
if (datai[, j] < lowerj) {resulti <- 0.5}
upperj <- upper.limits[which(names(upper.limits) == focal.var)]
if (datai[, j] > upperj) {resulti <- 0.5}
}
minj <- minima[which(names(minima) == focal.var)]
if (datai[, j] < minj) {resulti <- 0}
maxj <- maxima[which(names(maxima) == focal.var)]
if (datai[, j] > maxj) {resulti <- 0}
}
result[i] <- resulti
}
p <- as.numeric(result)
return(p)
}
dir.create("ensembles", showWarnings = F)
if (KML.out == T) {dir.create("kml", showWarnings = F)}
if(length(x@title) == 0) {x@title <- "stack1"}
stack.title <- RASTER.stack.name
rasterfull <- paste("ensembles//", RASTER.object.name, "_", stack.title , "_BIOCLIM_orig", sep="")
kmlfull <- paste("kml//", RASTER.object.name, "_", stack.title , "_BIOCLIM_orig", sep="")
if (CATCH.OFF == F) {
tryCatch(bioclim.raster <- raster::predict(object=x, model=bioclim.object, fun=predict.bioclim, na.rm=TRUE,
filename=rasterfull, progress='text', overwrite=TRUE, format=RASTER.format),
error= function(err) {print(paste("prediction of bioclim failed"))},
silent=F)
}else{
bioclim.raster <- raster::predict(object=x, model=bioclim.object, fun=predict.bioclim, na.rm=TRUE,
filename=rasterfull, progress='text', overwrite=TRUE, format=RASTER.format)
}
raster::setMinMax(bioclim.raster)
print(bioclim.raster)
raster::writeRaster(bioclim.raster, filename="working.grd", overwrite=T)
working.raster <- raster::raster("working.grd")
names(working.raster) <- paste(RASTER.object.name, "_", stack.title , "_BIOCLIM_orig", sep="")
raster::writeRaster(working.raster, filename=rasterfull, progress='text', overwrite=TRUE, format=RASTER.format)
if (KML.out == T) {
raster::KML(working.raster, filename=kmlfull, col = c("grey", "blue", "green"), colNA = 0,
blur=KML.blur, maxpixels=KML.maxpixels, overwrite=T, breaks = c(-0.1, 0, 0.5, 1.0))
}
cat(paste("\n", "bioclim raster provided in folder: ", getwd(), "//ensembles", "\n", sep=""))
return(bioclim.raster)
} |
getImplementedConstraints <- function() {
list(
"nonneg" = list(
name = "nonneg",
method = constraintNonNegativity,
params = list(),
params.info = list(),
info = "Non-negativity (sets negative values to zero)"
),
"unimod" = list(
name = "unimod",
method = constraintUnimod,
params = list(tol = 0),
params.info = list(tol = "tolerance (between 0 and 1)"),
info = "Unimodality (forces contribution or spectral profile to have a single maximum)"
),
"closure" = list(
name = "closure",
method = constraintClosure,
params = list(sum = 1),
params.info = list(sum = "value, the data rows should sum up to"),
info = "Closure (forces contributions or spectral profiles sum up to constant value)"
),
"norm" = list(
name = "norm",
method = constraintNorm,
params = list(type = "length"),
params.info = list(type = "type of normalization: 'length', 'area' or 'sum'"),
info = "Normalization (normalize spectra or contributions)"
),
"angle" = list(
name = "angle",
method = constraintAngle,
params = list(weight = 0.05),
params.info = list(weight = "how much of mean will be added: between 0 and 1"),
info = "Angle (increases contrast among resolved spectra or contributions)"
)
)
}
constraints.list <- function() {
constraints <- getImplementedConstraints()
cat("\nList of constraints available for mcrals():\n")
lapply(constraints, function(c) {
cat("\n\n")
fprintf(" %s\n", c$info)
cat(" ---------------\n")
fprintf(" name: '%s'\n", c$name)
if (length(c$params.info) == 0) {
cat(" no parameters required\n")
} else {
cat(" parameters:\n")
for (i in seq_along(c$params.info)) {
fprintf(" '%s': %s\n", names(c$params.info)[i], c$params.info[[i]])
}
}
})
invisible()
}
constraintClosure <- function(x, d, sum = 1) {
stopifnot("Parameter 'sum' should be positive number." = sum > 0 )
rsums <- rowSums(x)
rsums[rsums == 0] <- 1
s <- diag(sum / rsums, nrow(x), nrow(x))
return(s %*% x)
}
constraintUnimod <- function(x, d, tol = 0) {
f <- function(y, max, indseq, step) {
for (i in indseq) {
if (y[i] <= max) {
max <- y[i]
} else if (y[i] > max * (1 + tol)) {
y[i] <- y[i + step]
max <- y[i]
}
}
return(y)
}
peak.ind <- apply(x, 2, which.max)
nvar <- nrow(x)
for (a in seq_len(ncol(x))) {
left_part <- (peak.ind[a] - 1):1
x[, a] <- f(x[, a], max = x[peak.ind[a], a], indseq = left_part, step = +1)
right_part <- (peak.ind[a] + 1):nvar
x[, a] <- f(x[, a], max = x[peak.ind[a], a], indseq = right_part, step = -1)
}
return(x)
}
constraintNonNegativity <- function(x, d) {
x[x < 0] <- 0
return(x)
}
constraintNorm <- function(x, d, type = "length") {
types <- c("area", "length", "sum")
stopifnot("Parameter 'type' should be either 'area', 'length' or 'sum'." = type %in% types )
return(t(prep.norm(t(x), type)))
}
constraintAngle <- function(x, d, weight = 0.05) {
stopifnot("Parameter 'weight' should be between 0 and 1." = weight >= 0 && weight <= 1 )
m <- apply(d, ifelse(nrow(x) == ncol(d), 2, 1), mean)
m <- m / sqrt(sum(m^2))
x <- t(prep.norm(t(x), "length"))
return((1 - weight) * x + matrix(m * weight, nrow(x), ncol(x)))
}
constraint <- function(name, params = NULL, method = NULL) {
if (is.null(method)) {
item <- getImplementedConstraints()[[name]]
stopifnot("Either name of constraint is wrong or you need to provide a method if the
constraint is user defined." = !is.null(item))
if (is.null(params)) params <- item$params
if (length(params) > 0 && !(names(params) %in% names(item$params))) {
stop("Provided constraint parameters have wrong name.")
}
method <- item$method
} else {
res <- tryCatch(
do.call(method, c(matrix(runif(25, 5, 10)), params)),
error = function(m) stop("The method you provided raises an error: \n", m),
warning = function(m) stop("The method you provided raises a warning: \n", m)
)
stopifnot("The method you provided does not return matrix with correct dimension." =
dim(res) == c(5, 10))
}
obj <- list(
name = name,
method = method,
params = params
)
class(obj) <- c("constraint")
return(obj)
}
employ.constraint <- function(obj, x, d, ...) {
return(do.call(obj$method, c(list(x = x, d = d), obj$params)))
} |
spCentroid <- function(x) {
if (class(x)[1] %in% c('SpatialPolygons', 'SpatialPolygonsDataFrame')) {
centroids <- do.call(rbind, lapply(1:length(x), function(j) {
mc <- apply(x[j,]@polygons[[1]]@Polygons[[1]]@coords, 2, mean)
return(data.frame(x=mc[1], y=mc[2], id=j))}))
centroids <- SpatialPointsDataFrame(centroids[,1:2], centroids, proj4string=crs(x))
return(centroids)
} else {
stop('"x" is not of a valid class')
}
} |
library(datapackage.r)
library(testthat)
testthat::context("infer")
test_that('it infers local data package', {
descriptor <- infer(pattern = 'csv', basePath = 'inst/extdata/dp1')
expect_equal(descriptor$profile, 'tabular-data-package')
expect_equal(length(descriptor$resources), 1)
expect_equal(descriptor$resources[[1]]$path, 'data.csv')
expect_equal(descriptor$resources[[1]]$format, 'csv')
expect_equal(descriptor$resources[[1]]$encoding, 'utf-8')
expect_equal(descriptor$resources[[1]]$profile, 'tabular-data-resource')
expect_equal(descriptor$resources[[1]]$schema$fields[[1]]$name, 'name')
expect_equal(descriptor$resources[[1]]$schema$fields[[2]]$name, 'size')
}) |
distinctiveness_alt = function(pres_matrix, dist_matrix, given_range) {
full_matrix_checks(pres_matrix, dist_matrix)
if (!is.numeric(given_range) | is.na(given_range)) {
stop("'given_range' argument should be non-null and numeric")
}
common = species_in_common(pres_matrix, dist_matrix)
pres_matrix = pres_matrix[, common, drop = FALSE]
dist_matrix = dist_matrix[common, common]
if (!is_relative(pres_matrix)) {
warning("Provided object may not contain relative abundances nor ",
"presence-absence\n",
"Have a look at the make_relative() function if it is the case")
}
corr_matrix = dist_matrix
corr_matrix[dist_matrix >= given_range] = 1
corr_matrix[dist_matrix < given_range] = 0
diag(corr_matrix) = 0
index_matrix = pres_matrix %*% (dist_matrix / given_range +
(corr_matrix * (1 - dist_matrix /
given_range)))
if (requireNamespace("Matrix", quietly = TRUE) &
is(pres_matrix, "sparseMatrix")) {
index_matrix[Matrix::which(pres_matrix == 0)] = NA
total_sites = Matrix::rowSums(pres_matrix)
} else {
index_matrix[which(pres_matrix == 0)] = NA
total_sites = rowSums(pres_matrix)
}
denom_matrix = apply(pres_matrix, 2, function(x) total_sites - x)
index_matrix = index_matrix / denom_matrix
index_matrix[denom_matrix == 0 & pres_matrix != 0] = 1
dimnames(index_matrix) = dimnames(pres_matrix)
return(index_matrix)
} |
K1select = c(1:30, 401:430)
K1 = as.matrix(kdata.1[K1select,1:2])
km2 = kmeans(K1, 2)
library(cluster)
kp2 = pam(K1, 2)
selfmade = list(cluster = setNames(rep(c(1,2), each=30), rownames(K1)))
test_that("should give error on non-kmeans data", {
expect_error(ksharp(K1), "must have component")
expect_error(ksharp(1:10), "must have component")
})
test_that("should give error when data has no item names", {
dd = K1
rownames(dd) = NULL
expect_error(ksharp(km2, data=dd), "names")
})
test_that("should give error when running first time without data", {
expect_error(ksharp(km2), "null")
})
test_that("should give error when running on wrong data", {
small = K1[1:4,]
expect_error(ksharp(km2, data=small), "rownames")
})
test_that("should give error when running on wrong data", {
temp = km2
names(temp$cluster) = NULL
expect_error(ksharp(temp, data=K1), "names")
})
test_that("should give error when threshold not in [0,1]", {
expect_error(ksharp(km2, data=K1, threshold=-0.1), "threshold")
expect_error(ksharp(km2, data=K1, threshold=1.5), "threshold")
expect_error(ksharp(km2, data=K1, threshold=NULL), "threshold")
expect_error(ksharp(km2, data=K1, threshold=NA), "threshold")
})
test_that("should accept a numeric data frame", {
i4 = iris[1:100, 1:4]
rownames(i4) = paste0("I", 1:100)
ik = kmeans(i4, 2)
iks = ksharp(ik, data=i4)
expect_is(iks, "ksharp")
expect_is(iks, "kmeans")
})
test_that("should change class and add fields", {
sharp2 = ksharp(km2, data=K1)
expect_is(sharp2, "ksharp")
expect_is(sharp2, "kmeans")
})
test_that("should add medinfo values based on distance to centers", {
sharp2 = ksharp(km2, data=K1)
expect_false("medinfo" %in% names(km2))
expect_true("medinfo" %in% names(sharp2))
expect_equal(length(sharp2$medinfo), 1)
expect_equal(nrow(sharp2$medinfo$widths), nrow(K1))
})
test_that("change cluster values", {
sharp2 = ksharp(km2, threshold=0.4, data=K1)
expect_equal(sort(unique(km2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
})
test_that("can reset threshold based on ksharp objects", {
sharp2a = ksharp(km2, threshold=0, data=K1)
expect_equal(sort(unique(km2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2a$cluster)), c(1,2))
sharp2b = ksharp(sharp2a, threshold=0.5)
expect_equal(sort(unique(sharp2b$cluster)), c(0,1,2))
sharp2c = ksharp(sharp2b, threshold=0)
expect_equal(sort(unique(sharp2c$cluster)), c(1,2))
})
test_that("recompute silhouettes if needed", {
sharp2 = ksharp(km2, threshold=0.3, data=K1, method="sil")
silB = sharp2$silinfo
rownames(silB$widths) = NULL
km2B = km2
km2B$silinfo = silB
sharp2B = ksharp(km2B, threshold=0.3, data=K1, method="sil")
expect_equal(sharp2$silinfo$widths, sharp2B$silinfo$widths)
})
test_that("change clustering, method=silhouette", {
sharp2 = ksharp(km2, threshold=0.3, data=K1, method="silhouette")
expect_equal(sort(unique(km2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
numzeros = as.integer(table(sharp2$cluster)["0"])
expect_equal(numzeros, 0.3*nrow(K1))
})
test_that("change clustering, method=medoid", {
sharp2 = ksharp(km2, threshold=0.3, data=K1, method="medoid")
expect_equal(sort(unique(km2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
numzeros = as.integer(table(sharp2$cluster)["0"])
expect_equal(numzeros, 0.3*nrow(K1))
})
test_that("change clustering, method=neighbor", {
sharp2 = ksharp(km2, threshold=0.3, data=K1, method="neighbor")
expect_equal(sort(unique(km2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
numzeros = as.integer(table(sharp2$cluster)["0"])
expect_equal(numzeros, 0.3*nrow(K1))
})
test_that("absolute value thresholding", {
sharp2rel = ksharp(kp2, threshold=0.3, data=K1, method="neighbor")
sharp2abs = ksharp(kp2, threshold=0.3, data=K1, method="silhouette",
threshold.abs=0.6)
noise.rel = sum(sharp2rel$cluster==0)
noise.abs = sum(sharp2abs$cluster==0)
expect_gt(noise.abs, noise.rel)
})
test_that("absolute value thresholding ignores relative threshold", {
abs1 = ksharp(kp2, threshold=0.1, data=K1, method="neighbor",
threshold.abs=0.4)
abs2 = ksharp(kp2, threshold=0.5, data=K1, method="neighbor",
threshold.abs=0.4)
abs3 = ksharp(kp2, threshold=0.9, data=K1, method="neighbor",
threshold.abs=0.4)
expect_equal(abs1$cluster, abs2$cluster)
expect_equal(abs1$cluster, abs3$cluster)
})
test_that("change pam cluster values", {
sharp2 = ksharp(kp2, threshold=0.4, data=K1)
expect_equal(sort(unique(kp2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
})
test_that("sharpening on pam input requires no data", {
sharp2 = ksharp(kp2, threshold=0.4)
expect_equal(sort(unique(kp2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
})
test_that("change self-made cluster values", {
expect_error(ksharp(selfmade, threshold=0.4))
sharp2 = ksharp(selfmade, threshold=0.4, data=K1)
expect_equal(sort(unique(selfmade$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
})
test_that("change self-made cluster values (omitting data)", {
selfmade2 = selfmade
selfmade2$data = K1
sharp2 = ksharp(selfmade2, threshold=0.4)
expect_equal(sort(unique(selfmade2$cluster)), c(1,2))
expect_equal(sort(unique(sharp2$cluster)), c(0,1,2))
}) |
collaboration_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot",
cut = c(15, 20, 25)) {
data <- qui_stan_c(data)
create_dist(data = data,
metric = "Collaboration_hours",
hrvar = hrvar,
mingroup = mingroup,
return = return,
cut = cut)
}
collab_dist <- collaboration_dist |
skip_if_not_available("dataset")
library(dplyr, warn.conflicts = FALSE)
library(stringr)
tbl <- example_data
tbl$verses <- verses[[1]]
tbl$padded_strings <- stringr::str_pad(letters[1:10], width = 2 * (1:10) + 1, side = "both")
test_that("mutate() is lazy", {
expect_s3_class(
tbl %>% record_batch() %>% mutate(int = int + 6L),
"arrow_dplyr_query"
)
})
test_that("basic mutate", {
compare_dplyr_binding(
.input %>%
select(int, chr) %>%
filter(int > 5) %>%
mutate(int = int + 6L) %>%
collect(),
tbl
)
})
test_that("mutate() with NULL inputs", {
compare_dplyr_binding(
.input %>%
mutate(int = NULL) %>%
collect(),
tbl
)
})
test_that("empty mutate()", {
compare_dplyr_binding(
.input %>%
mutate() %>%
collect(),
tbl
)
})
test_that("transmute", {
compare_dplyr_binding(
.input %>%
select(int, chr) %>%
filter(int > 5) %>%
transmute(int = int + 6L) %>%
collect(),
tbl
)
})
test_that("transmute() with NULL inputs", {
compare_dplyr_binding(
.input %>%
transmute(int = NULL) %>%
collect(),
tbl
)
})
test_that("empty transmute()", {
compare_dplyr_binding(
.input %>%
transmute() %>%
collect(),
tbl
)
})
test_that("transmute() with unsupported arguments", {
expect_error(
tbl %>%
Table$create() %>%
transmute(int = int + 42L, .keep = "all"),
"`transmute()` does not support the `.keep` argument",
fixed = TRUE
)
expect_error(
tbl %>%
Table$create() %>%
transmute(int = int + 42L, .before = lgl),
"`transmute()` does not support the `.before` argument",
fixed = TRUE
)
expect_error(
tbl %>%
Table$create() %>%
transmute(int = int + 42L, .after = chr),
"`transmute()` does not support the `.after` argument",
fixed = TRUE
)
})
test_that("transmute() defuses dots arguments (ARROW-13262)", {
expect_warning(
tbl %>%
Table$create() %>%
transmute(stringr::str_c(chr, chr)) %>%
collect(),
"Expression stringr::str_c(chr, chr) not supported in Arrow; pulling data into R",
fixed = TRUE
)
})
test_that("mutate and refer to previous mutants", {
compare_dplyr_binding(
.input %>%
select(int, verses) %>%
mutate(
line_lengths = nchar(verses),
longer = line_lengths * 10
) %>%
filter(line_lengths > 15) %>%
collect(),
tbl
)
})
test_that("nchar() arguments", {
compare_dplyr_binding(
.input %>%
select(int, verses) %>%
mutate(
line_lengths = nchar(verses, type = "bytes"),
longer = line_lengths * 10
) %>%
filter(line_lengths > 15) %>%
collect(),
tbl
)
compare_dplyr_binding(
.input %>%
select(int, verses) %>%
mutate(
line_lengths = nchar(verses, type = "bytes", allowNA = TRUE),
longer = line_lengths * 10
) %>%
filter(line_lengths > 15) %>%
collect(),
tbl,
warning = paste0(
"In nchar\\(verses, type = \"bytes\", allowNA = TRUE\\), ",
"allowNA = TRUE not supported by Arrow; pulling data into R"
)
)
})
test_that("mutate with .data pronoun", {
compare_dplyr_binding(
.input %>%
select(int, verses) %>%
mutate(
line_lengths = str_length(verses),
longer = .data$line_lengths * 10
) %>%
filter(line_lengths > 15) %>%
collect(),
tbl
)
})
test_that("mutate with unnamed expressions", {
compare_dplyr_binding(
.input %>%
select(int, padded_strings) %>%
mutate(
int,
nchar(padded_strings)
) %>%
filter(int > 5) %>%
collect(),
tbl
)
})
test_that("mutate with reassigning same name", {
compare_dplyr_binding(
.input %>%
transmute(
new = lgl,
new = chr
) %>%
collect(),
tbl
)
})
test_that("mutate with single value for recycling", {
compare_dplyr_binding(
.input %>%
select(int, padded_strings) %>%
mutate(
dr_bronner = 1
) %>%
collect(),
tbl
)
})
test_that("dplyr::mutate's examples", {
compare_dplyr_binding(
.input %>%
select(name, mass) %>%
mutate(
mass2 = mass * 2,
mass2_squared = mass2 * mass2
) %>%
collect(),
starwars
)
compare_dplyr_binding(
.input %>%
select(name, height, mass, homeworld) %>%
mutate(
mass = NULL,
height = height * 0.0328084
) %>%
collect(),
starwars
)
compare_dplyr_binding(
.input %>%
select(name, homeworld, species) %>%
mutate(across(!name, as.factor)) %>%
collect(),
starwars,
warning = "Expression across.*not supported in Arrow"
)
compare_dplyr_binding(
.input %>%
select(name, mass, homeworld) %>%
group_by(homeworld) %>%
mutate(rank = min_rank(desc(mass))) %>%
collect(),
starwars,
warning = TRUE
)
df <- tibble(x = 1, y = 2)
compare_dplyr_binding(
.input %>% mutate(z = x + y) %>% collect(),
df
)
compare_dplyr_binding(
.input %>% mutate(z = x + y, .before = 1) %>% collect(),
df
)
compare_dplyr_binding(
.input %>% mutate(z = x + y, .after = x) %>% collect(),
df
)
df <- tibble(x = 1, y = 2, a = "a", b = "b")
compare_dplyr_binding(
.input %>% mutate(z = x + y, .keep = "all") %>% collect(),
df
)
compare_dplyr_binding(
.input %>% mutate(z = x + y, .keep = "used") %>% collect(),
df
)
compare_dplyr_binding(
.input %>% mutate(z = x + y, .keep = "unused") %>% collect(),
df
)
compare_dplyr_binding(
.input %>% mutate(z = x + y, .keep = "none") %>% collect(),
df
)
compare_dplyr_binding(
.input %>%
select(name, mass, species) %>%
mutate(mass_norm = mass / mean(mass, na.rm = TRUE)) %>%
collect(),
starwars,
warning = "window function"
)
})
test_that("Can mutate after group_by as long as there are no aggregations", {
compare_dplyr_binding(
.input %>%
select(int, chr) %>%
group_by(chr) %>%
mutate(int = int + 6L) %>%
collect(),
tbl
)
compare_dplyr_binding(
.input %>%
select(mean = int, chr) %>%
group_by(chr) %>%
mutate(mean = mean + 6L) %>%
collect(),
tbl
)
expect_warning(
tbl %>%
Table$create() %>%
select(int, chr) %>%
group_by(chr) %>%
mutate(avg_int = mean(int)) %>%
collect(),
"window functions not currently supported in Arrow; pulling data into R",
fixed = TRUE
)
expect_warning(
tbl %>%
Table$create() %>%
select(mean = int, chr) %>%
group_by(chr) %>%
mutate(avg_int = mean(mean)) %>%
collect(),
"window functions not currently supported in Arrow; pulling data into R",
fixed = TRUE
)
})
test_that("handle bad expressions", {
with_language("fr", {
expect_warning(
expect_error(
Table$create(tbl) %>% mutate(newvar = NOTAVAR + 2),
"objet 'NOTAVAR' introuvable"
),
NA
)
})
})
test_that("Can't just add a vector column with mutate()", {
expect_warning(
expect_equal(
Table$create(tbl) %>%
select(int) %>%
mutate(again = 1:10),
tibble::tibble(int = tbl$int, again = 1:10)
),
"In again = 1:10, only values of size one are recycled; pulling data into R"
)
})
test_that("print a mutated table", {
expect_output(
Table$create(tbl) %>%
select(int) %>%
mutate(twice = int * 2) %>%
print(),
"InMemoryDataset (query)
int: int32
twice: double (multiply_checked(int, 2))
See $.data for the source Arrow object",
fixed = TRUE
)
})
test_that("mutate and write_dataset", {
skip_if_not_available("dataset")
first_date <- lubridate::ymd_hms("2015-04-29 03:12:39")
df1 <- tibble(
int = 1:10,
dbl = as.numeric(1:10),
lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2),
chr = letters[1:10],
fct = factor(LETTERS[1:10]),
ts = first_date + lubridate::days(1:10)
)
second_date <- lubridate::ymd_hms("2017-03-09 07:01:02")
df2 <- tibble(
int = 101:110,
dbl = c(as.numeric(51:59), NaN),
lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2),
chr = letters[10:1],
fct = factor(LETTERS[10:1]),
ts = second_date + lubridate::days(10:1)
)
dst_dir <- tempfile()
stacked <- record_batch(rbind(df1, df2))
stacked %>%
mutate(twice = int * 2) %>%
group_by(int) %>%
write_dataset(dst_dir, format = "feather")
expect_true(dir.exists(dst_dir))
expect_identical(dir(dst_dir), sort(paste("int", c(1:10, 101:110), sep = "=")))
new_ds <- open_dataset(dst_dir, format = "feather")
expect_equal(
new_ds %>%
select(string = chr, integer = int, twice) %>%
filter(integer > 6 & integer < 11) %>%
collect() %>%
summarize(mean = mean(integer)),
df1 %>%
select(string = chr, integer = int) %>%
mutate(twice = integer * 2) %>%
filter(integer > 6) %>%
summarize(mean = mean(integer))
)
})
test_that("mutate and pmin/pmax", {
df <- tibble(
city = c("Chillan", "Valdivia", "Osorno"),
val1 = c(200, 300, NA),
val2 = c(100, NA, NA),
val3 = c(0, NA, NA)
)
compare_dplyr_binding(
.input %>%
mutate(
max_val_1 = pmax(val1, val2, val3),
max_val_2 = pmax(val1, val2, val3, na.rm = TRUE),
min_val_1 = pmin(val1, val2, val3),
min_val_2 = pmin(val1, val2, val3, na.rm = TRUE)
) %>%
collect(),
df
)
compare_dplyr_binding(
.input %>%
mutate(
max_val_1 = pmax(val1 - 100, 200, val1 * 100, na.rm = TRUE),
min_val_1 = pmin(val1 - 100, 100, val1 * 100, na.rm = TRUE),
) %>%
collect(),
df
)
}) |
[
{
"title": "The New Edition of the Portfolio Optimization",
"href": "https://www.rmetrics.org/node/187"
},
{
"title": "R/Finance 2013 slides",
"href": "https://systematicinvestor.wordpress.com/2013/05/20/rfinance-2013-slides/"
},
{
"title": "Tufte style visualizations in R using Plotly",
"href": "http://moderndata.plot.ly/tufte-style-visualizations-in-r-using-plotly/"
},
{
"title": "Matching clustering solutions using the ‘Hungarian method’",
"href": "http://things-about-r.tumblr.com/post/36087795708/matching-clustering-solutions-using-the-hungarian"
},
{
"title": "Does mindfulness aid insight problem solving? New study suggest so",
"href": "http://rpsychologist.com/does-mindfulness-aid-insight-problem-solving-skills"
},
{
"title": "India Australia test cricket matches over the years",
"href": "http://www.rcasts.com/2010/10/india-australia-test-cricket-matches.html"
},
{
"title": "Respecting Real-World Decision Making and Rejecting Models That Do Not: No MaxDiff or Best-Worst Scaling",
"href": "http://joelcadwell.blogspot.com/2015/05/respecting-real-world-decision-making.html"
},
{
"title": "Relation of Word Order and Compression Ratio and Degree of Structure",
"href": "http://www.joyofdata.de/blog/relation-of-word-order-and-compression-ratio/"
},
{
"title": "Dual axes time series plots may be ok sometimes after all",
"href": "http://ellisp.github.io/blog/2016/08/18/dualaxes"
},
{
"title": "A budget of classifier evaluation measures",
"href": "http://www.win-vector.com/blog/2016/07/a-budget-of-classifier-evaluation-measures/"
},
{
"title": "13 graphs on Outer Space, Satellites, and Astrophysics made in Python or R",
"href": "http://moderndata.plot.ly/13-graphs-on-outer-space-satellites-and-astrophysics-made-in-python-or-r/"
},
{
"title": "Interpolation and smoothing functions in base R",
"href": "http://blog.revolutionanalytics.com/2015/09/interpolation-and-smoothing-functions-in-base-r.html"
},
{
"title": "R for Publication by Page Piccinini: Lesson 3 – Logistic Regression",
"href": "http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-3-logistic-regression/"
},
{
"title": "Geocode your data using, R, JSON and Google Maps’ Geocoding APIs",
"href": "http://allthingsr.blogspot.com/2012/01/geocode-your-data-using-r-json-and.html"
},
{
"title": "Cointegration, R, Irish Mortgage Debt and Property Prices",
"href": "https://web.archive.org/web/https://timeseriesireland.wordpress.com/2011/05/15/cointegration-r-irish-mortgage-debt-and-property-prices/"
},
{
"title": "Kaleidoscope IIIb (useR! 2011)",
"href": "https://csgillespie.wordpress.com/2011/08/18/kaleidoscope-iiib-user-2011/"
},
{
"title": "Unit root tests and ARIMA models",
"href": "http://robjhyndman.com/hyndsight/unit-root-tests/"
},
{
"title": "R Reshape Package",
"href": "http://www.mathfinance.cn/R-reshape-package/"
},
{
"title": "Two free online courses starting soon: Data Analysis (with R) and Social Network Analysis",
"href": "https://rdatamining.wordpress.com/2013/01/17/two-free-online-courses-starting-soon-data-analysis-with-r-and-social-network-analysis/"
},
{
"title": "Longitudinal analysis: autocorrelation makes a difference",
"href": "http://www.quantumforest.com/2011/10/longitudinal-analysis-autocorrelation-makes-a-difference/"
},
{
"title": "Creating a Business Dashboard in R",
"href": "https://web.archive.org/web/http://fishyoperations.com/r/creating-a-business-dashboards-in-r/"
},
{
"title": "Méthodes de Monte-Carlo avec R",
"href": "https://xianblog.wordpress.com/2010/12/03/methodes-de-monte-carlo-avec-r/"
},
{
"title": "Tips for Making R User Group Videos",
"href": "http://blog.revolutionanalytics.com/2012/09/making-rug-videos.html"
},
{
"title": "The R Backpages 2",
"href": "http://blog.revolutionanalytics.com/2013/11/the-r-backpages-2.html"
},
{
"title": "Listing of Statistics and Machine Learning Conferences",
"href": "https://web.archive.org/web/http://ramhiser.com/blog/2011/06/12/listing-of-statistics-and-machine-learning-conferences/"
},
{
"title": "analyze the censo demografico no brasil (censo) with r and monetdb",
"href": "http://www.asdfree.com/2014/05/analyze-censo-demografico-no-brasil.html"
},
{
"title": "Another view of ordinary regression",
"href": "https://web.archive.org/web/http://pirategrunt.com/2013/07/08/another-view-of-ordinary-regression/"
},
{
"title": "R and the Next Big Thing",
"href": "https://web.archive.org/web/http://blog.revolution-computing.com/2010/04/r-and-the-next-big-thing.html"
},
{
"title": "MCMSki IV, Jan. 6-8, 2014, Chamonix (news
"href": "https://xianblog.wordpress.com/2013/11/26/mcmski-iv-jan-6-8-2014-chamonix-news-12/"
},
{
"title": "Visualize Color Palettes in Interactive 3D Grid (Shiny + RGL)",
"href": "http://www.trestletech.com/2013/01/visualize-color-palettes-in-interactive-3d-grid-shiny-rgl/"
},
{
"title": "Yeah Sure, Maybe, Well … Okay",
"href": "http://www.milktrader.net/2011/03/yeah-sure-maybe-well-okay.html"
},
{
"title": "More Airline Crashes via the Hadleyverse",
"href": "http://rud.is/b/2015/03/31/more-airline-crashes-via-the-hadleyverse/"
},
{
"title": "Because it’s Friday: Religion and reading level",
"href": "http://blog.revolutionanalytics.com/2010/09/religion-and-reading-level.html"
},
{
"title": "Presentations of the seventh Torino R net meeting – 27 Mar 2014",
"href": "http://torinor.net/2014/06/30/presentations-of-the-seventh-torino-r-net-meeting-27-mar-2014/"
},
{
"title": "R Tips: lots of tips for R programming",
"href": "https://rdatamining.wordpress.com/2012/04/26/r-tips-lots-of-tips-for-r-programming/"
},
{
"title": "Happy Thanksgiving from is.R()!",
"href": "http://is-r.tumblr.com/post/36277968787/happy-thanksgiving-from-isr"
},
{
"title": "Data types part 2: Using classes to your advantage",
"href": "http://rforpublichealth.blogspot.com/2012/11/data-types-part-2-using-classes-to-your.html"
},
{
"title": "Working with Bipartite/Affiliation Network Data in R",
"href": "https://solomonmessing.wordpress.com/2012/09/30/working-with-bipartiteaffiliation-network-data-in-r/"
},
{
"title": "Introduce your friends to R",
"href": "http://learningrbasic.blogspot.com/2010/02/introduce-your-friends-to-r.html"
},
{
"title": "UPDATE Multiple postgreSQL Table Records in Parellel",
"href": "https://nerdsrule.co/2013/02/27/update-multiple-postgresql-table-records-in-parellel/"
},
{
"title": "An R debugging example",
"href": "http://www.burns-stat.com/an-r-debugging-example/?utm_source=rss&utm_medium=rss&utm_campaign=an-r-debugging-example"
},
{
"title": "A predictive maintenance solution template with SQL Server R Services",
"href": "http://blog.revolutionanalytics.com/2016/09/r-services-maintenance.html"
},
{
"title": "A majority victory is not that impossible",
"href": "http://ww1.danielmarcelino.com/a-majority-victory-is-not-that-impossible/"
},
{
"title": "Working with themes in Lattice Graphics",
"href": "http://www.wekaleamstudios.co.uk/posts/working-with-themes-in-lattice-graphics/"
},
{
"title": "More operators or more syntax?",
"href": "https://renkun.me/blog/2014/08/23/more-operators-or-more-syntax.html"
},
{
"title": "More fun with boxplots",
"href": "http://www.nomad.priv.at/researchblog/?p=917"
},
{
"title": "How I Learned to Stop Worrying and Love R CMD Check",
"href": "http://juliasilge.com/blog/How-I-Stopped/"
},
{
"title": "RSPerl : Using R from within Perl",
"href": "http://www.compbiome.com/2009/10/rsperl-using-r-from-within-perl.html"
},
{
"title": "Free edX course for R beginners",
"href": "http://blog.revolutionanalytics.com/2015/08/free-edx-course-for-r-beginners.html"
},
{
"title": "R 2.13.1 scheduled for July 8",
"href": "http://blog.revolutionanalytics.com/2011/06/r-2131-scheduled-for-july-8.html"
}
] |
download_csv <- function(tablename, startyear="", endyear="", ..., genesis_db="de", save=TRUE){
argg <- eval(substitute(alist(...)))
baseurl <- set_db2(db=genesis_db)
param <- list(
sequenz='tabelleDownload',
selectionname=tablename,
startjahr = startyear,
endjahr = endyear,
format = 'csv')
param <- c(param,argg)
httrdata <- GET(baseurl, query = param)
str <- content(httrdata, encoding="windows-1252", as = "text")
if( save ){
writeLines(str, file(paste0(tablename,".csv")))
} else{ return(str) }
} |
causality_sh <- function(x, cause = NULL, vcov. = NULL,
boot = FALSE, boot.runs = 100) {
if (inherits(x, "varest")) {
class(x) <- "varest"
} else {
stop("\nPlease provide an object inheriting class 'varest'.\n")
}
x$datamat <- as.data.frame(x$datamat)
result <- vars::causality(x, cause = cause, vcov. = vcov., boot = boot,
boot.runs = boot.runs)
return(result)
} |
sqldf <- function(x, stringsAsFactors = FALSE,
row.names = FALSE, envir = parent.frame(),
method = getOption("sqldf.method"),
file.format = list(), dbname, drv = getOption("sqldf.driver"),
user, password = "", host = "localhost", port,
dll = getOption("sqldf.dll"), connection = getOption("sqldf.connection"),
verbose = isTRUE(getOption("sqldf.verbose"))) {
as.POSIXct.numeric <- function(x, ...)
structure(x, class = c("POSIXct", "POSIXt"))
as.POSIXct.character <- function(x) structure(as.numeric(x),
class = c("POSIXct", "POSIXt"))
as.Date.character <- function(x) structure(as.numeric(x), class = "Date")
as.Date2 <- function(x) UseMethod("as.Date2")
as.Date2.character <- function(x) as.Date.character(x)
as.Date.numeric <- function(x, origin = "1970-01-01", ...) base::as.Date.numeric(x, origin = origin, ...)
as.dates.character <- function(x) structure(as.numeric(x), class = c("dates", "times"))
as.times.character <- function(x) structure(as.numeric(x), class = "times")
name__class <- function(data, ...) {
if (is.null(data)) return(data)
cls <- sub(".*__([^_]+)|.*", "\\1", names(data))
f <- function(i) {
if (cls[i] == "") {
data[[i]]
} else {
fun_name <- paste("as", cls[i], sep = ".")
fun <- mget(fun_name, envir = environment(),
mode = "function", ifnotfound = NA, inherits = TRUE)[[1]]
if (identical(fun, NA)) data[[i]] else {
names(data)[i] <<- sub("__[^_]+$", "", names(data)[i])
fun(data[[i]])
}
}
}
data[] <- lapply(1:NCOL(data), f)
data
}
colClass <- function(data, cls) {
if (is.null(data)) return(data)
if (is.list(cls)) cls <- unlist(cls)
cls <- rep(cls, length = length(data))
f <- function(i) {
if (cls[i] == "") {
data[[i]]
} else {
fun_name <- paste("as", cls[i], sep = ".")
fun <- mget(fun_name, envir = environment(),
mode = "function", ifnotfound = NA, inherits = TRUE)[[1]]
if (identical(fun, NA)) data[[i]] else {
names(data)[i] <<- sub("__[^_]+$", "", names(data)[i])
fun(data[[i]])
}
}
}
data[] <- lapply(1:NCOL(data), f)
data
}
overwrite <- FALSE
request.open <- missing(x) && is.null(connection)
request.close <- missing(x) && !is.null(connection)
request.con <- !missing(x) && !is.null(connection)
request.nocon <- !missing(x) && is.null(connection)
dfnames <- fileobjs <- character(0)
if (!is.list(method)) method <- list(method, NULL)
to.df <- method[[1]]
to.db <- method[[2]]
if (request.close || request.nocon) {
on.exit({
dbPreExists <- attr(connection, "dbPreExists")
dbname <- attr(connection, "dbname")
if (!missing(dbname) && !is.null(dbname) && dbname == ":memory:") {
if (verbose) {
cat("sqldf: dbDisconnect(connection)\n")
}
dbDisconnect(connection)
} else if (!dbPreExists && drv == "sqlite") {
if (verbose) {
cat("sqldf: dbDisconnect(connection)\n")
cat("sqldf: file.remove(dbname)\n")
}
dbDisconnect(connection)
file.remove(dbname)
} else {
for (nam in dfnames) {
if (verbose) {
cat("sqldf: dbRemoveTable(connection, ", nam, ")\n")
}
dbRemoveTable(connection, nam)
}
for (fo in fileobjs) {
if (verbose) {
cat("sqldf: dbRemoveTable(connection, ", fo, ")\n")
}
dbRemoveTable(connection, fo)
}
if (verbose) {
cat("sqldf: dbDisconnect(connection)\n")
}
dbDisconnect(connection)
}
}, add = TRUE)
if (request.close) {
if (identical(connection, getOption("sqldf.connection")))
options(sqldf.connection = NULL)
return()
}
}
if (request.open || request.nocon) {
if (is.null(drv) || drv == "") {
drv <- if ("package:RPostgreSQL" %in% search()) { "PostgreSQL"
} else if ("package:RpgSQL" %in% search()) { "pgSQL"
} else if ("package:RMySQL" %in% search()) { "MySQL"
} else if ("package:RH2" %in% search()) { "H2"
} else "SQLite"
}
drv <- sub("^[Rr]", "", drv)
pkg <- paste("R", drv, sep = "")
if (verbose) {
if (!is.loaded(pkg)) cat("sqldf: library(", pkg, ")\n", sep = "")
library(pkg, character.only = TRUE)
} else library(pkg, character.only = TRUE)
drv <- tolower(drv)
if (drv == "mysql") {
if (verbose) cat("sqldf: m <- dbDriver(\"MySQL\")\n")
m <- dbDriver("MySQL")
if (missing(dbname) || is.null(dbname)) {
dbname <- getOption("RMySQL.dbname")
if (is.null(dbname)) dbname <- "test"
}
connection <- if (missing(dbname) || dbname == ":memory:") {
dbConnect(m)
} else dbConnect(m, dbname = dbname)
dbPreExists <- TRUE
} else if (drv == "postgresql") {
if (verbose) cat("sqldf: m <- dbDriver(\"PostgreSQL\")\n")
m <- dbDriver("PostgreSQL")
if (missing(user) || is.null(user)) {
user <- getOption("sqldf.RPostgreSQL.user")
if (is.null(user)) user <- "postgres"
}
if (missing(password) || is.null(password)) {
password <- getOption("sqldf.RPostgreSQL.password")
if (is.null(password)) password <- "postgres"
}
if (missing(dbname) || is.null(dbname)) {
dbname <- getOption("sqldf.RPostgreSQL.dbname")
if (is.null(dbname)) dbname <- "test"
}
if (missing(host) || is.null(host)) {
host <- getOption("sqldf.RPostgreSQL.host")
if (is.null(host)) host <- "localhost"
}
if (missing(port) || is.null(port)) {
port <- getOption("sqldf.RPostgreSQL.port")
if (is.null(port)) port <- 5432
}
connection.args <- list(m, user = user, password,
dbname = dbname, host = host, port = port)
connection.args.other <- getOption("sqldf.RPostgreSQL.other")
if (!is.null(connection.args.other))
connection.args <- modifyList(connection.args,
connection.args.other)
connection <- do.call("dbConnect", connection.args)
if (verbose) {
cat(sprintf("sqldf: connection <- dbConnect(m, user='%s', password=<...>, dbname = '%s', host = '%s', port = '%s', ...)\n", user, dbname, host, port))
if (!is.null(connection.args.other)) {
cat("other connection arguments:\n")
print(connection.args.other)
}
}
dbPreExists <- TRUE
} else if (drv == "pgsql") {
if (verbose) cat("sqldf: m <- dbDriver(\"pgSQL\")\n")
m <- dbDriver("pgSQL")
if (missing(dbname) || is.null(dbname)) {
dbname <- getOption("RpgSQL.dbname")
if (is.null(dbname)) dbname <- "test"
}
connection <- dbConnect(m, dbname = dbname)
dbPreExists <- TRUE
} else if (drv == "h2") {
if (verbose) cat("sqldf: m <- dbDriver(\"H2\")\n")
m <- dbDriver("H2")
if (missing(dbname) || is.null(dbname)) dbname <- ":memory:"
dbPreExists <- dbname != ":memory:" && file.exists(dbname)
connection <- if (missing(dbname) || is.null(dbname) ||
dbname == ":memory:") {
dbConnect(m, "jdbc:h2:mem:", "sa", "")
} else {
jdbc.string <- paste("jdbc:h2", dbname, sep = ":")
dbConnect(m, jdbc.string)
}
} else {
if (verbose) cat("sqldf: m <- dbDriver(\"SQLite\")\n")
m <- dbDriver("SQLite")
if (missing(dbname) || is.null(dbname)) dbname <- ":memory:"
dbPreExists <- dbname != ":memory:" && file.exists(dbname)
dll <- getOption("sqldf.dll")
if (length(dll) != 1 || identical(dll, FALSE) || nchar(dll) == 0) {
dll <- FALSE
} else {
if (dll == basename(dll)) dll <- Sys.which(dll)
}
options(sqldf.dll = dll)
if (!identical(dll, FALSE)) {
if (verbose) {
cat("sqldf: connection <- dbConnect(m, dbname = \"", dbname,
"\", loadable.extensions = TRUE\n", sep = "")
cat("sqldf: select load_extension('", dll, "')\n", sep = "")
}
connection <- dbConnect(m, dbname = dbname,
loadable.extensions = TRUE)
s <- sprintf("select load_extension('%s')", dll)
dbGetQuery(connection, s)
} else {
if (verbose) {
cat("sqldf: connection <- dbConnect(m, dbname = \"", dbname, "\")\n", sep = "")
}
connection <- dbConnect(m, dbname = dbname)
}
if (verbose) cat("sqldf: initExtension(connection)\n")
initExtension(connection)
}
attr(connection, "dbPreExists") <- dbPreExists
if (missing(dbname) && drv == "sqlite") dbname <- ":memory:"
attr(connection, "dbname") <- dbname
if (request.open) {
options(sqldf.connection = connection)
return(connection)
}
}
if (request.con) {
drv <- if (inherits(connection, "PostgreSQLConnection")) "PostgreSQL"
else if (inherits(connection, "pgSQLConnection")) "pgSQL"
else if (inherits(connection, "MySQLConnection")) "MySQL"
else if (inherits(connection, "H2Connection")) "H2"
else "SQLite"
drv <- tolower(drv)
dbPreExists <- attr(connection, "dbPreExists")
}
engine <- getOption("gsubfn.engine")
if (is.null(engine) || is.na(engine) || engine == "") {
engine <- if (requireNamespace("tcltk", quietly = TRUE)) "tcl" else "R"
} else if (engine == "tcl") requireNamespace("tcltk", quietly = TRUE)
words. <- words <- if (engine == "tcl") {
strapplyc(x, "[[:alnum:]._]+")
} else strapply(x, "[[:alnum:]._]+", engine = "R")
if (length(words) > 0) words <- unique(unlist(words))
is.special <- sapply(
mget(words, envir, "any", NA, inherits = TRUE),
function(x) is.data.frame(x) + 2 * inherits(x, "file"))
dfnames <- words[is.special == 1]
for(i in seq_along(dfnames)) {
nam <- dfnames[i]
if (dbPreExists && !overwrite && dbExistsTable(connection, nam)) {
dfnames <- head(dfnames, i-1)
stop(paste("sqldf:", "table", nam,
"already in", dbname, "\n"))
}
DF <- as.data.frame(get(nam, envir))
if (!is.null(to.db) && is.function(to.db)) DF <- to.db(DF)
if (verbose) cat("sqldf: dbWriteTable(connection, '", nam, "', ", nam, ", row.names = ", row.names, ")\n", sep = "")
dbWriteTable(connection, nam, DF, row.names = row.names)
}
fileobjs <- if (is.null(file.format)) { character(0)
} else {
eol <- if (.Platform$OS.type == "windows") "\r\n" else "\n"
words[is.special == 2]
}
for(i in seq_along(fileobjs)) {
fo <- fileobjs[i]
Filename <- summary(get(fo, envir))$description
if (dbPreExists && !overwrite && dbExistsTable(connection, Filename)) {
fileobjs <- head(fileobjs, i-1)
stop(paste("sqldf:", "table", fo, "from file",
Filename, "already in", dbname, "\n"))
}
args <- c(list(conn = connection, name = fo, value = Filename),
modifyList(list(eol = eol),
file.format))
args <- modifyList(args, as.list(attr(get(fo, envir), "file.format")))
filter <- args$filter
if (!is.null(filter)) {
args$filter <- NULL
Filename.tmp <- tempfile()
args$value <- Filename.tmp
filter.subs <- filter[-1]
if (length(filter.subs) > 0) {
filter.subs <- filter.subs[sapply(names(filter.subs), nzchar)]
}
filter.nms <- names(filter.subs)
filter.tempfiles <- sapply(filter.nms, tempfile)
cmd <- filter[[1]]
for(nm in filter.nms) {
cat(filter.subs[[nm]], file = filter.tempfiles[[nm]])
cmd <- gsub(nm, filter.tempfiles[[nm]], cmd, fixed = TRUE)
}
cmd <- if (nchar(Filename) > 0)
sprintf('%s < "%s" > "%s"', cmd, Filename, Filename.tmp)
else sprintf('%s > "%s"', cmd, Filename.tmp)
if (.Platform$OS.type == "windows") {
cmd <- paste("cmd /c", cmd)
if (FALSE) {
key <- "SOFTWARE\\R-core"
show.error.messages <- getOption("show.error.message")
options(show.error.messages = FALSE)
reg <- try(readRegistry(key, maxdepth = 3)$Rtools$InstallPath)
reg <- NULL
options(show.error.messages = show.error.messages)
if (!is.null(reg) && !inherits(reg, "try-error")) {
Rtools.path <- file.path(reg, "bin", fsep = "\\")
path <- Sys.getenv("PATH")
on.exit(Sys.setenv(PATH = path), add = TRUE)
path.new <- paste(path, Rtools.path, sep = ";")
Sys.setenv(PATH = path.new)
}
}
}
if (verbose) cat("sqldf: system(\"", cmd, "\")\n", sep = "")
system(cmd)
for(fn in filter.tempfiles) file.remove(fn)
}
if (verbose) cat("sqldf: dbWriteTable(", toString(args), ")\n")
do.call("dbWriteTable", args)
}
if (drv == "sqlite" || drv == "mysql" || drv == "postgresql") {
for(xi in x) {
if (verbose) {
cat("sqldf: dbGetQuery(connection, '", xi, "')\n", sep = "")
}
rs <- dbGetQuery(connection, xi)
}
} else {
for(i in seq_along(x)) {
if (length(words.[[i]]) > 0) {
dbGetQueryWords <- c("select", "show", "call", "explain",
"with")
if (tolower(words.[[i]][1]) %in% dbGetQueryWords || drv != "h2") {
if (verbose) {
cat("sqldf: dbGetQuery(connection, '", x[i], "')\n", sep = "")
}
rs <- dbGetQuery(connection, x[i])
} else {
if (verbose) {
cat("sqldf: dbSendUpdate:", x[i], "\n")
}
rs <- get("dbSendUpdate")(connection, x[i])
}
}
}
}
if (is.null(to.df)) to.df <- "auto"
if (is.function(to.df)) return(to.df(rs))
if (identical(to.df, "raw")) return(rs)
if (identical(to.df, "name__class")) return(do.call("name__class", list(rs)))
if (!identical(to.df, "nofactor") && !identical(to.df, "auto")) {
return(do.call("colClass", list(rs, to.df)))
}
row_names_name <- grep("row[_.]names", names(rs), value = TRUE)
if (length(row_names_name) > 1) warning(paste("ambiguity regarding row names:", row_names_name))
row_names_name <- row_names_name[1]
rs <- if (!is.na(row_names_name)) {
if (identical(row.names, FALSE)) {
rs[names(rs) != row_names_name]
} else {
rn <- rs[[row_names_name]]
rs <- rs[names(rs) != row_names_name]
if (all(regexpr("^[[:digit:]]*$", rn) > 0))
rn <- as.integer(rn)
rownames(rs) <- rn
rs
}
} else rs
tab <- do.call("rbind",
lapply(dfnames,
function(dfname) {
df <- get(dfname, envir)
nms <- names(df)
do.call("rbind",
lapply(seq_along(df),
function(j) {
column <- df[[j]]
cbind(dfname, nms[j], toString(class(column)),
toString(levels(column)))
}
)
)
}
)
)
tabu <- unique(tab[,-1,drop=FALSE])
dup <- unname(tabu[duplicated(tabu[,1]), 1])
auto <- function(i) {
cn <- colnames(rs)[[i]]
if (! cn %in% dup &&
(ix <- match(cn, tab[, 2], nomatch = 0)) > 0) {
df <- get(tab[ix, 1], envir)
if (inherits(df[[cn]], "ordered")) {
if (identical(to.df, "auto")) {
u <- unique(rs[[i]])
levs <- levels(df[[cn]])
if (all(u %in% levs))
return(factor(rs[[i]], levels = levels(df[[cn]]),
ordered = TRUE))
else return(rs[[i]])
} else return(rs[[i]])
} else if (inherits(df[[cn]], "factor")) {
if (identical(to.df, "auto")) {
u <- unique(rs[[i]])
levs <- levels(df[[cn]])
if (all(u %in% levs))
return(factor(rs[[i]], levels = levels(df[[cn]])))
else return(rs[[i]])
} else return(rs[[i]])
} else if (inherits(df[[cn]], "POSIXct"))
return(as.POSIXct(rs[[i]]))
else if (inherits(df[[cn]], "times"))
return(as.times.character(rs[[i]]))
else {
asfn <- paste("as",
class(df[[cn]]), sep = ".")
asfn <- match.fun(asfn)
return(asfn(rs[[i]]))
}
}
if (stringsAsFactors && is.character(rs[[i]])) factor(rs[[i]])
else rs[[i]]
}
rs2 <- lapply(seq_along(rs), auto)
rs[] <- rs2
rs
}
read.csv.sql <- function(file, sql = "select * from file",
header = TRUE, sep = ",", row.names, eol, skip, filter, nrows, field.types,
colClasses, dbname = tempfile(), drv = "SQLite", ...) {
file.format <- list(header = header, sep = sep)
if (!missing(eol))
file.format <- append(file.format, list(eol = eol))
if (!missing(row.names))
file.format <- append(file.format, list(row.names = row.names))
if (!missing(skip))
file.format <- append(file.format, list(skip = skip))
if (!missing(filter))
file.format <- append(file.format, list(filter = filter))
if (!missing(nrows))
file.format <- append(file.format, list(nrows = nrows))
if (!missing(field.types))
file.format <- append(file.format, list(field.types = field.types))
if (!missing(colClasses))
file.format <- append(file.format, list(colClasses = colClasses))
pf <- parent.frame()
if (missing(file) || is.null(file) || is.na(file)) file <- ""
tf <- NULL
if ( substring(file, 1, 7) == "http://" ||
substring(file, 1, 8) == "https://" ||
substring(file, 1, 6) == "ftp://" ||
substring(file, 1, 7) == "ftps://" ) {
tf <- tempfile()
on.exit(unlink(tf), add = TRUE)
download.file(file, tf, mode = "wb")
file <- tf
}
p <- proto(pf, file = file(file))
p <- do.call(proto, list(pf, file = file(file)))
sqldf(sql, envir = p, file.format = file.format, dbname = dbname, drv = drv, ...)
}
read.csv2.sql <- function(file, sql = "select * from file",
header = TRUE, sep = ";", row.names, eol, skip, filter, nrows, field.types,
colClasses, dbname = tempfile(), drv = "SQLite", ...) {
if (missing(filter)) {
filter <- if (.Platform$OS.type == "windows")
paste("cscript /nologo", normalizePath(system.file("trcomma2dot.vbs", package = "sqldf")))
else "tr , ."
}
read.csv.sql(file = file, sql = sql, header = header, sep = sep,
row.names = row.names, eol = eol, skip = skip, filter = filter,
nrows = nrows, field.types = field.types,
colClasses = colClasses, dbname = dbname, drv = drv)
} |
make_bag_tree <- function() {
parsnip::set_new_model("bag_tree")
parsnip::set_model_mode("bag_tree", "classification")
parsnip::set_model_mode("bag_tree", "regression")
parsnip::set_model_engine("bag_tree", "classification", "rpart")
parsnip::set_model_engine("bag_tree", "regression", "rpart")
parsnip::set_dependency("bag_tree", "rpart", "rpart")
parsnip::set_dependency("bag_tree", "rpart", "baguette")
parsnip::set_model_arg(
model = "bag_tree",
eng = "rpart",
parsnip = "class_cost",
original = "cost",
func = list(pkg = "baguette", fun = "class_cost"),
has_submodel = FALSE
)
parsnip::set_model_arg(
model = "bag_tree",
eng = "rpart",
parsnip = "tree_depth",
original = "maxdepth",
func = list(pkg = "dials", fun = "tree_depth"),
has_submodel = FALSE
)
parsnip::set_model_arg(
model = "bag_tree",
eng = "rpart",
parsnip = "min_n",
original = "minsplit",
func = list(pkg = "dials", fun = "min_n"),
has_submodel = FALSE
)
parsnip::set_model_arg(
model = "bag_tree",
eng = "rpart",
parsnip = "cost_complexity",
original = "cp",
func = list(pkg = "dials", fun = "cost_complexity"),
has_submodel = FALSE
)
parsnip::set_fit(
model = "bag_tree",
eng = "rpart",
mode = "regression",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "baguette", fun = "bagger"),
defaults = list(base_model = "CART")
)
)
parsnip::set_encoding(
model = "bag_tree",
eng = "rpart",
mode = "regression",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_fit(
model = "bag_tree",
eng = "rpart",
mode = "classification",
value = list(
interface = "formula",
protect = c("formula", "data", "weights"),
func = c(pkg = "baguette", fun = "bagger"),
defaults = list(base_model = "CART")
)
)
parsnip::set_encoding(
model = "bag_tree",
eng = "rpart",
mode = "classification",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_pred(
model = "bag_tree",
eng = "rpart",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(object = quote(object$fit), new_data = quote(new_data))
)
)
parsnip::set_pred(
model = "bag_tree",
eng = "rpart",
mode = "classification",
type = "class",
value = list(
pre = NULL,
post = fix_column_names,
func = c(pkg = NULL, fun = "predict"),
args =
list(
object = quote(object$fit),
new_data = quote(new_data),
type = "class"
)
)
)
parsnip::set_pred(
model = "bag_tree",
eng = "rpart",
mode = "classification",
type = "prob",
value = list(
pre = NULL,
post = fix_column_names,
func = c(pkg = NULL, fun = "predict"),
args = list(object = quote(object$fit), new_data = quote(new_data), type = "prob")
)
)
parsnip::set_model_engine("bag_tree", "classification", "C5.0")
parsnip::set_dependency("bag_tree", "C5.0", "C50")
parsnip::set_dependency("bag_tree", "C5.0", "baguette")
parsnip::set_fit(
model = "bag_tree",
eng = "C5.0",
mode = "classification",
value = list(
interface = "data.frame",
protect = c("x", "y", "weights"),
func = c(pkg = "baguette", fun = "bagger"),
defaults = list(base_model = "C5.0")
)
)
parsnip::set_encoding(
model = "bag_tree",
eng = "C5.0",
mode = "classification",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_model_arg(
model = "bag_tree",
eng = "C5.0",
parsnip = "class_cost",
original = "cost",
func = list(pkg = "baguette", fun = "class_cost"),
has_submodel = FALSE
)
parsnip::set_model_arg(
model = "bag_tree",
eng = "C5.0",
parsnip = "min_n",
original = "minCases",
func = list(pkg = "dials", fun = "min_n"),
has_submodel = FALSE
)
parsnip::set_pred(
model = "bag_tree",
eng = "C5.0",
mode = "classification",
type = "class",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args = list(
object = quote(object$fit),
new_data = quote(new_data),
type = "class"
)
)
)
parsnip::set_pred(
model = "bag_tree",
eng = "C5.0",
mode = "classification",
type = "prob",
value = list(
pre = NULL,
post = fix_column_names,
func = c(fun = "predict"),
args =
list(
object = quote(object$fit),
new_data = quote(new_data),
type = "prob"
)
)
)
} |
mgrcoatt_dist <- function(data,
hrvar = "Organization",
mingroup = 5,
return = "plot") {
myPeriod <-
data %>%
mutate(Date=as.Date(Date, "%m/%d/%Y")) %>%
arrange(Date) %>%
mutate(Start=first(Date), End=last(Date)) %>%
filter(row_number()==1) %>%
select(Start, End)
plot_data <-
data %>%
rename(group = !!sym(hrvar)) %>%
group_by(PersonId) %>%
filter(Meeting_hours>0) %>%
mutate(coattendman_rate = Meeting_hours_with_manager / Meeting_hours) %>%
summarise(periods = n(),
group = first(group), coattendman_rate=mean(coattendman_rate)) %>%
group_by(group) %>%
mutate(Employee_Count = n_distinct(PersonId)) %>%
filter(Employee_Count >= mingroup)
plot_data <-
plot_data %>%
mutate(bucket_coattendman_rate =
case_when(coattendman_rate>=0 & coattendman_rate<.25 ~ "0 - 25%",
coattendman_rate>=.25 & coattendman_rate<.5 ~ "25 - 50%",
coattendman_rate>=.50 & coattendman_rate<.75 ~ "50 - 75%",
coattendman_rate>=.75 ~ "75% +"))
plot_legend <-
plot_data %>%
group_by(group) %>%
summarize(Employee_Count=first(Employee_Count)) %>%
mutate(Employee_Count = paste("n=",Employee_Count))
plot_table <-
plot_data %>%
group_by(group, bucket_coattendman_rate) %>%
summarize(Employees=n(),
Employee_Count=first(Employee_Count),
percent= Employees / Employee_Count) %>%
arrange(group, bucket_coattendman_rate)
annot_table <-
plot_legend %>%
dplyr::left_join(plot_table, by = "group")
max_blank <- function(x){
as.character(
c(
scales::percent(
x[1:length(x) - 1]
),
"")
)
}
plot_object <-
plot_table %>%
ggplot(aes(x = group, y=Employees, fill = bucket_coattendman_rate)) +
geom_bar(stat = "identity", position = position_fill(reverse = TRUE)) +
coord_flip() +
scale_y_continuous(expand = c(.01, 0), labels = max_blank, position = "right") +
annotate("text", x = plot_legend$group, y = 1.15, label = plot_legend$Employee_Count, size = 3) +
annotate("rect", xmin = 0.5, xmax = length(plot_legend$group) + 0.5, ymin = 1.05, ymax = 1.25, alpha = .2) +
annotate(x = length(plot_legend$group) + 0.8,
xend = length(plot_legend$group) + 0.8,
y = 0,
yend = 1,
colour = "black",
lwd = 0.75,
geom = "segment") +
scale_fill_manual(name="",
values = c("
theme_wpa_basic() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()) +
labs(title = "Meetings coattended by line manager",
subtitle = paste("Percentage of meetings per person"),
caption = extract_date_range(data, return = "text"))
return_table <-
plot_table %>%
select(group, bucket_coattendman_rate, percent) %>%
spread(bucket_coattendman_rate, percent)
if(return == "table"){
return_table %>%
as_tibble() %>%
return()
} else if(return == "plot"){
return(plot_object)
} else {
stop("Please enter a valid input for `return`.")
}
} |
p_install_version_single_gh <- function(package, version, dependencies = TRUE, ...){
if (!basename(package) %in% p_lib()){
out <- p_install_gh(package, ...)
if (isTRUE(out)) {
message(sprintf(
"\n%s not found in user's library; Version %s was installed",
basename(package), utils::packageVersion(basename(package)))
)
}
return(invisible(out))
} else {
if (p_ver(basename(package)) < version) {
out <- p_install_gh(package, dependencies = dependencies, ...)
if (isTRUE(out)) {
message(sprintf("\n%s was updated to v. %s",
basename(package), utils::packageVersion(basename(package))))
}
return(invisible(out))
} else {
message(sprintf("\nVersion of %s (v. %s) is suitable",
basename(package), utils::packageVersion(basename(package))))
return(invisible(TRUE))
}
}
} |
context("filterPairs")
library(testthat)
data("lacy1989Ped")
ped <- lacy1989Ped
ped$gen <- findGeneration(ped$id, ped$sire, ped$dam)
kmat <- kinship(ped$id, ped$sire, ped$dam, ped$gen)
kin <- kinMatrix2LongForm(kmat, rm.dups = FALSE)
threshold <- 0.1
kin <- filterThreshold(kin, threshold = threshold)
ped$sex <- c("M", "F", "M", "M", "F", "F", "M")
kinNull <- filterPairs(kin, ped, ignore = NULL)
kinFF <- filterPairs(kin, ped, ignore = list(c("F", "F")))
kinMM <- filterPairs(kin, ped, ignore = list(c("M", "M")))
test_that("filterPairs removes the correct pairs", {
expect_equal(nrow(kinNull), 39)
expect_equal(nrow(kinFF), 32)
expect_equal(nrow(kinMM), 23)
expect_equal(nrow(kinFF[kinFF$id1 == "B" & kinFF$id2 == "E", ]), 0)
expect_equal(nrow(kinFF[kinFF$id1 == "B" & kinFF$id2 == "F", ]), 0)
expect_equal(nrow(kinMM[kinMM$id1 == "A" & kinMM$id2 == "D", ]), 0)
}) |
lgcpSim <- function(owin=NULL,
tlim=as.integer(c(0,10)),
spatial.intensity=NULL,
temporal.intensity=NULL,
cellwidth = 0.05,
model.parameters=lgcppars(sigma=2,phi=0.2,theta=1),
spatial.covmodel="exponential",
covpars=c(),
returnintensities=FALSE,
progressbar=TRUE,
ext=2,
plot=FALSE,
ratepow=0.25,
sleeptime=0,
inclusion="touching"){
if (!inherits(tlim,"integer")){
warning("Converting tlim into integer values, see ?as.integer")
tlim <- as.integer(tlim)
}
tlim <- sort(tlim)
if (tlim[1]==tlim[2]){
stop("Length of time interval given by as.integer(tlim) must be >= 1")
}
toffset <- tlim[1]
maxt <- tlim[2] - toffset
sigma <- model.parameters$sigma
phi <- model.parameters$phi
mu <- model.parameters$mu
theta <- model.parameters$theta
if(is.null(owin)){
owin <- owin()
}
if (is.null(temporal.intensity)){
temporal.intensity <- constantInTime(100,tlim)
}
else{
if (!inherits(temporal.intensity,"temporalAtRisk")){
temporal.intensity <- temporalAtRisk(temporal.intensity,tlim)
}
if(!all(tlim==attr(temporal.intensity,"tlim"))){
stop("Incompatible temporal.intensity, integer time limits (tlim and temporal.intensity$tlim) do not match")
}
}
ndivs <- diff(tlim)
tdiff = maxt/ndivs
times <- tdiff/2 + tdiff*(0:(ndivs-1))
mut <- sapply(times+toffset,temporal.intensity)
if (progressbar){
pb <- txtProgressBar(min=1,max=ndivs,style=3)
}
const0 <- 0.05
c2 <- -phi*log(const0)
if (cellwidth>c2/2){
warning(paste("cellwidth should be at least",c2/2,"to get accurate results."))
}
xyt <- ppp(window=owin)
ow <- selectObsWindow(xyt,cellwidth)
xyt <- ow$xyt
M <- ow$M
N <- ow$N
cat(paste("FFT Grid size: [",ext*M," , ",ext*N,"]\n",sep=""))
if(is.null(spatial.intensity)){
spatial <- spatialAtRisk(list(X=seq(xyt$window$xrange[1],xyt$window$xrange[2],length.out=M),Y=seq(xyt$window$yrange[1],xyt$window$yrange[2],length.out=N),Zm=matrix(1/(M*N),M,N)))
}
else{
if(!any(class(spatial.intensity)=="spatialAtRisk")){
spatial <- spatialAtRisk(spatial.intensity)
}
else{
spatial <- spatial.intensity
}
}
study.region <- xyt$window
del1 <- (study.region$xrange[2]-study.region$xrange[1])/M
del2 <- (study.region$yrange[2]-study.region$yrange[1])/N
Mext <- ext*M
Next <- ext*N
mcens <- study.region$xrange[1]+.5*del1+(0:(Mext-1))*del1
ncens <- study.region$yrange[1]+.5*del2+(0:(Next-1))*del2
xg <- mcens[1:M]
yg <- ncens[1:N]
cellarea <- del1*del2
if(inclusion=="centroid"){
cellInside <- inside.owin(x=rep(mcens,Next),y=rep(ncens,each=Mext),w=study.region)
}
else if(inclusion=="touching"){
cellInside <- touchingowin(x=mcens,y=ncens,w=study.region)
}
else{
stop("Invlaid choice for argument 'inclusion'.")
}
cellInside <- as.numeric(matrix(as.logical(cellInside),Mext,Next)[1:M,1:N])
spatialvals <- fftinterpolate(spatial,mcens,ncens,ext=ext)
spatialvals <- spatialvals[1:M,1:N]
spatialvals <- spatialvals*cellInside
spatialvals <- spatialvals / (cellarea*sum(spatialvals))
bcb <- blockcircbase(x=mcens,y=ncens,sigma=sigma,phi=phi,model=spatial.covmodel,additionalparameters=covpars)
Qeigs <- eigenfrombase(inversebase(bcb))
rqe <- sqrt(Qeigs)
irqe <- 1/rqe
if(returnintensities){
intensities <- array(NA,c(M,N,ndivs))
truefield <- array(NA,c(M,N,ndivs))
}
else{
intensities <- NULL
truefield <- NULL
}
cases <- NULL
t <- NULL
Y <- YfromGamma(matrix(rnorm(Mext*Next),Mext,Next),invrootQeigs=irqe,mu=mu)[1:M,1:N]
rate <- as.vector(mut[1]*spatialvals*cellarea*exp(Y))
if(returnintensities){
intensities[,,1] <- rate
truefield[,,1] <- Y
}
cmat <- matrix(rpois(M*N,rate),M,N)
ncases <- sum(cmat)
if(ncases>0){
caseidx <- which(cmat>0)
caseidx <- unlist(sapply(caseidx,function(x){rep(x,cmat[x])}))
cases <- cbind(rep(xg,length(yg)),rep(yg,each=length(xg)))[caseidx,] + cbind(runif(ncases,-del1/2,del1/2),runif(ncases,-del2/2,del2/2))
t <- sort(runif(ncases,times[1]-tdiff/2,times[1]+tdiff/2))
}
if(plot){
rate[rate==0] <- NA
image.plot(xg,yg,matrix(rate,M,N)^ratepow)
points(cases,pch="+",cex=0.5)
Sys.sleep(sleeptime)
}
for(i in 2:ndivs){
Y <- mu*(1-exp(-theta)) + exp(-theta)*Y + sqrt(1-exp(-2*theta))*YfromGamma(matrix(rnorm(Mext*Next),Mext,Next),invrootQeigs=irqe,mu=0)[1:M,1:N]
rate <- as.vector(mut[i]*spatialvals*cellarea*exp(Y))
cmat <- matrix(rpois(M*N,rate),M,N)
ncases <- sum(cmat)
if(ncases>0){
caseidx <- which(cmat>0)
caseidx <- unlist(sapply(caseidx,function(x){rep(x,cmat[x])}))
newcases <- cbind(rep(xg,length(yg)),rep(yg,each=length(xg)))[caseidx,] + cbind(runif(ncases,-del1/2,del1/2),runif(ncases,-del2/2,del2/2))
cases <- rbind(cases,newcases)
t <- c(t,sort(runif(ncases,times[i]-tdiff/2,times[i]+tdiff/2)))
if(plot){
rate[rate==0] <- NA
image.plot(xg,yg,matrix(rate,M,N)^ratepow)
points(newcases,pch="+",cex=0.5)
Sys.sleep(sleeptime)
}
}
if(returnintensities){
intensities[,,i] <- rate
truefield[,,i] <- Y
}
if (progressbar){
setTxtProgressBar(pb,i)
}
}
if (progressbar){
close(pb)
}
if(is.null(t)){
stop("No data generated for chosen parameters")
}
if(!all(inside.owin(cases[,1],cases[,2],owin))){
remidx <- which(!inside.owin(cases[,1],cases[,2],owin))
cases <- cases[-remidx,]
t <- t[-remidx]
}
xyt <- stppp(ppp(x=cases[,1],y=cases[,2],window=owin),t=(t+toffset),tlim=tlim)
attr(xyt,"rejects") <- NULL
attr(xyt,"spatialatrisk") <- spatial
attr(xyt,"temporalfitted") <- mut
attr(xyt,"cellwidth") <- cellwidth
attr(xyt,"sigma") <- sigma
attr(xyt,"phi") <- phi
attr(xyt,"theta") <- theta
attr(xyt,"temporalintensity") <- temporal.intensity
attr(xyt,"temporalfitted") <- mut
attr(xyt,"spatialcovmodel") <- spatial.covmodel
attr(xyt,"covpars") <- covpars
attr(xyt,"ext") <- ext
attr(xyt,"xvals") <- xg
attr(xyt,"yvals") <- yg
attr(xyt,"intensities") <- intensities
attr(xyt,"truefield") <- truefield
attr(xyt,"inclusion") <- inclusion
return(xyt)
} |
hiredis <- function(..., version = NULL) {
config <- redis_config(...)
con <- redis_connection(config)
redis_api(con, version)
}
redis_available <- function(...) {
!inherits(try(hiredis(...), silent = TRUE), "try-error")
} |
addParents <- function(ped) {
sires <- ped$sire
dams <- ped$dam
a1 <- sires[!(sires %in% ped$id) & !is.na(sires)]
a1 <- a1[!duplicated(a1)]
a2 <- dams[!(dams %in% ped$id) & !is.na(dams)]
a2 <- a2[!duplicated(a2)]
a1 <- data.frame(id = a1, stringsAsFactors = FALSE)
a2 <- data.frame(id = a2, stringsAsFactors = FALSE)
ped <- ped[ , !names(ped) %in% "recordStatus"]
ped <- cbind(ped, recordStatus = "original", stringsAsFactors = FALSE)
if (nrow(a1) > 0) {
a1$sire <- NA
a1$dam <- NA
a1$sex <- "M"
a1$recordStatus <- "added"
ped <- rbindFill(ped, a1)
}
if (nrow(a2) > 0) {
a2$sire <- NA
a2$dam <- NA
a2$sex <- "F"
a2$recordStatus <- "added"
ped <- rbindFill(ped, a2)
}
return(ped)
} |
ug_bayes <- hBayesDM_model(
task_name = "ug",
model_name = "bayes",
model_type = "",
data_columns = c("subjID", "offer", "accept"),
parameters = list(
"alpha" = c(0, 1, 20),
"beta" = c(0, 0.5, 10),
"tau" = c(0, 1, 10)
),
regressors = NULL,
postpreds = c("y_pred"),
preprocess_func = ug_preprocess_func) |
spark_read_bigquery <- function(sc, name, billingProjectId = default_billing_project_id(),
projectId = billingProjectId, datasetId = NULL,
tableId = NULL, sqlQuery = NULL, type = default_bigquery_type(),
gcsBucket = default_gcs_bucket(),
serviceAccountKeyFile = default_service_account_key_file(),
additionalParameters = NULL, memory = FALSE, ...) {
if(!(type %in% c("direct", "avro", "json", "csv")))
stop(sprintf("The import type '%s' is not supported by spark_read_bigquery", type))
parameters <- c(list(
"bq.project" = billingProjectId,
"bq.staging_dataset.gcs_bucket" = gcsBucket,
"bq.location" = default_dataset_location(),
"bq.service_account_key_file" = serviceAccountKeyFile,
"type" = type
), additionalParameters)
if(!is.null(datasetId) && !is.null(tableId)) {
parameters[["table"]] <- sprintf("%s.%s.%s", projectId, datasetId, tableId)
} else if(!is.null(sqlQuery)) {
parameters[["sqlQuery"]] <- sqlQuery
} else {
stop("Either both of 'datasetId' and 'tableId' or 'sqlQuery' must be specified.")
}
spark_read_source(
sc,
name = name,
source = "bigquery",
options = parameters,
memory = memory,
...
)
} |
summary.POUMM <- function(object, ...,
startMCMC = NA, endMCMC = NA, thinMCMC = 1000,
stats = statistics(object),
mode = c('short', 'long', 'expert')) {
N <- MLE <- samplePriorMCMC <- HPD <- HPD50 <- ESS <- HPDUpperFiltered <-
HPDLowerFiltered <- value <- HPDUpper <- HPDLower <- it <- PostMean <- mcs <-
ESS <- nChains <- chain <- G.R. <- stat <- Mean <- NULL
mode <- tolower(mode)
tipTimes <- nodeTimes(object$pruneInfo$tree, tipsOnly = TRUE)
tMax <- max(tipTimes)
tMean <- mean(tipTimes)
parLower <- matrix(object$spec$parLower, nrow = 1)
parUpper <- matrix(object$spec$parUpper, nrow = 1)
parML <- matrix(object$fitML$par, nrow = 1)
anlist <- lapply(seq_along(stats), function(i) {
data.table(stat = names(stats)[i], MLE = stats[[i]](parML))
})
anlist <- c(anlist, list(
data.table(stat = "logpost", MLE = NA),
data.table(stat = "loglik", MLE = object$fitML$value),
data.table(stat = "AIC", MLE = AIC(object)),
data.table(stat = "AICc", MLE = AIC(object) + 2*object$dof*(object$dof+1)/(object$N-object$dof-1))
))
an.ML <- rbindlist(anlist)
an.ML[, N:=object$N]
setcolorder(an.ML, c('stat', 'N', 'MLE'))
if(!is.null(object$fitMCMC)) {
if(is.na(startMCMC)) {
startMCMC <- object$spec$nSamplesMCMC / 10
}
if(is.na(endMCMC)) {
endMCMC <- object$spec$nSamplesMCMC
}
anlist <- lapply(seq_along(stats), function(i) {
analyseMCMCs(object$fitMCMC$chains,
stat = stats[[i]], statName = names(stats)[i],
start = startMCMC, end = endMCMC, thinMCMC = thinMCMC,
as.dt = TRUE)
})
anlist <- c(anlist, list(
analyseMCMCs(object$fitMCMC$chains,
stat=NULL, statName='logpost',
start = startMCMC, end=endMCMC, thinMCMC = thinMCMC,
as.dt = TRUE),
analyseMCMCs(object$fitMCMC$chains,
stat = NULL, statName='loglik',
start = startMCMC, end = endMCMC, thinMCMC = thinMCMC,
as.dt = TRUE),
analyseMCMCs(object$fitMCMC$chains,
stat = NULL, statName='AIC',
start = startMCMC, end = endMCMC, thinMCMC = thinMCMC,
as.dt = TRUE, k = object$dof, N = object$N),
analyseMCMCs(object$fitMCMC$chains,
stat = NULL, statName='AICc',
start = startMCMC, end = endMCMC, thinMCMC = thinMCMC,
as.dt = TRUE, k = object$dof, N = object$N)
))
an.MCMC <- rbindlist(anlist)
an.MCMC[, samplePriorMCMC:=rep( c(object$spec$samplePriorMCMC,
rep(FALSE, object$spec$nChainsMCMC - 1)), length.out=.N) ]
if(mode[1] != 'expert') {
an.MCMC <- an.MCMC[,
list(
PostMean = mean(unlist(Mean)),
HPD = list(colMeans(do.call(rbind, HPD))),
HPD50 = list(colMeans(do.call(rbind, HPD50))),
start = start(mcs),
end = end(mcs),
thin = thin(mcs),
ESS = sum(unlist(ESS)),
G.R. = if(length(mcs)>1) {
gelman.diag(mcs, autoburnin=FALSE)$psrf[1]
} else {
as.double(NA)
},
nChains = length(mcs),
mcmc = mcmc.list(mcmc(do.call(rbind, mcs)))),
by=list(stat, samplePriorMCMC)]
}
if(mode[1] == 'short') {
an.MCMC <- an.MCMC[
samplePriorMCMC == FALSE,
list(stat, PostMean, HPD, ESS, G.R.)]
} else if(mode[1] == 'long') {
an.MCMC <- an.MCMC[
samplePriorMCMC == FALSE,
list(stat, PostMean, HPD, HPD50, start, end,
thin = thinMCMC, ESS, G.R., nChains, mcmc)]
} else if(mode[1] == 'expert') {
an.MCMC <- an.MCMC[, list(stat, samplePriorMCMC,
PostMean = Mean, HPD, HPD50, start, end, thin = thinMCMC,
ESS, mcmc = mcs, chain)]
} else {
warning(paste('mode should be one of "short", "long" or "expert", but was', mode[1], '.'))
}
} else {
an.MCMC <- NULL
}
if(mode[1] %in% c('short', 'long')) {
if(!is.null(an.ML) & !is.null(an.MCMC)) {
res <- merge(an.ML, an.MCMC, by = 'stat', all = TRUE, sort = FALSE)
res[sapply(HPD, is.null), HPD:=list(list(as.double(c(NA, NA))))]
if(mode[1] == 'long')
res[sapply(HPD50, is.null), HPD50:=list(list(as.double(c(NA, NA))))]
} else if(!is.null(an.ML)) {
res <- an.ML
} else if(!is.null(an.MCMC)) {
res <- an.MCMC
}
} else {
res <- list(spec = object$spec, startMCMC = startMCMC, endMCMC = endMCMC,
thinMCMC = thinMCMC,
ML = an.ML, MCMC = an.MCMC,
MCMCBetterLik = object$MCMCBetterLik)
}
class(res) <- c('summary.POUMM', class(res))
res
}
generateStatisticFunG0 <- function(object) {
function(par) {
if( 'g0' %in% names(object$spec$parMapping(par)) ) {
object$spec$parMapping(par)[, 'g0']
} else {
g0s <- try(
apply(par, 1, function(par) {
ll <- object$loglik(par, pruneInfo = object$pruneInfo)
attr(ll, "g0")
}), silent = TRUE)
if(inherits(g0s, "try-error")) {
rep(NA_real_, nrow(par))
} else {
g0s
}
}
}
}
plot.summary.POUMM <- function(
x, type = c("MCMC"),
doPlot = TRUE,
stat = c("alpha", "theta", "sigma", "sigmae", "g0", "H2tMean"),
chain = NULL,
doZoomIn = FALSE,
zoomInFilter = paste0("(stat %in% c('H2e','H2tMean','H2tInf','H2tMax') & ",
"(value >= 0 & value <= 1) ) |",
"( !stat %in% c('H2e','H2tMean','H2tInf','H2tMax') & ",
"(value <= median(HPDUpper) + 4 * (median(HPDUpper) - median(HPDLower)) &",
"value >= median(HPDLower) - 4 * (median(HPDUpper) - median(HPDLower))))"),
palette = c("
prettyNames = TRUE,
...) {
N <- MLE <- samplePriorMCMC <- HPD <- HPD50 <- ESS <- HPDUpperFiltered <-
HPDLowerFiltered <- value <- HPDUpper <- HPDLower <- it <- PostMean <- mcs <-
ESS <- nChains <- chain <- G.R. <- stat2 <- statFactor <- NULL
if(inherits(x, "summary.POUMM") && !is.null(x$MCMC)) {
.stat <- stat
.chain <- chain
data <- merge(x$ML, x$MCMC, by = "stat")
data <- data[
{
if(!is.null(.stat)) {stat %in% .stat} else rep(TRUE, .N)
} & {
if(!is.null(.chain)) {chain %in% .chain} else rep(TRUE, .N)
}]
setkey(data, stat)
data <- data[list(.stat)]
data <- data[{
if(!is.null(.stat)) {stat %in% .stat} else rep(TRUE, .N)
} & {
if(!is.null(.chain)) {chain %in% .chain} else rep(TRUE, .N)
}, list(
N,
MLE,
samplePriorMCMC,
HPDLower = sapply(HPD, function(.) .[1]),
HPDUpper = sapply(HPD, function(.) .[2]),
HPD50Lower = sapply(HPD50, function(.) .[1]),
HPD50Upper = sapply(HPD50, function(.) .[2]),
ESS,
value = unlist(mcmc),
it = seq(x$startMCMC, by = x$thinMCMC, along.with = mcmc[[1]])),
by = list(stat = factor(stat), chain = factor(chain))]
if(doZoomIn) {
data[, stat2:=stat]
data <- data[, {
.SD[eval(parse(text = zoomInFilter))]
}, by = stat2]
data[, stat2:=NULL]
}
data[, HPDUpperFiltered:=min(max(value), unique(HPDUpper)),
list(stat = factor(stat), chain = factor(chain))]
data[, HPDLowerFiltered:=max(min(value), unique(HPDLower)),
list(stat = factor(stat), chain = factor(chain))]
.availStats <- data[, as.character(unique(stat))]
statFactorLabels <- if(prettyNames) {
prettifyNames(.availStats)
} else {
.availStats
}
data[, statFactor:=factor(stat, levels = .availStats, labels = statFactorLabels)]
.stat <- .availStats[1]
dtm <- data[stat == .stat, list(stat, it, chain, value)]
dtm[, (.stat) := value]
dtm[, c("stat", "value") := NULL]
for(.stat in .availStats[-1]) {
dtm2 <-
data[stat == .stat,
eval(parse(text=paste0("list(it, chain, ", .stat, ' = value)')))]
dtm <- merge(dtm, dtm2, by=c("it", "chain"), all=TRUE)
}
names(palette) <- as.character(seq_along(palette))
my_ggplot <- function(...) ggplot(...) +
scale_color_manual(values = palette) +
scale_fill_manual(values = palette)
if(type == "MCMC") {
traceplot <- my_ggplot(data) +
geom_line(aes(x=it, y=value, col = chain)) +
facet_wrap(~statFactor,
scales = "free",
labeller = if(prettyNames) "label_parsed" else "label_value")
densplot <- my_ggplot(data) +
geom_density(aes(x=value, fill = chain, col = chain), alpha=0.5) +
geom_segment(aes(x=HPDLowerFiltered, xend=HPDUpperFiltered,
y=0, yend=0, col = chain)) +
geom_point(aes(x=MLE, y=0)) +
facet_wrap(~statFactor,
scales = "free", labeller= if(prettyNames) "label_parsed" else "label_value")
if(doPlot) {
print(traceplot)
if(interactive()) {
print("Press Enter to see a univariate posterior density plot")
scan("", what = "character", nlines = 1)
}
print(densplot)
} else {
list(traceplot = traceplot, densplot = densplot)
}
}
} else {
stop("plot.summary.POUMM called on a non summary.POUMM-object or a missing MCMC element. Verify that summary.POUMM has been called with mode = 'expert'")
}
}
prettifyNames <- function(names) {
prettyNames <- c(alpha = "alpha",
theta = "theta",
g0 = "g[0]",
sigma = "sigma",
sigmae = "sigma[e]",
H2tMean = "H[bar(t)]^2",
H2e = "H[e]^2",
H2tInf = "H[infinity]^2")
sapply(names, function(n) {pn <- prettyNames[n]; if(!is.na(pn)) pn else n}, USE.NAMES = FALSE)
}
statistics <- function(object) {
UseMethod('statistics')
}
statistics.POUMM <- function(object) {
listPar <- sapply(seq_along(object$spec$parLower), function(i) {
name <- names(object$spec$parLower)[i]
stat <- eval(
parse(text=paste0("list(", name, " = function(par) par[, ", i , "])"))
)
})
listOtherStats <- list(
H2e = function(par) H2e(z = object$pruneInfo$z,
sigmae = object$spec$parMapping(par)[, 'sigmae']),
H2tInf = function(par) H2(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
sigmae = object$spec$parMapping(par)[, 'sigmae'],
t = Inf),
H2tMax = function(par) H2(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
sigmae = object$spec$parMapping(par)[, 'sigmae'],
t = object$tMax),
H2tMean = function(par) H2(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
sigmae = object$spec$parMapping(par)[, 'sigmae'],
t = object$tMean),
alpha = function(par) object$spec$parMapping(par)[, 'alpha'],
theta = function(par) object$spec$parMapping(par)[, 'theta'],
sigma = function(par) object$spec$parMapping(par)[, 'sigma'],
sigmae = function(par) object$spec$parMapping(par)[, 'sigmae'],
g0 = generateStatisticFunG0(object),
sigmaG2tMean = function(par) varOU(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
t = object$tMean),
sigmaG2tMax = function(par) varOU(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
t = object$tMax),
sigmaG2tInf = function(par) varOU(alpha = object$spec$parMapping(par)[, 'alpha'],
sigma = object$spec$parMapping(par)[, 'sigma'],
t = Inf))
c(listPar, listOtherStats[setdiff(names(listOtherStats), names(listPar))])
} |
empSE <- function(estimates, get=c("empSE", "empSE_mcse"), na.rm=FALSE, ...){
assertthat::assert_that(length(!is.na(estimates)) > 0)
x <- c()
if(na.rm){
estimates <- estimates[!is.na(estimates)]
}
deviations <- estimates - mean(estimates)
if(any(is.na(deviations))){
x["empSE"] <- NA
x["empSE_mcse"] <- NA
return(x[get])
}
n <- length(deviations)
x["empSE"] <- sqrt(sum(deviations^2) / (n-1))
x["empSE_mcse"] <- x["empSE"]/sqrt(2*(n-1))
return(x[get])
} |
getAttributes <- function(mart, dataset){
if ((!is.character(mart)) || (!is.character(dataset)))
stop("Please use a character string as mart or dataset.",
call. = FALSE)
if (!is.element(mart, getMarts()$mart))
stop("Please select a valid mart with getMarts().", call. = FALSE)
message("Starting retrieval of attribute information from mart ", mart, " and dataset ", dataset, " ...")
if (stringr::str_detect(mart, "ENSEMBL"))
url <-
paste0(
"http://ensembl.org/biomart/martservice?type=attributes&dataset=",
dataset,
"&requestid=biomart&mart=",
mart
)
if (stringr::str_detect(mart, "plants"))
url <-
paste0(
"http://plants.ensembl.org/biomart/martservice?type=attributes&dataset=",
dataset,
"&requestid=biomart&mart=",
mart
)
if (stringr::str_detect(mart, "fung"))
url <-
paste0(
"http://fungi.ensembl.org/biomart/martservice?type=attributes&dataset=",
dataset,
"&requestid=biomart&mart=",
mart
)
if (stringr::str_detect(mart, "protist"))
url <-
paste0(
"http://protist.ensembl.org/biomart/martservice?type=attributes&dataset=",
dataset,
"&requestid=biomart&mart=",
mart
)
if (stringr::str_detect(mart, "metazoa"))
url <-
paste0(
"http://metazoa.ensembl.org/biomart/martservice?type=attributes&dataset=",
dataset,
"&requestid=biomart&mart=",
mart
)
testContent <-
httr::content(httr::GET(url), as = "text", encoding = "UTF-8")
if (testContent == "Attribute 'mains' does not exist\n") {
warning("No attributes were available for mart = ",
mart,
" and dataset = ",
dataset,
".",
call. = FALSE)
attrBioMart <- data.frame(name = "NA", description = "NA")
return(attrBioMart)
}
attributesPage <- httr::handle(url)
xmlContentAttributes <- httr::GET(handle = attributesPage)
httr::stop_for_status(xmlContentAttributes)
suppressWarnings(rawDF <-
do.call("rbind", apply(as.data.frame(strsplit(
httr::content(xmlContentAttributes, as = "text",
encoding = "UTF-8"),
"\n"
)), 1, function(x)
unlist(strsplit(x, "\t")))))
colnames(rawDF) <- paste0("V", seq_len(ncol(rawDF)))
attrBioMart <-
as.data.frame(rawDF[, c("V1", "V2")],
stringsAsFactors = FALSE,
colClasses = rep("character", 2))
colnames(attrBioMart) <- c("name", "description")
return(attrBioMart)
} |
plot_def <- function(result,
cluster = "all",
hotspot = TRUE,
noise = FALSE,
ignition = TRUE,
from = NULL,
to = NULL,
bg = NULL) {
if (!"spotoroo" %in% class(result)) {
stop('Needs a "spotoroo" object as input.')
}
aes <- ggplot2::aes
geom_point <- ggplot2::geom_point
labs <- ggplot2::labs
theme <- ggplot2::theme
theme_bw <- ggplot2::theme_bw
ggplot <- ggplot2::ggplot
element_blank <- ggplot2::element_blank
unit <- ggplot2::unit
scale_color_brewer <- ggplot2::scale_color_brewer
filter <- dplyr::filter
lon <- lat <- membership <- NULL
check_type_bundle("logical", hotspot, ignition, noise)
is_length_one_bundle(hotspot, ignition, noise)
if (!identical("all", cluster)){
check_type("numeric", cluster)
if (length(cluster) == 0) stop("Please provide valid membership labels.")
indexes <- result$ignition$membership %in% cluster
result$ignition <- result$ignition[indexes, ]
indexes <- result$hotspots$membership %in% c(cluster, -1)
result$hotspots <- result$hotspots[indexes, ]
}
if (!is.null(from)) {
is_length_one(from)
indexes <- result$ignition$obsTime >= from
result$ignition <- result$ignition[indexes, ]
indexes <- result$hotspots$obsTime >= from
result$hotspots <- result$hotspots[indexes, ]
if (nrow(result$hotspots) == 0) {
stop(paste("No hot spots/noise observed later than", from))
}
}
if (!is.null(to)) {
is_length_one(to)
indexes <- result$ignition$obsTime <= to
result$ignition <- result$ignition[indexes, ]
indexes <- result$hotspots$obsTime <= to
result$hotspots <- result$hotspots[indexes, ]
if (nrow(result$hotspots) == 0) {
stop(paste("No hot spots/noise observed ealier than", from))
}
}
if (ggplot2::is.ggplot(bg)) {
p <- bg
} else {
p <- ggplot() +
theme_bw(base_size = 9) +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
panel.spacing = unit(0, "lines"),
plot.background = element_blank(),
legend.justification = c(0, 0),
legend.position = c(0, 0))
}
if (length(unique(result$hotspots$membership)) <= 9) {
if (hotspot) {
p <- p + geom_point(data = filter(result$hotspots,
!noise),
aes(lon,
lat,
col = as.character(membership)),
alpha = 0.4,
size = 1.5)
}
if (noise) {
p <- p + geom_point(data = filter(result$hotspots,
noise),
aes(lon,
lat),
col = "black",
alpha = 0.2,
size = 1.5)
}
if (ignition & length(unique(result$hotspots$membership)) > 1) {
p <- p +
geom_point(data = result$ignition,
aes(lon,
lat),
col = "black",
size = 1.5)
}
p <- p + scale_color_brewer(palette = "Set1") +
theme(legend.position = "none") +
labs(col = "")
} else {
if (hotspot) {
p <- p + geom_point(data = filter(result$hotspots,
!noise),
aes(lon,
lat),
col = "black",
alpha = 0.4,
size = 1.5)
}
if (noise) {
p <- p + geom_point(data = filter(result$hotspots,
noise),
aes(lon,
lat),
col = "blue",
alpha = 0.2,
size = 1.5)
}
if (ignition) {
p <- p +
geom_point(data = result$ignition,
aes(lon,
lat),
col = "red",
size = 1.5)
}
p <- p +
theme(legend.position = "none") +
labs(col = "")
}
title <- paste("Fires Selected:", nrow(result$ignition), "\n")
left <- min(result$hotspots$obsTime)
right <- max(result$hotspots$obsTime)
if (!is.null(from)) left <- from
title <- paste0(title, "From: ", left, "\n")
if (!is.null(to)) right <- to
title <- paste0(title, "To: ", right)
title2 <- "Overview of Fires"
if (ignition) title2 <- paste0(title2, " and Ignition Locations")
p <- p + labs(title = title2,
subtitle = title)
return(p)
} |
previous_quarter <-
function(x = Sys.Date(),
n = 1,
part = getOption("timeperiodsR.parts")) {
if ( ! "Date" %in% class(x) ) {
x <- as.Date(x)
}
start <- floor_date( x, unit = "quarter" ) - months(3 * n)
stop <- start + months(3) - days(1)
out <- custom_period(start, stop)
part <- match.arg(part, getOption("timeperiodsR.parts"))
if ( part == "all" ) {
return(out)
} else {
return(out[[part]])
}
} |
geom_smooth <- function(mapping = NULL, data = NULL,
stat = "smooth", position = "identity",
...,
method = NULL,
formula = NULL,
se = TRUE,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE) {
params <- list(
na.rm = na.rm,
orientation = orientation,
se = se,
...
)
if (identical(stat, "smooth")) {
params$method <- method
params$formula <- formula
}
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomSmooth,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = params
)
}
GeomSmooth <- ggproto("GeomSmooth", Geom,
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, range_is_orthogonal = TRUE, ambiguous = TRUE)
params
},
extra_params = c("na.rm", "orientation"),
setup_data = function(data, params) {
GeomLine$setup_data(data, params)
},
draw_group = function(data, panel_params, coord, lineend = "butt", linejoin = "round",
linemitre = 10, se = FALSE, flipped_aes = FALSE) {
ribbon <- transform(data, colour = NA)
path <- transform(data, alpha = NA)
ymin = flipped_names(flipped_aes)$ymin
ymax = flipped_names(flipped_aes)$ymax
has_ribbon <- se && !is.null(data[[ymax]]) && !is.null(data[[ymin]])
gList(
if (has_ribbon) GeomRibbon$draw_group(ribbon, panel_params, coord, flipped_aes = flipped_aes),
GeomLine$draw_panel(path, panel_params, coord, lineend = lineend, linejoin = linejoin, linemitre = linemitre)
)
},
draw_key = draw_key_smooth,
required_aes = c("x", "y"),
optional_aes = c("ymin", "ymax"),
default_aes = aes(colour = "
linetype = 1, weight = 1, alpha = 0.4)
) |
library(ggplot2)
load('output/result-model5-3.RData')
ms <- rstan::extract(fit)
qua <- apply(ms$y_pred, 2, quantile, prob=c(0.1, 0.5, 0.9))
d_est <- data.frame(d, t(qua), check.names=FALSE)
d_est$A <- as.factor(d_est$A)
p <- ggplot(data=d_est, aes(x=Y, y=`50%`, ymin=`10%`, ymax=`90%`, shape=A, fill=A)) +
theme_bw(base_size=18) + theme(legend.key.height=grid::unit(2.5,'line')) +
coord_fixed(ratio=1, xlim=c(0, 0.5), ylim=c(0, 0.5)) +
geom_pointrange(size=0.5, color='grey5') +
geom_abline(aes(slope=1, intercept=0), color='black', alpha=3/5, linetype='31') +
scale_shape_manual(values=c(21, 24)) +
scale_fill_manual(values=c('white', 'grey70')) +
labs(x='Observed', y='Predicted') +
scale_x_continuous(breaks=seq(from=0, to=0.5, by=0.1)) +
scale_y_continuous(breaks=seq(from=0, to=0.5, by=0.1))
ggsave(file='output/fig5-3.png', plot=p, dpi=300, w=5, h=4) |
baseline.peakDetection <- function(spectra, left, right, lwin, rwin, snminimum, mono=0, multiplier=5, left.right, lwin.rwin){
np <- dim(spectra)
Midspec <- corrected <- matrix(0,np[1],np[2])
Sn <- Peaks <- Y1 <- Y2 <- Y3 <- list()
if(!missing(left.right)){
left <- left.right
right <- left.right
}
if(!missing(lwin.rwin)){
lwin <- lwin.rwin
rwin <- lwin.rwin
}
for(a in 1:np[1]){
spectrum <- spectra[a,]
mixr <- .mixedup(spectrum, left, right)
y <- mixr$topper; yleft <- mixr$lotter; yright <- mixr$rotter
slip <- .peakRemoval(spectrum, y, yleft, yright, mono)
mini1 <- .localMinPet(slip, lwin, rwin, mono)
midspec <- spectrum - mini1
mixr <- .mixedup(midspec, left, right)
y2 <- mixr$topper; yleft2 <- mixr$lotter; yright2 <- mixr$rotter
slip2 <- .peakRemoval(midspec, y2, yleft2, yright2, mono)
mini <- .localMinPet(slip2, lwin, rwin, mono)
newspec <- midspec - mini
corrected[a,] <- newspec
if(!missing(snminimum)){
mixr <- .mixedup(newspec, left, right)
y3 <- mixr$topper; yleft3 <- mixr$lotter; yright3 <- mixr$rotter
width <- multiplier*pmax(yright3-y3, y3-yleft3)
noise <- 0*y3
middle <- 0*y3
for(i in 1:length(y3)){
lend <- max(1, (y3[i]-width[i]))
rend <- min(length(newspec), (y3[i]+width[i]))
slice <- c(newspec[lend:yleft3[i]], newspec[yright3[i]:rend])
middle[i] <- median(slice)
noise[i] <- median(abs(slice-middle[i]))
noise[i] <- median(abs(diff(newspec[lend:rend])))
}
signal <- newspec[y3]-middle
sn <- pmax(0, signal/noise)
peaks <- y3[sn > snminimum]
Peaks[[a]] <- peaks
Sn[[a]] <- sn
Y1[[a]] <- y
Y2[[a]] <- y2
Y3[[a]] <- y3
Midspec[a,] <- midspec
}
}
if(missing(snminimum)){
list(baseline=spectra-corrected, corrected=corrected)
} else {
list(baseline=spectra-corrected, corrected=corrected, peaks=Peaks, sn=Sn, y3=Y3, midspec=Midspec, y=Y1, y2=Y2)
}
}
.peakRemoval <- function(w, y, yleft, yright, mono){
if(missing(mono))
mono <- 0
magic <- 3
slopes <- (w[yright]-w[yleft])/(yright-yleft)
m <- magic*median(abs(slopes))
counters <- 1:length(slopes)
if(mono > 0){
startup <- min(counters[abs(slopes)<m])
} else {
temp <- 1:length(w)
screwy <- max(temp[w==max(w)])
startup <- min(counters[y > screwy])
}
m <- magic*median(abs(slopes[counters>startup]))
selector <- !(counters>startup & abs(slopes) > m)
z <- y
zr <- yright
zl <- yleft
for(i in 2:(length(y)-1)){
if(selector[i] == 0){
if(w[yright[i-1]] > w[yright[i]])
zr[i-1] <- zr[i]
if(w[yleft[i+1]] > w[yleft[i]])
zl[i+1] <- zl[i]
}
}
z <- z[selector]
zl <- zl[selector]
zr <- zr[selector]
newspec <- w
for(i in 1:length(z)){
yr <- zr[i]
yl <- zl[i]
slope <- (w[yr] - w[yl])/(yr-yl)
newspec[yl:yr] <- slope*((yl:yr) - yl) + w[yl]
}
pmin(newspec, w)
}
.mixedup <- function(w, left, right){
n <- length(w)-1
if (missing(right)) right <- 30
if (missing(left)) left <- 5
if(left <= 0)
left <- 5
if(right < left){
temp <- right
right <- left
left <- temp
}
x <- diff(w)
xl <- x[1:(n-1)]
xr <- x[2:n]
neartop <- (xl > 0 & xr <= 0) | (xl == 0 & xr < 0)
nearbot <- (xl < 0 & xr >= 0) | (xl == 0 & xr > 0)
xx <- 1:length(x)
nb <- c(1,(xx[nearbot]+1))
nt <- xx[neartop]+1
curt <- 1
curb <- 1
tops <- 0
bots <- 1
numtop <- 1
numbot <- 1
while(curt < length(nt) && curb < length(nb)){
while(nb[curb]<nt[curt] && curb < length(nb)){
curb <- curb+1
}
bots[numbot] <- nb[curb]
numbot <- numbot+1
while(nt[curt] < nb[curb] && curt < length(nt)){
curt <- curt + 1
}
tops[numtop] <- nt[curt];
numtop <- numtop + 1
}
fuzz <- median(abs(x))
flux <- w[tops] - w[bots]
tops <- tops[flux > 2*fuzz]
dt <- diff(tops)
a <- (right-left)/length(x)^2
resolve <- left + (a*tops)*tops
temtops <- tops
topper <- 1
i <- 1
while(i < length(temtops)-1){
if(dt[i] < resolve[i]){
if(w[temtops[i]] < w[temtops[i+1]])
temtops[i] <- temtops[i+1]
else
temtops[i+1] <- temtops[i]
dt[i+1] <- temtops[i+2]-temtops[i]
}
else
topper[length(topper)+1] <- temtops[i]
i <- i + 1
}
lotter <- rep(1,length(topper)-1)
rotter <- rep(1,length(topper)-1)
for(i in 2:length(topper)){
temp <- topper[i-1]:topper[i]
lotter[i] <- max(temp[w[temp]==min(w[temp])])
rotter[i] <- min(temp[w[temp]==min(w[temp])])
}
rotter <- c(rotter[2:length(rotter)], length(x))
uptick <- topper-lotter
upper <- median(uptick)-median(abs(uptick-median(uptick)))
dntick <- rotter-topper
downer <- median(dntick)-median(abs(dntick-median(dntick)))
magic <- min(upper, downer) + 1
keeper <- !(uptick < magic | dntick < magic)
topper <- topper[keeper]
lotter <- lotter[keeper]
bottle <- c(lotter, length(x));
for(i in 1:length(topper)){
temp <- bottle[i]:bottle[i+1];
topper[i] <- max(temp[w[temp]==max(w[temp])])
}
lotter <- rep(1,length(topper)-1)
rotter <- rep(1,length(topper)-1)
for(i in 2:length(topper)){
temp <- topper[i-1]:topper[i]
lotter[i] <- max(temp[w[temp]==min(w[temp])])
rotter[i] <- min(temp[w[temp]==min(w[temp])])
}
maxright <- min(topper[length(topper)]+100, length(w))
rotter <- c(rotter[2:length(rotter)], maxright)
list(topper=topper, lotter=lotter, rotter=rotter)
}
.localMinPet <- function(spectrum, window, rightWindow, mono){
if(missing(window))
window <- 100
if(missing(rightWindow))
rightWindow <- window
if(missing(mono))
mono <- 0
len <- length(spectrum)
tops <- 1:len
a <- (rightWindow-window)/len^2
resolve <- floor(window + (a*tops)*tops)
mini <- numeric(len)
lend <- pmax(1,(tops-resolve))
rend <- pmin(len, (tops+resolve))
for(i in 1:len){
s <- spectrum[lend[i]:rend[i]]
mini[i] <- min(s)
}
if(mono > 0){
mono <- numeric(len)
mono[1] <- mini[1]
for(i in 2:len){
mono[i] <- mono[i-1]
if(mini[i] < mono[i])
mono[i] <- mini[i]
}
mini <- mono
}
mini
} |
print.geomerge <- function(x, ...){
inputs <- names(x$inputData)
datsets <- length(inputs)
if (!('period' %in% names(x$data))){
time.lag <- FALSE
}
num <- c()
non.num <- c()
for (inpt in 1:datsets){
if (class(x$inputData[[inpt]])=='SpatialPointsDataFrame'){
if (is.numeric(x$data@data[,paste0(inputs[inpt],'.',x$parameters$point.agg)])){
num <- c(num,inputs[inpt])
}else{
non.num <- c(non.num,inputs[inpt])
}
}else if (class(x$inputData[[inpt]])=='SpatialPolygonsDataFrame'){
if (is.numeric(x$data@data[,inputs[inpt]])){
num <- c(num,inputs[inpt])
}else{
non.num <- c(non.num,inputs[inpt])
}
}else if (class(x$inputData[[inpt]])=='RasterLayer'){
num <- c(num,inputs[inpt])
}
}
main = paste0("geomerge completed: ",datsets," datasets successfully integrated -")
if (length(x$parameters$time)>1){
main <- paste0(main,' run in dynamic mode, spatial panel was generated.\n\n')
}else{
main <- paste0(main,' run in static mode.\n\n')
}
num.message = paste0('The following ',length(num),' numerical variable(s) are available:','\n ',paste(num,collapse=", "),'\n\n')
non.num.message = paste0('The following ',length(non.num),' non numerical variable(s) are available:','\n ',paste(non.num,collapse=", "),'\n\n')
if (length(num)>0 & length(non.num)>0){
message <- paste0(main,num.message,non.num.message)
}else if (length(num)>0 & length(non.num)==0){
message <- paste0(main,num.message)
}else if (length(num)==0 & length(non.num)>0){
message <- paste0(main,non.num.message)
}
if (x$parameters$spat.lag){
message <- paste0(message,'First and second order spatial lag values available.\n')
}
if (length(x$parameters$time)>1 & x$parameters$time.lag){
message <- paste0(message,'First and second order temporal lag values available.\n')
}
cat(message)
} |
bs.g2 <- function(target, dataset, threshold = 0.05) {
runtime <- proc.time()
dataset <- as.matrix(dataset)
target <- as.numeric(target)
z <- cbind(dataset, target)
all.dc <- Rfast::colrange(z, cont = FALSE)
p <- dim(z)[2] - 1
ind <- 1:p
stat <- rep( Inf, p )
pval <- rep( -100, p )
dof <- rep( 100, p )
sig <- log(threshold)
for ( i in 1:p ) {
mod <- Rfast::g2Test(z, x = p + 1, y = i, cs = ind[ ind != i ], dc = all.dc)
dof[i] <- mod$df
stat[i] <- mod$statistic
}
pval <- pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE)
no <- which(pval == 0)
if ( length(no) > 1 ) {
sel <- which.min( stat[no]/dof[no] )
} else sel <- which.max(pval)
mat <- cbind(1:p, pval, stat)
colnames(mat) <- c("variable", "log.p-values", "statistic" )
info <- matrix( c(0, -10, -10), ncol = 3 )
colnames(info) <- c("Variables", "log.p-values", "statistic")
if ( pval[sel] < sig ) {
res <- list(info = matrix(0, 0, 3), runtime = proc.time() - runtime, mat = mat, ci_test = "gSquare")
} else {
info[1, ] <- mat[sel, ]
mat <- mat[-sel, , drop = FALSE]
dat <- z[, -sel, drop = FALSE]
dc2 <- all.dc[-sel]
p <- p - 1
ind <- 1:p
stat <- rep( Inf, p )
pval <- rep( -100, p )
dof <- rep( 100, p )
for ( i in 1:p ) {
mod <- Rfast::g2Test(dat, x = p + 1, y = i, cs = ind[ ind != i ], dc = dc2)
stat[i] <- mod$statistic
dof[i] <- mod$df
}
pval <- pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE)
mat[, 2:3] <- cbind(pval, stat)
no <- which(pval == 0)
if ( length(no) < 1 ) {
sel <- which.max( pval )
} else sel <- which.min(stat[no]/dof[no])
while ( pval[sel] > sig & p > 1 ) {
info <- rbind(info, mat[sel, ])
mat <- mat[-sel, , drop = FALSE]
dat <- z[, -info[, 1], drop = FALSE]
dc2 <- all.dc[ -info[, 1] ]
p <- p - 1
if ( p == 1 ) {
mod <- Rfast::gchi2Test(target, dat[, -(p + 1)], logged = TRUE)
stat <- mod[2, 1]
pval <- mod[2, 2]
sel <- 1
if ( pval > sig ) {
info <- rbind(info, mat[sel, ])
mat <- NULL
}
} else {
ind <- 1:p
stat <- rep( Inf, p )
pval <- rep( -100, p )
dof <- rep( 100, p )
for ( i in 1:p ) {
mod <- Rfast::g2Test(dat, x = p + 1, y = i, cs = ind[ ind != i ], dc = dc2)
stat[i] <- mod$statistic
dof[i] <- mod$df
}
pval <- pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE)
mat[, 2:3] <- cbind(pval, stat)
no <- which(pval == 0)
if ( length(no) < 1 ) {
sel <- which.max( pval )
} else sel <- which.min(stat[no]/dof[no])
}
}
runtime <- proc.time() - runtime
info <- info[ info[, 1] > 0, , drop = FALSE]
res <- list(runtime = runtime, info = info, mat = mat, ci_test = "gSquare" )
}
res
}
|
cli_progress_num <- function() {
length(clienv$progress)
}
cli_progress_cleanup <- function() {
while ((n <- cli_progress_num()) > 0) {
cli_progress_done(clienv$progress[[n]]$id)
}
ansi_show_cursor()
invisible()
}
should_run_progress_examples <- function() {
if (is_rcmd_check()) return(FALSE)
tolower(Sys.getenv("R_PROGRESS_NO_EXAMPLES")) != "true"
}
is_rcmd_check <- function() {
if (identical(Sys.getenv("NOT_CRAN"), "true")) {
FALSE
} else {
Sys.getenv("_R_CHECK_PACKAGE_NAME_", "") != ""
}
} |
summary.funnelplot <- function(object, ...){
k <- object$conflev
outp <- list("call" = object$call)
for(i in k){
temp <- sort(object$data[which(object$data[, as.character(i)] == "worse"), "instance"])
outp[[as.character(i)]] = droplevels(as.factor(temp))
}
return(outp)
} |
conf.int = function(level = 0.95, size = 50, cl = c('red', 'gray'), ...) {
n = ani.options('nmax')
d = replicate(n, rnorm(size))
m = colMeans(d)
z = qnorm(1 - (1 - level)/2)
y0 = m - z/sqrt(size)
y1 = m + z/sqrt(size)
rg = range(c(y0, y1))
cvr = y0 < 0 & y1 > 0
xax = pretty(1:n)
for (i in 1:n) {
dev.hold()
plot(
1:n, ylim = rg, type = 'n', xlab = 'Samples',
ylab = expression('CI: [' ~ bar(x) - z[alpha/2] * sigma/sqrt(n) ~ ', ' ~ bar(x) +
z[alpha/2] * sigma/sqrt(n) ~ ']'), xaxt = 'n', ...)
abline(h = 0, lty = 2)
axis(1, xax[xax <= i])
arrows(
1:i, y0[1:i], 1:i, y1[1:i], length = par('din')[1]/n * 0.5,
angle = 90, code = 3, col = cl[cvr[1:i] + 1])
points(1:i, m[1:i], col = cl[cvr[1:i] + 1])
legend(
'topright', legend = format(c(i - sum(cvr[1:i]), sum(cvr[1:i])), width = nchar(n)),
fill = cl, bty = 'n', ncol = 2)
legend(
'topleft',
legend = paste('coverage rate:', format(round(mean(cvr[1:i]), 3), nsmall = 3)),
bty = 'n')
ani.pause()
}
CI = cbind(y0, y1)
colnames(CI) = paste(round(c((1 - level)/2, 1 - (1 - level)/2), 2) * 100, '%')
rownames(CI) = 1:n
invisible(list(level = level, size = size, CI = CI, CR = mean(cvr)))
} |
tidy.lmrob <- function(x, conf.int = FALSE, conf.level = 0.95, ...) {
ret <- coef(summary(x)) %>%
as_tibble(rownames = "term")
names(ret) <- c("term", "estimate", "std.error", "statistic", "p.value")
if (conf.int) {
ci <- stats::confint.default(x, level = conf.level) %>%
as_tibble()
names(ci) <- c("conf.low", "conf.high")
ret <- ret %>%
cbind(ci)
}
ret
}
augment.lmrob <- function(x, data = model.frame(x), newdata = NULL, se_fit = FALSE, ...) {
augment_newdata(
x, data, newdata,
.se_fit = se_fit
)
}
glance.lmrob <- function(x, ...) {
s <- summary(x)
as_glance_tibble(
r.squared = s$r.squared,
sigma = s$sigma,
df.residual = x$df.residual,
na_types = "rri"
)
} |
parse.ls.error <- function(lsp, func.locations, err.file) {
error.str <- readLines(err.file, warn=FALSE)[[1]]
m <- regmatches(error.str, regexec("^Error: At line ([[:digit:]]+): (.+)$", error.str))[[1]]
if (length(m) != 0) {
line.no <- as.integer(m[[2]])
err.text <- m[[3]]
return(sprintf("%s\n%s", err.text, find.ls.context(lsp, func.locations, line.no)))
}
m <- regmatches(error.str, regexec("^^Error \\[[^]]+ line: ([[:digit:]]+) ]: (.+)$", error.str))[[1]]
if (length(m) != 0) {
line.no <- as.integer(m[[2]])
err.text <- m[[3]]
return(sprintf("%s\n%s", err.text, find.ls.context(lsp, func.locations, line.no)))
}
return(error.str)
}
find.ls.context <- function(lsp, func.locations, line.no) {
for(funcName in names(func.locations)) {
loc <- func.locations[[funcName]]
if (loc$start.line <= line.no && line.no < loc$end.line) {
inFuncLine <- line.no - loc$start.line + 1
funcDesc <- lsp$functions[[funcName]]
lines <- paste(".", strsplit(funcDesc$body, '\n')[[1]])
lines[[inFuncLine]] <- sprintf('>%s', substring(lines[[inFuncLine]], 2))
ctx <- lines[max(1, inFuncLine-1):min(inFuncLine+1, length(lines))]
if (inFuncLine <= 2) {
ctx[[1]] <- sprintf('%s {%s', funcDesc$decl, ctx[[1]])
}
return(sprintf("in '%s' function, arround\n%s", funcName, paste(ctx, collapse='\n')))
}
}
return("At unexpected position (line: %d)", line.no)
} |
ETref <- function(x, Tmax = NULL, Tmin = NULL, Rhmax = NULL, Rhmin = NULL, Tmean = NULL, Rhmean = NULL,
u = NULL, Rs = NULL, n = NULL, P = NULL, elev, lat.rad = NULL, lat.deg = NULL, long.deg = NULL,
tl, G = NULL, actVP = NULL, control = list()) {
control <- modifyList(controlDefaults, control)
if(all(is.numeric(x))){
tl <- 24
}
if(all(is.timepoint(x))) {
if(length(x) > 1) {
tl <- as.numeric(difftime(x[2:length(x)], x[1:(length(x)-1)] , units = 'hour'))
tl <- unique(tl)
if(length(tl) > 1) stop('Difference betwenn time steps must be consistent in x!')
}
if(length(x) == 1) {
stopifnot(exists('tl'))
}
}
doy <- prep.date(x)
if (is.null(lat.rad) & is.null(lat.deg)) stop('no latitude')
if (is.null(lat.rad)) lat.rad <- (pi/180)*lat.deg
if (is.null(P)) {
P <- estP(elev = elev, control)
}
if(control$uz == 2) {
u2 <- u
}
if(control$uz != 2) {
u2 <- adj_u2(u = u, uz = control$uz)
}
if (all(tl > 1)){
if(!is.null(actVP)) {
Vpres <- actVP
}else{
Vpres <- VP(Tmax, Tmin, Rhmax = Rhmax, Rhmin = Rhmin, Rhmean = Rhmean, interval = 'day')
}
if (is.null(Rs) & is.null(n)) {
stop('For daily or longer periods solar radiation (Rs) or sunshine duration (n) must be provided!')
}
if (is.null(Rs)) { Rs <- estRs(x, n, lat.rad = lat.rad, control = control)}
if (is.null(G)) { G <- 0 }
Tmean <- ((Tmax + Tmin)/2)
obj <- ((0.408* deltaVP(Tmax = Tmax, Tmin = Tmin)*
(Rn(x = doy, Tmax = Tmax, Tmin = Tmin, Rhmax = Rhmax, Rhmin = Rhmin, Rs = Rs, control = control,
lat.rad = lat.rad, elev = elev, Rhmean = Rhmean, actVP = actVP, Tmean = Tmean) - G))+
(psyc_cons(elev = elev, P = P)*900/(Tmean + 273))*(u2)* (satVP(Tmax, Tmin, interval = 'day') -
Vpres))/
(deltaVP(Tmax = Tmax, Tmin = Tmin) + (psyc_cons(elev = elev, P)*(1+(0.34*u2))))
}
if (all(tl <= 1)) {
if(is.null(long.deg)) {
stop('For hourly or shorter periods longitude (long.deg) must be provided!')
}
if(is.null(Rs)) {
stop('For hourly or shorter periods solar radiation (Rs) must be provided!')
}
if (is.null(G)) {G <- estG(x = x, Tmean = Tmean, Rhmean = Rhmean, Rs = Rs,
lat.rad = lat.rad, long.deg = long.deg, tl = tl, elev = elev,
control = control) }
obj <- ((0.408* deltaVP(Tmean = Tmean)*
(Rn(x = x, Rs = Rs, Tmean = Tmean, Rhmean = Rhmean, lat.rad = lat.rad,
long.deg = long.deg, elev = elev, control = control, tl = tl) -
G)) +
(psyc_cons(elev, P, control = control)*(37/(Tmean + 273))* u2*
(e0(Tmean) - VP(Tmean = Tmean, Rhmean = Rhmean, interval = 'hour'))
))/
(deltaVP(Tmean = Tmean) + (psyc_cons(elev, P, control = control)*(1 + 0.34 * u2)))
}
obj
} |
library(tinytest)
library(tiledb)
isOldWindows <- Sys.info()[["sysname"]] == "Windows" && grepl('Windows Server 2008', osVersion)
ctx <- tiledb_ctx(limitTileDBCores())
if (get_return_as_preference() != "asis") set_return_as_preference("asis")
d1 <- tiledb_dim("d1", domain=c(1L, 100L))
dom <- tiledb_domain(c(d1))
a1 <- tiledb_attr(type = "FLOAT64")
sch <- tiledb_array_schema(dom, c(a1))
expect_true(is(sch, "tiledb_array_schema"))
d1 <- tiledb_dim("d1", domain = c(1L, 100L))
d2 <- tiledb_dim("d2", domain = c(1L, 100L))
dom <- tiledb_domain(c(d1, d2))
a1 <- tiledb_attr(type = "FLOAT64")
sch <- tiledb_array_schema(dom, c(a1))
expect_true(is(domain(sch), "tiledb_domain"))
ds <- tiledb::dimensions(sch)
expect_equal(length(ds), 2)
expect_true(is(ds[[1]], "tiledb_dim"))
expect_true(is(ds[[2]], "tiledb_dim"))
as <- tiledb::attrs(sch)
expect_equal(length(as), 1)
expect_true(is(as[[1]], "tiledb_attr"))
expect_equal(tiledb::cell_order(sch), "COL_MAJOR")
expect_equal(tiledb::tile_order(sch), "COL_MAJOR")
expect_false(is.sparse(sch))
d1 <- tiledb_dim("d1", domain = c(1L, 100L))
d2 <- tiledb_dim("d2", domain = c(1L, 100L))
d3 <- tiledb_dim("d3", domain = c(1L, 100L))
dom <- tiledb_domain(c(d1, d2, d3))
a1 <- tiledb_attr("attribute1", type = "FLOAT64")
a2 <- tiledb_attr("attribute2", type = "INT32")
sch <- tiledb_array_schema(dom, c(a1, a2),
cell_order = "ROW_MAJOR",
tile_order = "ROW_MAJOR",
coords_filter_list = tiledb_filter_list(c(tiledb_filter("GZIP"))),
offsets_filter_list = tiledb_filter_list(c(tiledb_filter("ZSTD"))),
sparse = TRUE)
expect_true(is(domain(sch), "tiledb_domain"))
ds <- tiledb::dimensions(sch)
expect_equal(length(ds), 3)
expect_true(is(ds[[1]], "tiledb_dim"))
expect_true(is(ds[[2]], "tiledb_dim"))
expect_true(is(ds[[3]], "tiledb_dim"))
as <- tiledb::attrs(sch)
expect_equal(length(as), 2)
expect_equal(names(as), c("attribute1", "attribute2"))
expect_true(is(as[[1]], "tiledb_attr"))
expect_true(is(as[[2]], "tiledb_attr"))
expect_equal(tiledb::cell_order(sch), "ROW_MAJOR")
expect_equal(tiledb::tile_order(sch), "ROW_MAJOR")
filter_list <- tiledb::filter_list(sch)
expect_equal(tiledb_filter_type(filter_list[["coords"]][0]), "GZIP")
expect_equal(tiledb_filter_get_option(filter_list[["coords"]][0], "COMPRESSION_LEVEL"), -1)
expect_equal(tiledb_filter_type(filter_list[["offsets"]][0]), "ZSTD")
expect_equal(tiledb_filter_get_option(filter_list[["offsets"]][0], "COMPRESSION_LEVEL"), -1)
expect_true(is.sparse(sch))
tiledb:::libtiledb_array_schema_set_capacity(sch@ptr, 100000)
expect_equal(tiledb:::libtiledb_array_schema_get_capacity(sch@ptr), 100000)
expect_error(tiledb:::libtiledb_array_schema_set_capacity(sch@ptr, -10))
if (!(isOldWindows)) {
dir.create(uri <- tempfile())
key <- "0123456789abcdeF0123456789abcdeF"
dom <- tiledb_domain(dims = c(tiledb_dim("rows", c(1L, 4L), 4L, "INT32"),
tiledb_dim("cols", c(1L, 4L), 4L, "INT32")))
schema <- tiledb_array_schema(dom, attrs = c(tiledb_attr("a", type = "INT32")))
tiledb:::libtiledb_array_create_with_key(uri, schema@ptr, key)
ctx <- tiledb_ctx()
arrptr <- tiledb:::libtiledb_array_open_with_key(ctx@ptr, uri, "WRITE", key)
A <- new("tiledb_dense", ctx=ctx, uri=uri, as.data.frame=FALSE, ptr=arrptr)
expect_true(is(A, "tiledb_dense"))
unlink(uri, recursive=TRUE)
}
dom <- tiledb_domain(dims = c(tiledb_dim("rows", c(1L, 4L), 4L, "INT32"),
tiledb_dim("cols", c(1L, 4L), 4L, "INT32")))
sch <- tiledb_array_schema(dom,
attrs = c(tiledb_attr("a", type = "INT32")),
sparse = TRUE)
expect_false(allows_dups(sch))
allows_dups(sch) <- TRUE
expect_true(allows_dups(sch)) |
hyperparam.alpha <- function(icp.torus, alphavec = NULL, alpha.lim = 0.15){
if(is.null(icp.torus)) {stop("icp.torus object must be input.")}
if(icp.torus$model == "mixture") {model <- "mixture"}
else if(icp.torus$model == "kmeans") {model <- "kmeans"}
else {stop("model kde is not supported.")}
n2 <- icp.torus$n2
if (is.null(alphavec) && alpha.lim > 1) {stop("alpha.lim must be less than 1.")}
output <- list()
out <- data.frame()
if (is.null(alphavec)) {alphavec <- 1:floor(min(n2, 1000) * alpha.lim) / n2}
n.alphavec <- length(alphavec)
if (model == "kmeans"){
for (ii in 1:n.alphavec){
alpha <- alphavec[ii]
ialpha <- ifelse((n2 + 1) * alpha < 1, 1, floor((n2 + 1) * alpha))
t <- icp.torus$score_ellipse[ialpha]
ncluster <- conn.comp.ellipse(icp.torus$ellipsefit, t)$ncluster
out <- rbind(out, data.frame(alpha = alpha, ncluster = ncluster))
if(ii%%10 == 0) cat(".")
}
cat("\n")
nclusters.length <- rle(out$ncluster)$lengths
length <- max(nclusters.length)
length.index <- which.max(nclusters.length)
length.sum <- ifelse(length.index == 1, 0, sum(nclusters.length[1:(length.index - 1)]))
term.alpha <- out$alpha[(length.sum + 1):(length.sum + length)]
alphahat <- stats::median(term.alpha)
output$alpha.results <- out
output$alphahat <- alphahat
}
else if (model == "mixture"){
for (ii in 1:n.alphavec){
alpha <- alphavec[ii]
ialpha <- ifelse((n2 + 1) * alpha < 1, 1, floor((n2 + 1) * alpha))
t <- icp.torus$score_ellipse[ialpha]
ncluster <- conn.comp.ellipse(icp.torus$ellipsefit, t)$ncluster
out <- rbind(out, data.frame(alpha = alpha, ncluster = ncluster))
if(ii%%10 == 0) cat(".")
}
cat("\n")
nclusters.length <- rle(out$ncluster)$lengths
length <- max(nclusters.length)
length.index <- which.max(nclusters.length)
length.sum <- ifelse(length.index == 1, 0, sum(nclusters.length[1:(length.index - 1)]))
term.alpha <- out$alpha[(length.sum + 1):(length.sum + length)]
alphahat <- stats::median(term.alpha)
output$alpha.results <- out
output$alphahat <- alphahat
}
return(structure(output, class = "hyperparam.alpha"))
} |
.Random.seed <- c(403L, 10L, 1897936630L, -1719655904L, 881993699L, -1426011007L,
-545453328L, 1718534542L, -512610567L, 806804619L, 1551647930L, 1053810620L,
1911463167L, -1908805547L, 1750049644L, 2123865026L, -142685155L, -1759859561L,
-1014494722L, -1217082952L, 1255720347L, 2006477817L, -886901944L, -309207434L,
-460957775L, 745187811L, 331939506L, 1853436676L, -2002112441L, 533583645L, 889597332L,
642175290L, 1125657989L, 604317279L, 400494822L, 178410352L, -82086765L, 1122496817L,
-2036508704L, -1899635586L, -1732489463L, 1004474683L, 331183370L, 1501129964L,
135584111L, 553475749L, 1369354332L, 4532274L, -876093651L, 1237888487L, -689442546L,
-1154345240L, -522045205L, 315701641L, 1326041368L, -903521210L, 679208097L,
478710579L, -1902939486L, 913820052L, -885991401L, 766689293L, 1430324516L, 1340555530L,
-2125858699L, -1786883121L, -253631274L, -1929153408L, -1662547261L, -166800287L,
1767019728L, 339002926L, 1357395929L, 242964459L, 739249754L, 2142111772L, 873600287L,
-1285188235L, 1939907596L, 1875764706L, -1895803203L, 1101754679L, 2056639966L,
-491255016L, -762183045L, 317141017L, -1126897496L, 588696150L, 769111761L, -1558038909L,
-1884820206L, -996247388L, 318617703L, -500631107L, -1152445644L, 1834481818L,
744742629L, 1909700735L, 1331229190L, -842179184L, 1398014003L, -11243567L, -1610422912L,
-1080301474L, 1667155881L, -20775333L, 1891000938L, -162574580L, -621156017L,
-480783867L, 2044100796L, -1994020462L, -360136051L, -1822199609L, -1733360210L,
741478408L, -1374419957L, 469090537L, 1340784568L, -1498539930L, -145405695L,
-667746413L, 298291266L, -160737292L, 1008992759L, 646776301L, 1482966660L, -2073347926L,
-754481643L, -1261741393L, -265678666L, -722563360L, -2146725341L, -1214038719L,
-1085439952L, -66938290L, -580264263L, -408507701L, -2041156742L, -396322180L,
-1975112001L, -1247111275L, 649809836L, 716475778L, 413700957L, 1484275287L,
63397182L, 1189424504L, 2144091739L, 1594251705L, -123671544L, -705005898L, 13796849L,
-810116061L, 47248498L, 1563797188L, 1056604295L, 2101675101L, -2003195308L,
-2060451718L, 624264133L, 878130463L, 1143837862L, 1336550960L, 101940435L, -1417497871L,
189612576L, -2088655682L, 142430409L, -461516165L, -1500874678L, -860059476L,
-107614289L, 1220885349L, 1778667804L, 246208882L, 1748781549L, 2065243687L,
-1784066482L, 1987801768L, 1644318891L, -1741915703L, 1497126360L, 359048326L,
896649569L, -1930998541L, -1583516830L, -1234928172L, -847497001L, 995543757L,
-1258546588L, -1743007670L, -103279179L, -2136114929L, 1909679638L, -2092556096L,
-645581181L, -1269108063L, -1472605040L, 993591150L, -1727801063L, -2075838037L,
1775802266L, 112658268L, 1742345823L, -681433547L, -1125923380L, -580319966L,
-1233211523L, 333218935L, -1102366306L, 1673211992L, -1803375173L, -633584807L,
334377192L, -2146692842L, 835498641L, 1192542019L, -31352238L, 576433380L, -1146865881L,
-605998211L, -2042247564L, 1718532186L, -1210171227L, -736632129L, 1835678022L,
1496747984L, -1934177805L, -1679943776L, -354409284L, -414342704L, -133320350L,
1767960552L, 961975244L, 385066748L, 1152828402L, -532697984L, 2003863796L, -1274437496L,
-1399242438L, -1537692848L, 20545644L, 536116372L, -1469086382L, 2000079584L,
-439759668L, -204983136L, 1194440066L, 1692673256L, -1416100628L, 1293498428L,
321727602L, -648078224L, 1906635300L, 421578296L, 725934618L, -1835447088L, 9825852L,
-898475884L, 217531522L, -181615680L, 989751612L, 1091522192L, 1495471138L, 1056276488L,
-2006834036L, 346840092L, 1930027154L, -1162093440L, 311446548L, -1873832152L,
842285114L, -1465083696L, 549359724L, 948045492L, 2119486482L, 1422369760L, -833014836L,
624499168L, 930687010L, -1809339096L, -855805684L, -1816112580L, 979855602L,
1475407088L, 63520580L, 561798232L, 1433087546L, -1986381584L, 981092028L, 932717076L,
-751110974L, 1097546336L, -1284230788L, 1608772816L, -269340638L, -1157163864L,
1368076684L, -1743912516L, 837323826L, -227365056L, 1530055348L, -418853560L,
-604981574L, -593085680L, 1581336812L, 695643220L, 230146834L, -1179193952L,
-774498356L, 1760389984L, 1143729346L, 599958056L, 284302764L, -236084420L, -1039765646L,
707862320L, -742491100L, -492105160L, -1608726822L, 1211212688L, 307745020L,
-1460082284L, 1164294978L, -512232960L, -1840221124L, -480688L, -1680534366L,
862840648L, -189290996L, -91187492L, -459268014L, -305819520L, -318147756L, 1733792744L,
-16313606L, -408400048L, -1263972308L, 533778804L, -1419679086L, 251515488L,
629406860L, 1310567776L, 1443987682L, -504309592L, -1066024244L, 1284457980L,
-901638222L, -526667792L, -804799036L, -1838724776L, 1030303098L, -717759056L,
-1639736900L, 1774332500L, -2036781630L, 1520798496L, -1621660740L, 551384144L,
-1883400222L, 1335810920L, -1483053236L, 524081916L, -949398798L, 1359180032L,
-986639244L, 1875098120L, -1175625286L, -855868976L, 228332524L, -1952426092L,
1679860946L, -140603296L, 1841805644L, -2035294432L, 1706844802L, 1458975208L,
-627883028L, -1114276292L, -1428745614L, -1435347088L, 556007716L, -2139357640L,
1248898458L, 1221465552L, -244158020L, -687924588L, 2003908226L, -367396416L,
1058234172L, -139704688L, -1675443422L, -246403576L, -768366836L, -400875620L,
-2078607342L, 1706001280L, -1030340844L, 1541155112L, 1946417210L, -176576560L,
673661548L, -1090698188L, 456469650L, 2014131552L, 920084812L, -508010016L, -348735582L,
-680960088L, 643714188L, -1138938948L, -966459278L, 1815024624L, -1877065660L,
384242776L, 270665786L, 279511152L, -933082564L, 410913556L, -1315840318L, -2126569760L,
-238959492L, 1118187728L, -544726110L, 1816191528L, 1696308492L, 280865724L,
-386839246L, -606731072L, 1636482612L, -152213816L, -1887760710L, 1579731088L,
-1802966292L, 2107531860L, 592733842L, 1397480224L, 176249804L, 727233760L, -1460815166L,
-1618329560L, -302324820L, -1559637316L, 1061920242L, 1015803440L, 1212745636L,
1816782264L, -301185190L, 1837074576L, 563389308L, 521689876L, -659193534L, -176659712L,
841459644L, 1367909200L, -664805485L, 497185716L, -1596671806L, 1442184407L,
908278049L, -228978458L, 17118692L, -1799720683L, -827029185L, -1838230312L,
-2124530442L, 856246019L, -467533755L, -1875828638L, 1716381648L, 815856889L,
748516907L, 1629880732L, -1031314998L, -947993921L, 257963017L, 1827489054L,
207603916L, -1696678755L, -525033177L, -1088992432L, 1355757038L, -367889765L,
-101026563L, -1712972822L, -533521272L, -13958607L, -430599005L, -1157048156L,
1806723410L, -1745742681L, 1767166193L, 1059711030L, 1634539732L, -888443803L,
-1932302737L, -1781389144L, -1286130170L, -685074637L, -2120150123L, -1568266254L,
93824064L, -1043227223L, 1639167003L, 477655532L, 567740922L, -1207980497L, -1302676935L,
379425870L, -1891410788L, -398520819L, 390820471L, -519028096L, 2063300830L,
-1057320021L, -1609491283L, -623697638L, 27006424L, 2049986113L, 1475233011L,
614093588L, 631399074L, 2144754615L, -2141194367L, -1537442426L, -1811427388L,
-651275531L, -108050593L, -1526658632L, -1000853354L, 543528611L, -705972123L,
-1585590910L, 491532016L, -627080551L, -1807620469L, 760121212L, 1855080874L,
-696368673L, 1377081193L, -1215864962L, -1814124692L, 1701600189L, 1402472583L,
1357218928L, -1254047986L, 1974404155L, 1628932893L, -2022325814L, -1564546328L,
-673767983L, -1945776189L, 607754436L, -2127239310L, 1954273863L, 110848529L,
1699390358L, -1498634508L, 1734609029L, -1672266289L, 2110064840L, 2071667046L,
1634046867L, -504439563L, 34176210L, 163900192L, 1561666313L, 402474043L, -537048692L,
666050586L, -999732081L, -1108626471L, 1218950254L, 575510524L, 1004965229L,
-1701083369L, 1410627296L, -1573993282L, -1855925621L, -2022205171L, 586845498L,
1899007352L, 1818789665L, 1169039315L, 1100367604L, 2010519426L, 2058862103L,
1989711073L, 1966240294L, 49853220L, 1742822357L, 1585216383L, 989560344L, 1712588086L,
1969068995L, -2013740539L, -658663006L, -2077319792L, -1028264647L, -2017318421L,
-570905892L, -1098412278L, -1473216001L, 1865320521L, 234955230L, -385152628L,
1970693469L, -679574169L, -466954608L, -1414055762L, -320947877L, 1512795453L,
1772625834L, -1626785720L, -1295871887L, -1308328477L, -178226972L, -1073310702L,
1473732583L, -1924921423L, 13097462L, -703241196L, 880057125L, 296582191L, -1174002577L) |
formulaMultilinear <-
function (nloc = 2, max.level = 2, max.dom = 2, e.unique = FALSE)
{
a <- noia::effectsNames[2]
d <- noia::effectsNames[3]
f <- paste("phen ~ X[[\"", effNames(nloc = nloc), "\"]]*R",
sep = "")
for (l1 in 1:nloc) {
add <- effNames(c(a), c(l1), nloc)
dom <- effNames(c(d), c(l1), nloc)
f <- paste(f, " + ", "X[[\"", add, "\"]]*a", l1, sep = "")
if (max.dom > 0) {
f <- paste(f, " + ", "X[[\"", dom, "\"]]*d", l1,
sep = "")
}
}
if ((max.level > 1) && (nloc > 1)) {
for (l1 in 1:(nloc - 1)) {
for (l2 in (l1 + 1):nloc) {
aXa <- effNames(c(a, a), c(l1, l2), nloc)
aXd <- effNames(c(a, d), c(l1, l2), nloc)
dXa <- effNames(c(d, a), c(l1, l2), nloc)
dXd <- effNames(c(d, d), c(l1, l2), nloc)
if (e.unique) {
f <- paste(f, " + ", "X[[\"", aXa, "\"]]*a",
l1, "*a", l2, "*ee", sep = "")
if (max.dom > 1) {
f <- paste(f, " + ", "X[[\"", aXd, "\"]]*a",
l1, "*d", l2, "*ee", sep = "")
f <- paste(f, " + ", "X[[\"", dXa, "\"]]*d",
l1, "*a", l2, "*ee", sep = "")
f <- paste(f, " + ", "X[[\"", dXd, "\"]]*d",
l1, "*d", l2, "*ee", sep = "")
}
}
else {
f <- paste(f, " + ", "X[[\"", aXa, "\"]]*a",
l1, "*a", l2, "*e", l1, l2, sep = "")
if (max.dom > 1) {
f <- paste(f, " + ", "X[[\"", aXd, "\"]]*a",
l1, "*d", l2, "*e", l1, l2, sep = "")
f <- paste(f, " + ", "X[[\"", dXa, "\"]]*d",
l1, "*a", l2, "*e", l1, l2, sep = "")
f <- paste(f, " + ", "X[[\"", dXd, "\"]]*d",
l1, "*d", l2, "*e", l1, l2, sep = "")
}
}
}
}
}
return(f)
} |
library(testthat)
context("checkrcompObjItemLength")
test_that("rcompObjItemLength works",{
expect_equal(rcompObjItemLength(iris), 150)
expect_equal(rcompObjItemLength(c(1,2,3)), 3)
expect_equal(rcompObjItemLength(NA), 1)
expect_equal(rcompObjItemLength(NULL), 0)
}) |
args(vars:::predict.varest)
predictions <- predict(varsimest, n.ahead = 25,
ci = 0.95)
class(predictions)
args(vars:::plot.varprd)
plot(predictions, names = "y1")
args(fanchart)
fanchart(predictions, names = "y2") |
test_that("todos() works", {
path <- test_path("scripts")
file <- test_path("scripts/todos.R")
res <- todos(path = path)
exp <- struct(
list(
line = c(3L, 7L),
file = rep(file, 2),
todo = c("make x longer", "add another example")
),
c("todos_df", "data.frame"),
todos_type = "todo",
row.names = 1:2,
.keep_attr = TRUE
)
expect_identical(res, exp)
res <- todos(pattern = "example", path = path)
exp <- struct(
list(
line = 7L,
file = file,
todo = "add another example"
),
c("todos_df", "data.frame"),
todos_type = "todo",
row.names = 1L,
.keep_attr = TRUE
)
expect_identical(res, exp)
res <- fixmes(path = path)
exp <- struct(
list(
line = 9L,
file = file,
fixme = "This is a fixme"
),
c("todos_df", "data.frame"),
todos_type = "fixme",
row.names = 1L,
.keep_attr = TRUE
)
expect_identical(res, exp)
})
test_that("todo() errors and messages", {
path <- test_path("scripts")
err <- "path must be a character vector of length 1L"
expect_error(todos(path = 1), err)
expect_error(todos(path = c("a", "b")), err)
expect_error(todos(path = "zzz"), "path not found: zzz")
expect_error(do_todo(c("todo", "fixme"), path = "."), "Length of text must be 1")
expect_message(res <- todos("zzzzzz", path = path), "No todos found")
expect_null(res)
skip("not currently testing snaps")
expect_snapshot(todos(path = path))
}) |
library(tidyverse)
library(here)
library(janitor)
library(likert)
library(jkmisc)
library(nord)
star_wars <- dir(here("week7", "data"), pattern = "StarWars", full.names = TRUE) %>%
read_csv()
clean_names <- stringi::stri_trans_general(names(star_wars), "latin-ascii") %>%
gsub("[^\\x{00}-\\x{7f}]", "", ., perl = TRUE) %>%
clean_names()
star_wars <- set_names(star_wars, clean_names)
headers <- slice(star_wars, 1) %>%
flatten_chr()
clean_names <- gsub("X\\d+", NA_character_, clean_names) %>%
enframe() %>%
fill(value) %>%
pull(value)
shiny_clean_names <- paste(clean_names, headers, sep = "|")
long_star_wars <- set_names(star_wars, c("RespondentID", shiny_clean_names[-1])) %>%
slice(-1) %>%
gather(item, value, -1) %>%
separate(item, c("question", "category"), sep = "\\|") %>%
mutate(category = if_else(category == "Response", NA_character_, category)) %>%
mutate(index = group_indices(., question))
plot_data <- long_star_wars %>%
filter(index == 12) %>%
replace_na(list(value = "Unfamiliar (N/A)")) %>%
filter(value != "Unfamiliar (N/A)") %>%
spread(category, value) %>%
mutate_at(vars(-RespondentID, -question, -index), function(x)
factor(x,
levels = c("Very unfavorably", "Somewhat unfavorably","Neither favorably nor unfavorably (neutral)", "Somewhat favorably", "Very favorably"),
labels = 1:5
))
likert_data <- plot_data %>%
select(-RespondentID, -question, -index) %>%
as.data.frame() %>%
likert()
ggplot2::update_geom_defaults("text", list(family = "Scope One", size = 4))
plot <- likert.bar.plot(likert_data) +
scale_fill_nord("mountain_forms", labels = c("Very unfavorably", "Somewhat unfavorably","Neither favorably nor unfavorably (neutral)", "Somewhat favorably", "Very favorably"), name = "Response") +
labs(title = "The Favorability Rankings of Star Wars Characters", subtitle = "People look favourably upon the scruffy nerf herder, and would give a ride to the EVIL RAISIN THAT SHOOTS LIGHTNING FROM HIS HANDS before the goofy gungan.") +
theme_jk(grid = "XY") +
theme(plot.title = element_text(family = "Oswald"))
ggsave(here("week7", "tw7_likert.png"), width = 16, height = 10)
|
compute_ratio_minus1 <- function(lambda, rho, alpha, gams,
d, n.ints, n.nodes, natural){
c.alpha <- stats::qnorm(1 - alpha/2)
new.par <- optimize_knots(lambda, rho, alpha, gams,
d, n.ints, n.nodes, natural)
s.spl <- spline_s(new.par, d, n.ints, c.alpha, natural)
sel.max <- stats::optimize(compute_sel, c(0, d), maximum = TRUE,
y = new.par, d = d, n.ints = n.ints,
n.nodes = n.nodes, alpha = alpha, s.spl = s.spl)$objective
sel.min <- compute_sel(gam = 0, new.par, d, n.ints, n.nodes, alpha, s.spl = s.spl)
expected.gain <- 1 - sel.min^2
max.potential.loss <- sel.max^2 - 1
out <- expected.gain / max.potential.loss - 1
} |
SASiformat <- function(x, default)
UseMethod("SASiformat")
SASiformat.default <- function(x, default=NULL)
{
lab <- attr(x,"SASiformat")
if(is.null(lab))
default
else
lab
}
SASiformat.data.frame <- function(x, default=NULL)
{
sapply( x, SASiformat)
}
"SASiformat<-" <- function(x, value)
UseMethod("SASiformat<-")
"SASiformat<-.default" <- function(x, value)
{
attr(x,'SASiformat') <- value
x
}
"SASiformat<-.data.frame" <- function(x, value)
{
if( ncol(x) != length(value) )
stop("vector of iformats must match number of data frame columns")
for(i in 1:ncol(x))
attr(x[[i]],'SASiformat') <- value[i]
x
} |
expect_silent(mf_get_pal(n = 5, palette = 'Dynamic'))
expect_silent(mf_get_pal(n = c(6, 5), palette = c("Mint", 'Reds 2')))
expect_silent(mf_get_pal(n = c(6, 5), palette = c("Mint", 'Reds 2'), neutral = "grey")) |
nonpar.rules <- function(Z,S,phi){
if(length(Z)!=length(S))
message("***** Warning: Disease status and risk score vector lengths do not match. \n")
data <- cbind(Z,S)
Z <- data[complete.cases(data),1]
S <- data[complete.cases(data),2]
Z <- 1*Z
if(phi>1 || phi<0)
message("***** Warning: Invalid phi. \n")
if(cor(Z,S)<0)
message("***** Warning: Disease status is negatively associated with risk score.
Suggest using (-) value for risk score. \n")
total.sam.sz <- length(Z)
S.srt <- sort(unique(S))
n.unique.S <- length(S.srt)
cum.F <- 0
for(i in 1:n.unique.S){
cum.F <- c(cum.F, mean(S<=S.srt[i],na.rm=TRUE))
}
flg <- T; i <- 1;j1 <- 0; bounds <- NULL
while(flg){
j <- sum((cum.F-cum.F[i]) <=phi)-1
if(j>=i){
if(i == 1){
bounds <- c(i, j)
j1 <- j
}
if(i>1){
if(j>j1){
bounds <- rbind(bounds, c(i,j))
}
j1 <- j
}
}
i <- i+1
if(i>n.unique.S || j1==n.unique.S) flg=F
}
if(phi==0){
bounds <- cbind(1:n.unique.S, 1:n.unique.S)
message("***** Warning: 0 patient taking viral load test. \n")
}
l <- S.srt[bounds[,1]]
u <- S.srt[bounds[,2]]
return(cbind(l,u))
}
nonpar.fnr.fpr <- function(Z,S,l,u){
if(length(l)!=length(u))
message("***** Warning: Wrong rules set. \n")
n.bounds <- length(l)
mean.Z <- mean(Z,na.rm=TRUE)
fnr.fpr <- NULL
for(i in 1:n.bounds){
fnr.fpr <- rbind(fnr.fpr, c(mean((S<l[i])*Z,na.rm=TRUE)/mean(Z,na.rm=TRUE),
mean((S>u[i])*(1-Z),na.rm=TRUE)/mean(1-Z,na.rm=TRUE)))
}
return(fnr.fpr)
}
semipar.fnr.fpr <- function(Z,S,l,u){
if(length(l)!=length(u))
message("***** Warning: Wrong rules set. \n")
p <- mean(Z)
temp <- density(S)
fit <- glm(Z~ S, family=binomial)
beta0star <- fit$coef[1]-log(p/(1-p))
t <- exp(beta0star+temp$x*fit$coef[2])
g1 <- temp$y/(p+(1-p)/t)
g0 <- temp$y/(p*t+1-p)
x <- temp$x
len <- length(x)
dif <- x[2:len]-x[1:(len-1)]
cal.fnr <- function(dens,a){
if( a>max(x) ){
area <- 1
} else if( a<min(x) ){
area <- 0
} else {
diff <- a-x
diff1 <- diff[diff<=0][1]
indx <- which(diff==diff1)
area <- sum(dens[1:(indx-2)]*dif[1:(indx-2)])+dens[indx-1]*(a-x[indx-1])
}
return(area)
}
fnr.fpr <- NULL
K <- length(l)
for( i in 1:K){
fnr <- cal.fnr(g1,l[i])
fpr <- 1-cal.fnr(g0,u[i])
fnr.fpr <- rbind(fnr.fpr,c(fnr,fpr))
}
return(fnr.fpr)
}
cal.AUC <- function(Z,S,l,u){
n = length(Z)
p <- mean(Z)
Hphi <- function(Sj,bounds=cbind(l,u)){
diff <- Sj-bounds[,2]
diff1 <- diff[diff<=0][1]
indx <- which(diff==diff1)
return(bounds[indx,1])
}
auc <- 0
for(j in 1:n){
auc <- auc+sum(Z*(1-Z[j])*((S>Hphi(S[j]))+(S==Hphi(S[j]))/2))
}
auc <- auc/(n^2*p*(1-p))
} |
floopCauchyLoss <- function (par,x,y) {
t <- par[1:length(x)]
cx <- par[length(x)+1]
cy <- par[length(x)+2]
b.x <- par[length(x)+3]
b.y <- par[length(x)+4]
logm <- par[length(x)+5]
logn <- par[length(x)+6]
retention <- par[length(x)+7]
times <- cumsum(t)
costp <- cos(times)
sintp <- sin(times)
direc <- sign(costp)
direcsin <- sign(sintp)
pred.x <- cx+b.x*costp
pred.y <- cy+direcsin*retention*abs(sintp)^exp(logm)+direc*b.y*abs(costp)^exp(logn)
logloss <- crossprod(y-pred.y[1:length(y)])+crossprod(x-pred.x)
logloss
} |
simPPe <- function(lscape.size = 150, buffer.width = 25, variance.X = 1, theta.X = 10, M = 250, beta = 1, quads.along.side = 6, show.plots = TRUE) {
buffer.width <- round(buffer.width[1])
stopifNegative(buffer.width)
quads.along.side <- round(quads.along.side[1])
stopifNegative(quads.along.side, allowZero=FALSE)
lscape.size <- round(lscape.size[1])
stopifnotGreaterthan(lscape.size, 2 * buffer.width + quads.along.side - 1)
variance.X <- variance.X[1]
stopifNegative(variance.X)
theta.X <- theta.X[1]
stopifNegative(theta.X)
M <- round(M[1])
stopifNegative(M)
size.core <- lscape.size - 2 * buffer.width
prop.core <- size.core^2/lscape.size^2
pixel.size <- 1
x <- seq(1, lscape.size, pixel.size)-0.5
y <- seq(1, lscape.size, pixel.size)-0.5
grid <- as.matrix(expand.grid(x,y))
lambda_pp <- M / size.core^2
quad.size <- size.core / quads.along.side
breaks <- seq(buffer.width, size.core+buffer.width, by = quad.size)
mid.pt <- breaks[-length(breaks)] + 0.5 * quad.size
core <- range(breaks)
nsite <- length(mid.pt)^2
RFoptions(seed=NA)
field <- matrix(RFsimulate(RMexp(var = variance.X, scale = theta.X),
x=x, y=y, grid=TRUE)@data$variable1, ncol = lscape.size)
M2 <- round(M/prop.core)
probtemp <- exp(beta[1]*c(field))
probs <- probtemp / sum(probtemp)
pixel.id <- sort(sample(1:lscape.size^2, M2 , replace=TRUE, prob=probs))
u1 <- grid[pixel.id,1] + runif(M2, -pixel.size/2, pixel.size /2)
u2 <- grid[pixel.id,2] + runif(M2, -pixel.size/2, pixel.size /2)
u <- cbind(u1, u2)
Nac <- as.matrix(table(cut(u[,1], breaks=breaks),
cut(u[,2], breaks= breaks)))
E_N <- round(mean(Nac),2)
zac <- Nac ; zac[zac>1] <- 1
E_z <- round(mean(zac), 2)
if(show.plots) {
oldpar <- par(mfrow = c(1, 3), mar = c(4,2,5,2), cex.main = 1.8, cex.axis = 1.2) ; on.exit(par(oldpar))
tryPlot <- try( {
image(rasterFromXYZ(cbind(grid, c(field))), col=topo.colors(10),
main = "Point pattern with\ncore and buffer area",
xlab = "", ylab = "", axes = FALSE, asp = 1)
mtext(paste("Mean intensity (lambda) =", round(lambda_pp, 5)), side=1)
polygon(c(buffer.width, size.core+buffer.width, size.core+buffer.width, buffer.width),
c(buffer.width, buffer.width, size.core+buffer.width, size.core+buffer.width),
lwd = 2, lty = 1)
points(u[,1], u[,2], pch=20, col='black', cex = 1.2)
image(rasterFromXYZ(cbind(grid, c(field))), col=topo.colors(10), main = "Abundance, N",
xlab = "", ylab = "", axes = FALSE, asp = 1)
mtext(paste0("Mean(N) = ", E_N, ", var(N) = ", round(var(c(Nac)), 2)), side=1)
polygon(c(buffer.width, size.core+buffer.width, size.core+buffer.width, buffer.width),
c(buffer.width, buffer.width, size.core+buffer.width, size.core+buffer.width), lwd = 2, lty = 1)
points(u[,1], u[,2], pch=20, col='black', cex = 1.2)
for(i in 1:length(breaks)){
for(k in 1:length(breaks)){
segments(breaks[i], breaks[k], rev(breaks)[i], breaks[k])
segments(breaks[i], breaks[k], breaks[i], rev(breaks)[k])
}
}
for(i in 1:length(mid.pt)){
for(k in 1:length(mid.pt)){
text(mid.pt[i], mid.pt[k], Nac[i,k], cex =4^(0.8-0.5*log10(quads.along.side)), col='red')
}
}
image(rasterFromXYZ(cbind(grid, c(field))), col=topo.colors(10), main = "Occurrence, z",
xlab = "", ylab = "", axes = FALSE, asp = 1)
mtext(paste("Mean(z) =", E_z), side=1)
polygon(c(buffer.width, size.core+buffer.width, size.core+buffer.width, buffer.width),
c(buffer.width, buffer.width, size.core+buffer.width, size.core+buffer.width), lwd = 2, lty = 1)
points(u[,1], u[,2], pch=20, col='black', cex = 1.2)
for(i in 1:length(breaks)){
for(k in 1:length(breaks)){
segments(breaks[i], breaks[k], rev(breaks)[i], breaks[k])
segments(breaks[i], breaks[k], breaks[i], rev(breaks)[k])
}
}
for(i in 1:length(mid.pt)){
for(k in 1:length(mid.pt)){
text(mid.pt[i], mid.pt[k], zac[i,k], cex =4^(0.8-0.5*log10(quads.along.side)), col='red')
}
}
for(i in 1:(length(breaks)-1)){
for(k in 1:(length(breaks)-1)){
if(zac[i,k] == 1)
next
polygon(c(breaks[i], breaks[i+1], breaks[i+1], breaks[i]),
c(breaks[k], breaks[k], breaks[k+1], breaks[k+1]),
col = adjustcolor("black", 0.6))
}
}
}, silent = TRUE)
if(inherits(tryPlot, "try-error"))
tryPlotError(tryPlot)
}
return(list(
grid.size = lscape.size, buffer.width = buffer.width, variance.X = variance.X, theta.X = theta.X, M = M, beta = beta, quads.along.side = quads.along.side,
core = core,
M2 = M2,
grid = grid,
pixel.size = pixel.size,
size.core = size.core,
prop.core = prop.core,
X = field,
probs = probs,
pixel.id = pixel.id,
u = u,
nsite = nsite,
quad.size = quad.size,
breaks = breaks,
mid.pt = mid.pt,
lambda_pp = lambda_pp,
Nac = Nac,
zac = zac,
E_N = E_N,
E_z = E_z))
} |
wide_path_matrix <- function(ncells) {
if (!inherits(ncells, "numeric")) {
stop("ncells argument is invalid. Expecting numeric value")
}
if (ncells%%2 == 0) {
stop("ncells argument is invalid. Expecting odd numeric value")
}
if (ncells < 3) {
stop("ncells argument is invalid. Expecting numeric value 3 or greater")
}
wpMatrix = matrix(1, nrow = ceiling(ncells), ncol = ceiling(ncells))
indents <- ceiling((nrow(wpMatrix)/3) - 1)
if (indents > 0) {
for (i in 1:indents) {
row_idx = c(i, ncol(wpMatrix) - i + 1)
col_idx = c(1:(indents - i + 1))
wpMatrix[row_idx, c(col_idx, nrow(wpMatrix) - col_idx + 1)] <- NA
}
}
start_row = (nrow(wpMatrix))/2 + 1
start_col = (ncol(wpMatrix))/2 + 1
wpMatrix[start_row, start_col] <- 0
return(wpMatrix)
} |
test_that("classif_penalized", {
suppressMessages(requirePackages("!penalized", default.method = "load"))
suppressMessages(requirePackages("survival"))
parset.list = list(
list(maxiter = 100),
list(lambda1 = 2),
list(lambda1 = 2, lambda2 = 1),
list(lambda2 = 2),
list(fusedl = TRUE, lambda1 = 2, maxiter = 20L),
list(fusedl = TRUE, lambda1 = 2, lambda2 = 1, maxiter = 5L),
list(fusedl = TRUE, lambda2 = 2, maxiter = 20L)
)
old.probs.list = list()
for (i in seq_along(parset.list)) {
parset = parset.list[[i]]
pars = list(binaryclass.formula, data = binaryclass.train)
pars = c(pars, parset)
capture.output({
m = do.call(penalized::penalized, pars)
})
m@formula$unpenalized[[2L]] = as.symbol(binaryclass.target)
old.probs.list[[i]] = 1 - penalized::predict(m, data = binaryclass.test)
}
testProbParsets("classif.penalized", binaryclass.df, binaryclass.target,
binaryclass.train.inds, old.probs.list, parset.list)
parset.list = list(
list(maxiter = 100),
list(lambda1 = 2, lambda2 = 1),
list(lambda1 = 1, lambda2 = 2),
list(lambda1 = 2, lambda2 = 1, maxiter = 2L, fusedl = TRUE),
list(lambda1 = 1, lambda2 = 2, maxiter = 4L, fusedl = TRUE)
)
tt = function(formula, data, subset = seq_len(nrow(data)), ...) {
penalized::penalized(formula, data = data[subset, ], ...)
}
tp = function(model, newdata, ...) {
pred = penalized::predict(model, data = newdata, ...)
ifelse(pred > 0.5, binaryclass.class.levs[2L], binaryclass.class.levs[1L])
}
testCVParsets("classif.penalized", binaryclass.df, binaryclass.target,
tune.train = tt, tune.predict = tp, parset.list = parset.list)
}) |
context("cwt_perio")
test_that("wct_perio periodogram works", {
data(dams_sample)
dd <- dams_sample[id %in% dams_sample[meta=TRUE, ,id[1:5]]]
per <- dd[,
cwt_periodogram(activity, sampling_rate = 1/300, n_sim = 1, resolution=1/32),
by = id]
}) |
apc.data.sums <- function(apc.data.list,data.type="r",average=FALSE,keep.incomplete=TRUE,apc.index=NULL)
{
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
if(data.type %in% c("d","m") & is.null(apc.data.list$dose)==TRUE) return(cat("apc.error: Doses are not available \n"))
if(data.type == "r") data.matrix <- apc.data.list$response
if(data.type == "d") data.matrix <- apc.data.list$dose
if(data.type == "m") data.matrix <- apc.data.list$response / apc.data.list$dose
trap <- matrix(data=NA,nrow=apc.index$age.max,ncol=apc.index$coh.max)
trap[apc.index$index.trap] <- data.matrix[apc.index$index.data]
trap.ap <- matrix(data=NA,nrow=apc.index$age.max,ncol=apc.index$per.max)
for(row in 1:apc.index$age.max)
{
col.lower <- max(1,apc.index$per.zero+2-row)
col.upper <- min(apc.index$coh.max,apc.index$per.zero+1-row+apc.index$per.max)
per.lower <- max(1,row-apc.index$per.zero)
per.upper <- col.upper-col.lower+per.lower
trap.ap[row,per.lower:per.upper] <- trap[row,col.lower:col.upper]
}
if(average==TRUE)
{ sums.age <- rowMeans(trap.ap,na.rm=keep.incomplete)
sums.coh <- colMeans(trap, na.rm=keep.incomplete)
sums.per <- colMeans(trap.ap,na.rm=keep.incomplete)
}
if(average==FALSE)
{ sums.age <- rowSums(trap.ap,na.rm=keep.incomplete)
sums.coh <- colSums(trap ,na.rm=keep.incomplete)
sums.per <- colSums(trap.ap,na.rm=keep.incomplete)
}
return(list(sums.age=sums.age,
sums.per=sums.per,
sums.coh=sums.coh))
}
apc.plot.data.sums <- function(apc.data.list,data.type="a",average=FALSE,keep.incomplete=TRUE,apc.index=NULL,type="o",log="",main.outer=NULL,main.sub=NULL)
{
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
if(is.null(main.outer)==TRUE)
main.outer <- "Data sums by age/period/cohort index"
if(data.type %in% c("r","d","m") | is.null(apc.data.list$dose)==TRUE) par(mfrow=c(1,3))
if(data.type == "a" & is.null(apc.data.list$dose)==FALSE) par(mfrow=c(3,3))
if(data.type %in% c("d","m") & is.null(apc.data.list$dose)==TRUE) return(cat("apc.plot.data.sums error: Doses are not available \n"))
par(mar=c(5,5,2,0),oma=c(0,0,1,1))
if(average==TRUE) s.ylab="averages of data"
if(average==FALSE) s.ylab="sums of data"
if(data.type %in% c("r","a"))
{ sums.response <- apc.data.sums(apc.data.list,data.type="r",average,keep.incomplete,apc.index)
if(is.null(main.sub)==TRUE) main <- "response"
plot(seq(from=apc.index$age1,by=apc.index$unit,length=apc.index$age.max),sums.response$sums.age,main=main,xlab="age" ,ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$per1,by=apc.index$unit,length=apc.index$per.max),sums.response$sums.per,main=main,xlab="period",ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$coh1,by=apc.index$unit,length=apc.index$coh.max),sums.response$sums.coh,main=main,xlab="cohort",ylab=s.ylab,type=type,log=log)
}
if(data.type %in% c("d","a") & is.null(apc.data.list$dose)==FALSE)
{
sums.dose <- apc.data.sums(apc.data.list,data.type="d",average,keep.incomplete,apc.index)
if(is.null(main.sub)==TRUE) main <- "dose"
plot(seq(from=apc.index$age1,by=apc.index$unit,length=apc.index$age.max),sums.dose$sums.age,main=main,xlab="age" ,ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$per1,by=apc.index$unit,length=apc.index$per.max),sums.dose$sums.per,main=main,xlab="period",ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$coh1,by=apc.index$unit,length=apc.index$coh.max),sums.dose$sums.coh,main=main,xlab="cohort",ylab=s.ylab,type=type,log=log)
}
if(data.type %in% c("m","a") & is.null(apc.data.list$dose)==FALSE)
{
sums.dose <- apc.data.sums(apc.data.list,data.type="m",average,keep.incomplete,apc.index)
if(is.null(main.sub)==TRUE) main <- "rates"
plot(seq(from=apc.index$age1,by=apc.index$unit,length=apc.index$age.max),sums.dose$sums.age,main=main,xlab="age" ,ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$per1,by=apc.index$unit,length=apc.index$per.max),sums.dose$sums.per,main=main,xlab="period",ylab=s.ylab,type=type,log=log)
plot(seq(from=apc.index$coh1,by=apc.index$unit,length=apc.index$coh.max),sums.dose$sums.coh,main=main,xlab="cohort",ylab=s.ylab,type=type,log=log)
}
title(main.outer,outer=TRUE)
}
apc.plot.data.sparsity <- function(apc.data.list,data.type="a",swap.axes=FALSE,apc.index=NULL,sparsity.limits=c(1,2),cex=NULL,pch=15,main.outer=NULL)
{
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
if(is.null(main.outer)==TRUE)
main.outer <- paste("Sparsity plots \n","(black <",as.character(sparsity.limits[1]),",grey <",as.character(sparsity.limits[2]),")")
data.format <- apc.index$data.format
xlab <- apc.index$data.xlab
ylab <- apc.index$data.ylab
x1 <- apc.index$data.x1
y1 <- apc.index$data.y1
xmax <- apc.index$data.xmax
ymax <- apc.index$data.ymax
unit <- apc.index$unit
if(data.format=="CL") swap.axes=1-swap.axes
xlim <- c(x1,x1 +(xmax-1)*unit)
ylim <- c(y1,y1 +(ymax-1)*unit)
if(data.format=="CL")
if(swap.axes) xlim <- c(x1 +(xmax-1)*unit,x1)
else ylim <- c(y1 +(ymax-1)*unit,y1)
if(data.type %in% c("r","d") | is.null(apc.data.list$dose)==TRUE) par(mfrow=c(1,1))
if(data.type == "a" & is.null(apc.data.list$dose)==FALSE) par(mfrow=c(1,2))
if(data.type == "d" & is.null(apc.data.list$dose)==TRUE) return(cat("apc.error: Doses are not available \n"))
par(mar=c(5,5,2,0),oma=c(0,0,2,1))
function.sparsity.plot <- function(data.matrix,main,swap.axes)
{ if(is.null(cex)==TRUE)
{ nmax <- max(xmax,ymax)
cex <- 0.5
if(nmax<20) cex <- 1
if(nmax<10) cex <- 2
if(nmax<5 ) cex <- 5
}
if(swap.axes){ l.x1 <- y1; l.y1 <- x1; l.xmax <- ymax; l.ymax <- xmax }
else { l.x1 <- x1; l.y1 <- y1; l.xmax <- xmax; l.ymax <- ymax }
if(swap.axes){
data.matrix <- t(data.matrix)
plot(1,1,pch=NA,xlim=ylim,ylim=xlim,xlab=ylab,ylab=xlab,main=main)
}
else plot(1,1,pch=NA,xlim=xlim,ylim=ylim,xlab=xlab,ylab=ylab,main=main)
for(row in 1:l.xmax)
for(col in 1:l.ymax)
{
x <- l.x1+(row-1)*unit
y <- l.y1+(col-1)*unit
z <- data.matrix[row,col]
if(is.na(z)==TRUE) points(x,y,cex=cex,pch="x")
else
{
if(z<sparsity.limits[2]) points(x,y,cex=cex,pch=pch,col=gray(0.66))
if(z<sparsity.limits[1]) points(x,y,cex=cex,pch=pch,col=gray(0.0))
}
}
}
if(data.type %in% c("r","a"))
function.sparsity.plot(apc.data.list$response,"responses",swap.axes)
if(data.type %in% c("d","a") & is.null(apc.data.list$dose)==FALSE)
function.sparsity.plot(apc.data.list$dose,"doses",swap.axes)
title(main.outer,outer=TRUE)
}
apc.plot.data.within <- function(apc.data.list,data.type="r",plot.type="awc",average=FALSE,thin=NULL,apc.index=NULL,ylab=NULL,type="o",log="",legend=TRUE,lty=1:5,col=1:6,bty="n",main=NULL,x="topleft",return=FALSE)
{
if((plot.type %in% c("awp","awc","cwp","pwa","cwa","pwc"))==FALSE)
return(cat("apc.plot.data.within error: plot.type not recognised \n"))
l.data.type <- data.type
if(data.type == "response") l.data.type <- "r"
if(data.type == "dose") l.data.type <- "d"
if(data.type == "rates") l.data.type <- "m"
if(data.type == "mortality") l.data.type <- "m"
if(l.data.type %in% c("d","m") & is.null(apc.data.list$dose)==TRUE)
return(cat("apc.plot.data.within error: Doses are not available \n"))
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
if(l.data.type == "r")
{ title.add.to <- "response"; m <- apc.data.list$response; }
if(l.data.type == "d")
{ title.add.to <- "dose"; m <- apc.data.list$dose; }
if(l.data.type == "m")
{ title.add.to <- "rates"; m <- apc.data.list$response/apc.data.list$dose; }
trap.m <- matrix(data=NA,nrow=apc.index$age.max,ncol=apc.index$coh.max)
trap.m[apc.index$index.trap] <- m[apc.index$index.data]
if(is.null(ylab))
{
if(log=="y") ylab <- "log "
if(l.data.type=="r") ylab <- paste(ylab,"response",sep="")
if(l.data.type=="d") ylab <- paste(ylab,"dose",sep="")
if(l.data.type=="m") ylab <- paste(ylab,"rate",sep="")
}
function.trapezoid.to.ap <- function(trapezoid,transpose=FALSE)
{
age.max <- apc.index$age.max
per.max <- apc.index$per.max
coh.max <- apc.index$coh.max
per.zero <- apc.index$per.zero
nrow <- age.max
ncol <- coh.max
if(transpose==TRUE)
{
trapezoid <- t(trapezoid)
nrow <- coh.max
ncol <- age.max
}
m <- matrix(data=NA,nrow=nrow,ncol=per.max)
for(row in 1:nrow)
{
col.lower <- max(1,per.zero+2-row)
col.upper <- min(ncol,per.zero+1-row+per.max)
per.lower <- max(1,row-per.zero)
per.upper <- col.upper-col.lower+per.lower
m[row,per.lower:per.upper] <- trapezoid[row,col.lower:col.upper]
}
return(m)
}
if(plot.type=="awp")
{ m.to.plot <- function.trapezoid.to.ap(trap.m);
x1 <- apc.index$age1; x.max <- apc.index$age.max; xlab <- "age";
w1 <- apc.index$per1; w.max <- apc.index$per.max; title.sub <- "within period" }
if(plot.type=="awc")
{ m.to.plot <- trap.m;
x1 <- apc.index$age1; x.max <- apc.index$age.max; xlab <- "age";
w1 <- apc.index$coh1; w.max <- apc.index$coh.max; title.sub <- "within cohort" }
if(plot.type=="cwp")
{ m.to.plot <- function.trapezoid.to.ap(trap.m,transpose=TRUE);
x1 <- apc.index$coh1; x.max <- apc.index$coh.max; xlab <- "cohort";
w1 <- apc.index$per1; w.max <- apc.index$per.max; title.sub <- "within period" }
if(plot.type=="pwa")
{ m.to.plot <- t(function.trapezoid.to.ap(trap.m));
x1 <- apc.index$per1; x.max <- apc.index$per.max; xlab <- "period";
w1 <- apc.index$age1; w.max <- apc.index$age.max; title.sub <- "within age" }
if(plot.type=="cwa")
{ m.to.plot <- t(trap.m);
x1 <- apc.index$coh1; x.max <- apc.index$coh.max; xlab <- "cohort";
w1 <- apc.index$age1; w.max <- apc.index$age.max; title.sub <- "within age" }
if(plot.type=="pwc")
{ m.to.plot <- t(function.trapezoid.to.ap(trap.m,transpose=TRUE));
x1 <- apc.index$per1; x.max <- apc.index$per.max; xlab <- "period";
w1 <- apc.index$coh1; w.max <- apc.index$coh.max; title.sub <- "within cohort" }
function.thin.value <- function(m,thin=NULL)
{
l.thin <- thin
if(is.null(l.thin)==TRUE)
{ ncol <- ncol(m)
l.thin <- 1
if(ncol>10) l.thin <- 2
if(ncol>20) l.thin <- 4
if(ncol>40) l.thin <- 8
if(ncol>80) l.thin <- 16
}
return(l.thin)
}
function.thin.matrix <- function(m,l.thin)
{
if(l.thin==1) mm <- m
else
{
nrow <- nrow(m)
ncol <- ncol(m)
ngroup <- ceiling(ncol/l.thin)
mm <- matrix(data=NA,nrow=nrow,ncol=ngroup)
if(average==TRUE)
{ for(group in 1:(ngroup-1))
{ mmm <- as.matrix(m[,((group-1)*l.thin+1):(group*l.thin)])
mm[,group] <- as.matrix( rowMeans(mmm,na.rm=TRUE))
}
mmm <- as.matrix(m[,((ngroup-1)*l.thin+1):ncol])
mm[,ngroup] <- as.matrix( rowMeans(mmm,na.rm=TRUE))
}
if(average==FALSE)
{ for(group in 1:(ngroup-1))
{ mmm <- as.matrix(m[,((group-1)*l.thin+1):(group*l.thin)])
mm[,group] <- as.matrix( rowSums(mmm,na.rm=TRUE))
}
mmm <- as.matrix(m[,((ngroup-1)*l.thin+1):ncol])
mm[,ngroup] <- as.matrix( rowSums(mmm,na.rm=TRUE))
}
if(ngroup != ncol/l.thin)
print("apc.plot.data.within warning: maximal index not divisible by thin, so last group smaller than other groups")
}
return(mm)
}
l.thin <- function.thin.value(m.to.plot,thin)
m.to.plot <- function.thin.matrix(m.to.plot,l.thin=l.thin)
old.par <- par()
par(mar=c(5,5,3,1)+0.1)
v.x <- seq(from=x1,length=x.max,by=apc.index$unit)
if(is.null(main)) main <- title.sub
matplot(v.x,m.to.plot,type=type,pch=20,log=log,lty=lty,col=col,xlab=xlab,ylab=ylab,main=main)
within <- seq(from=w1,length=ceiling(w.max/l.thin),by=apc.index$unit*l.thin)
if(legend==TRUE) legend(x=x,legend=as.character(within),lty=lty,col=col,bty=bty)
par <- old.par
if(return==TRUE)
{ dimnames(m.to.plot) <- list(as.character(v.x),as.character(within))
return(m.to.plot) }
}
apc.plot.data.within.all.six <- function(apc.data.list,data.type="r",average=FALSE,thin=NULL,apc.index=NULL,ylab=NULL,type="o",log="",legend=TRUE,lty=1:5,col=1:6,bty="n",main.outer=NULL,x="topleft")
{
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
if(is.null(main.outer)) main.outer <- "plots of data using two indices"
old.par <- par()
par(mfrow=c(2,3))
par(oma=c(0,0,2,0))
l.data.type = c("awp","awc","cwp","pwa","cwa","pwc")
for(i in 1:6)
apc.plot.data.within(apc.data.list,data.type=data.type,plot.type=l.data.type[i],average=average,thin=thin,apc.index=apc.index,ylab=ylab,type=type,log=log,legend=legend,lty=lty,col=col,bty=bty,x=x)
title(main.outer,outer=TRUE)
par <- old.par
}
apc.plot.data.level <- function(apc.data.list,data.type="r",rotate=FALSE,apc.index=NULL,main=NULL,lab=NULL,contour=FALSE,colorkey=TRUE)
{
if(is.null(apc.index)==TRUE)
apc.index <- apc.get.index(apc.data.list)
l.data.type <- data.type
if(data.type == "response") l.data.type <- "r"
if(data.type == "dose") l.data.type <- "d"
if(data.type == "rates") l.data.type <- "m"
if(data.type == "mortality") l.data.type <- "m"
if(l.data.type %in% c("d","m") & is.null(apc.data.list$dose)==TRUE)
return(cat("apc.plot.data.within error: Doses are not available \n"))
if(l.data.type == "r")
{ l.main <- "response"; m <- apc.data.list$response; }
if(l.data.type == "d")
{ l.main <- "dose"; m <- apc.data.list$dose; }
if(l.data.type == "m")
{ l.main <- "rates"; m <- apc.data.list$response/apc.data.list$dose; }
if(l.data.type == "residual")
{ l.main <- "residual"; m <- apc.data.list$m.residual; }
if(l.data.type == "fitted.values")
{ l.main <- "fitted values"; m <- apc.data.list$m.fitted.values; }
if(l.data.type == "linear.predictors")
{ l.main <- "linear predictors"; m <- apc.data.list$m.linear.predictors; }
if(is.null(main)) main <- l.main
l.rotate <- rotate
if(apc.data.list$data.format=="CL") l.rotate <- 1-l.rotate
x1 <- apc.index$data.x1; xmax <- apc.index$data.xmax; xlab <- apc.index$data.xlab;
y1 <- apc.index$data.y1; ymax <- apc.index$data.ymax; ylab <- apc.index$data.ylab;
unit<- apc.index$unit
if(is.null(lab)) lab[1:2] <- c(min(5,xmax),min(5,ymax))
x.at <- seq(from=1,to=xmax,length=lab[1])
x.lab<- as.character(x1+(x.at-1)*unit)
if(l.rotate) x.lab <- x.lab[length(x.lab):1]
x <- list(at=x.at,labels=x.lab)
y.at <- seq(from=1,to=ymax,length=lab[2])
y.lab<- as.character(y1+(y.at-1)*unit)
y <- list(at=y.at,labels=y.lab)
if(l.rotate)
print(levelplot(t(m[nrow(m):1,]),xlab=ylab,ylab=xlab,scales=list(x=y,y=x),main=main,contour=contour,colorkey=colorkey))
else
print(levelplot(m,xlab=xlab,ylab=ylab,scales=list(x=x,y=y),main=main,contour=contour,colorkey=colorkey))
}
apc.plot.data.all <- function(apc.data.list,log="",rotate=FALSE)
{
apc.index <- apc.get.index(apc.data.list)
apc.plot.data.sums(apc.data.list,log=log,apc.index=apc.index)
dev.new(); apc.plot.data.sparsity(apc.data.list,apc.index=apc.index)
dev.new(); apc.plot.data.within.all.six(apc.data.list,"r",log=log,apc.index=apc.index)
if(is.null(apc.data.list$dose)==FALSE)
{ dev.new(); apc.plot.data.within.all.six(apc.data.list,"d",log=log,apc.index=apc.index)
dev.new(); apc.plot.data.within.all.six(apc.data.list,"m",log=log,apc.index=apc.index)
}
dev.new(); apc.plot.data.level(apc.data.list,"r",rotate=rotate,apc.index=apc.index)
if(is.null(apc.data.list$dose)==FALSE)
{ dev.new(); apc.plot.data.level(apc.data.list,"d",rotate=rotate,apc.index=apc.index)
dev.new(); apc.plot.data.level(apc.data.list,"m",rotate=rotate,apc.index=apc.index)
}
} |
ao_get_learners_quiz_statistic <- function(
email,
content_id
) {
cli_alert_info('Compose request body')
rbody <- oa_make_body(
action = 'getLearnersQuizStatistic',
options = 'records',
values = content_id
)
rbody <- set_names(rbody, c('action', str_glue("options[records][{email}][]")))
cli_alert_info('Send request')
resp <- oa_request(body = rbody, token = suppressMessages(ao_auth()))
cli_alert_info('Parse result')
res <- oa_parser(resp[[1]][[1]]) %>%
oa_set_class('oa_quize_stat')
cli_alert_success('Loaded {nrow(res)} learners')
return(res)
} |
library(otsad)
context("Clasic Processing Tssd-Ewma")
test_that("CpTsSdEwma gives the correct result", {
n <- 500
x <- c(31,26,56,6,47,49,82,38,55,18,63,89,29,40,77,67,21,36,36,70,54,72,54,75,200,18,78,89,55,28,
49,93,35,96,70,89,19,63,99,14,34,87,78,83,61,50,79,89,21,31,34,20,24,28,60,26,13,23,60,22,
47,65,97,68,45,36,46,45,25,111,114,111,112,112,112,114,111,114,113,111,112,110,112,115,110,
110,112,111,115,113,91,21,36,45,91,39,52,13,4,78,33,39,5,37,58,69,98,71,2,54,84,81,9,24,
97,4,92,73,21,85,40,40,48,59,36,3,100,96,56,11,24,87,74,50,58,2,48,5,47,63,68,9,15,91,13,
73,96,5,2,20,51,93,14,17,61,82,85,79,2,70,82,57,49,17,9,17,3,71,77,86,44,42,59,83,80,33,96,
66,46,61,29,72,93,68,19,35,13,11,30,84,100,44,21,97,67,30,12,60,13,79,37,96,92,83,32,88,81,
62,8,43,35,76,22,30,36,64,90,75,46,4,57,44,61,96,27,66,8,8,38,30,56,37,85,63,40,30,39,71,
95,78,22,72,67,71,28,72,67,5,7,28,31,96,39,38,85,85,32,14,62,80,34,91,20,80,76,92,33,9,92,
96,68,75,45,12,68,74,49,18,68,27,35,22,2,38,57,68,75,96,17,33,14,64,34,65,31,8,67,76,56,
54,85,66,96,62,50,98,50,66,60,95,37,88,46,50,47,62,61,79,56,170,41,52,53,100,43,100,79,52,
51,92,27,18,41,54,25,38,59,21,81,64,74,44,58,26,47,17,62,96,48,76,3,18,64,17,36,19,90,24,
99,3,11,25,73,4,55,69,31,39,74,97,77,59,47,36,39,21,14,39,27,71,41,27,41,20,83,53,40,58,98,
66,34,34,95,39,57,52,14,24,72,30,52,28,37,44,81,53,70,85,85,40,16,64,29,93,16,97,1,71,64,
78,90,52,75,93,10,50,20,100,4,22,90,12,37,17,17,98,82,96,40,86,7,31,50,65,52,80,57,36,66,
24,27,52,74,78,12,62,92,64,28,36,68,91,74,92,39,86,6,26,37,37,29,39,35,28,81,100,76,61,60,
59,24,46,100,9,6,50,6,96,64,27,100,36,38,34,11,58,34,1,100,37)
df <- data.frame(timestamp=1:n,value=x)
result <- CpTsSdEwma(
data = df$value,
n.train = 5,
threshold = 0.01,
l = 3,
m = 20
)
correct.results <- rep(0, 500)
correct.results[92] <- 1
expect_equal(as.numeric(result$is.anomaly), correct.results)
}) |
download_municipality_inventory <- function(url = get_current_url(),
path = getwd(), verbose = TRUE) {
destfile <- file.path(tempdir(), "municipality_inventory.zip")
curl::curl_download(url = url, destfile = destfile)
file_list_zip <- unzip(zipfile = destfile, list = TRUE)
file_list_zip <- as_tibble(file_list_zip)
file_list_zip <- add_column(file_list_zip, is_xml = grepl(".xml", file_list_zip$Name))
file_list_zip <- mutate(file_list_zip, is_draft = grepl("DRAFT", Name))
file_list_zip <- filter(file_list_zip, is_draft != TRUE)
file_list_zip_relevant <- filter(file_list_zip, is_xml == TRUE)
unzip(zipfile = destfile, files = file_list_zip_relevant$Name, exdir = tempdir(), overwrite = FALSE)
copy_success <- file.copy(file.path(tempdir(), file_list_zip_relevant$Name), to = path, overwrite = FALSE)
if (!copy_success)
stop(paste0("XML File already exists at target (", path, ") location"))
xml_file_path <- file.path(path, basename(file_list_zip_relevant$Name))
if (verbose) {
mutations_object <- import_CH_municipality_inventory(file_path = xml_file_path)
mutations <- mutations_object$mutations
change_date_max <- max(mutations$change_date)
message <- paste0("Municipal inventory successfully obtained. Most recent mutations enregistered: ",
format(change_date_max, "%d.%m.%Y"), ".")
message(message)
}
return(xml_file_path)
} |
rm(list = ls())
source("helper.R")
context("test-rowcolstats.R")
n <- 10
m <- 15
set.seed(14)
tt <- matrix(rnorm(m*n),n,m)
tt[tt<0] <- 0
ss <- as.spam(tt)
test_that("rowcolstats", {
spamtest_eq(rowSums.spam(ss),rowSums(tt))
spamtest_eq(colSums.spam(ss),colSums(tt))
spamtest_eq(rowSums(ss),rowSums(tt))
spamtest_eq(colSums(ss),colSums(tt))
options(spam.structurebased=FALSE)
spamtest_eq(rowMeans.spam(ss),rowMeans(tt))
spamtest_eq(colMeans.spam(ss),colMeans(tt))
spamtest_eq(rowMeans(ss),rowMeans(tt))
spamtest_eq(colMeans(ss),colMeans(tt))
options(spam.structurebased=TRUE)
spamtest_eq(rowMeans.spam(ss),rowSums(tt)/apply(tt>0,1,sum))
spamtest_eq(colMeans.spam(ss),colSums(tt)/apply(tt>0,2,sum))
spamtest_eq(rowMeans(ss),rowSums(tt)/apply(tt>0,1,sum))
spamtest_eq(colMeans(ss),colSums(tt)/apply(tt>0,2,sum))
spamtest_eq(rowMeans.spam(ss),apply.spam(ss,1,mean))
spamtest_eq(colMeans.spam(ss),apply.spam(ss,2,mean))
spamtest_eq(rowMeans(ss),apply.spam(ss,1,mean))
spamtest_eq(colMeans(ss),apply.spam(ss,2,mean))
spamtest_eq(rowMeans.spam(spam(0,n,m)),rowMeans(tt*0), relative = FALSE)
spamtest_eq(colMeans.spam(spam(0,n,m)),colMeans(tt*0), relative = FALSE)
spamtest_eq(rowMeans.spam(as.spam(diag(0,n))),rowMeans(diag(0,n)), relative = FALSE)
spamtest_eq(colMeans.spam(as.spam(diag(0,n))),colMeans(diag(0,n)), relative = FALSE)
spamtest_eq(rowMeans(spam(0,n,m)),rowMeans(tt*0), relative = FALSE)
spamtest_eq(colMeans(spam(0,n,m)),colMeans(tt*0), relative = FALSE)
spamtest_eq(rowMeans(as.spam(diag(0,n))),rowMeans(diag(0,n)), relative = FALSE)
spamtest_eq(colMeans(as.spam(diag(0,n))),colMeans(diag(0,n)), relative = FALSE)
options(spam.structurebased=TRUE)
}) |
calcAcq <- function(par, scoreGP, timeGP, acq, y_max, kappa, eps) {
p <- matrix(par,ncol=length(par),dimnames = list(NULL,names(par)))
GP_Pred <- predict(scoreGP,p,type="SK")
if (acq == "ucb") {
return((GP_Pred$mean + kappa * (GP_Pred$sd)))
} else if (acq == "ei") {
z <- (GP_Pred$mean - y_max - eps) / (GP_Pred$sd)
return(((GP_Pred$mean - y_max - eps) * pnorm(z) + (GP_Pred$sd) * dnorm(z)))
} else if (acq == "eips") {
GPe_Pred <- predict(timeGP,p,type="SK")
z <- (GP_Pred$mean - y_max - eps) / (GP_Pred$sd)
return(((GP_Pred$mean - y_max - eps) * pnorm(z) + (GP_Pred$sd) * dnorm(z))/GPe_Pred$mean)
} else if (acq == "poi") {
z <- (GP_Pred$mean - y_max - eps) / (GP_Pred$sd)
return((pnorm(z)))
}
} |
getClinDT <- function(data,
nonVisibleVar = NULL, nonVisible = NULL,
percVar = NULL,
barVar = NULL,
barColorThr = NULL,
barRange = NULL,
filter = "top",
searchBox = FALSE,
pageLength,
fixedColumns = NULL,
columnsWidth = NULL,
options = list(),
expandVar = NULL, expandIdx = NULL,
escape = TRUE,
rowGroup = NULL, rowGroupVar = NULL,
vAlign = "top",
callback = NULL,
buttons = getClinDTButtons(),
scrollX = TRUE,
file = NULL,
verbose = TRUE,
...){
extraArgs <- list(...)
isSharedData <- inherits(x = data, what = "SharedData")
dataContent <- if(isSharedData){
data$origData()
}else data
if(inherits(dataContent, "tbl_df")){
dataContent <- as.data.frame(dataContent)
}
if(!inherits(dataContent, c("data.frame", "matrix")))
stop("'data' should be a data.frame, a matrix, a tibble or a SharedData object.")
colnames <- extraArgs$colnames
if(!is.null(colnames)){
colnames <- colnames[colnames %in% colnames(dataContent)]
if(length(colnames) == 0){
colnames <- NULL
warning("'colnames' doesn't contain labels for columns in data. ",
"Are you sure you have specified it correctly (c([newName] = [oldName], ...)?")
}
extraArgs$colnames <- colnames
}
if(!is.null(nonVisible))
warning("'nonVisible' is deprecated, please use: 'nonVisibleVar' instead.")
nonVisibleVar <- checkVarInData(var = nonVisibleVar, data = dataContent, label = "non-visible")
if(!is.null(nonVisibleVar)){
if(!is.null(nonVisible))
warning("'nonVisible' or 'nonVisibleVar' should be specified, 'nonVisibleVar' is used")
nonVisible <- match(nonVisibleVar, colnames(dataContent))-1
}
if(missing(pageLength)){
pageLength <- ifelse(nrow(dataContent) <= 10, Inf, 10)
}
if(!is.null(rowGroup)){
warning("'rowGroup' is deprecated, please use: 'rowGroupVar' instead.")
rowGroupVar <- rowGroup
}
rowGroupVar <- checkVarInData(var = rowGroupVar, data = dataContent, label = "row group")
if(!is.null(rowGroupVar)){
rowGroup <- match(rowGroupVar, colnames(dataContent))-1
if(length(rowGroup) == 0) rowGroup <- NULL
}else rowGroup <- NULL
if(is.logical(escape)){
if(length(escape) != 1){
stop("If escape is logical, it should be of length 1.")
}else{
if(escape){
escape <- seq(from = 1, to = ncol(dataContent))
}else{
escape <- numeric()
}
}
}else if(is.numeric(escape)){
idxEscNotInData <- escape[!abs(escape) %in% seq_len(ncol(dataContent))]
if(length(idxEscNotInData) > 0){
stop("'Escape' contains columns not in data: ", toString(idxEscNotInData), ".")
}
if(any(escape < 0)){
if(!all(escape < 0))
stop("If 'escape' contains negative elements, they should all be negative.")
escape <- setdiff(seq(from = 1, to = ncol(dataContent)), -escape)
}
}
if(!is.null(rowGroup))
nonVisible <- union(nonVisible, rowGroup)
idxControl <- NULL
expandVar <- checkVarInData(var = expandVar, data = dataContent, label = "expandable")
isExpandIdxWrong <-
!is.null(expandIdx) && (
(!is.matrix(expandIdx)) ||
!all(c("row", "col") %in% colnames(expandIdx))
)
if(isExpandIdxWrong){
stop("'expandIdx' should be a matrix with columns: ",
"'row' and 'col'.")
}
if(!is.null(expandVar) | !is.null(expandIdx)){
if(!is.null(expandIdx)){
idxExpandVar <- unique(expandIdx[, "col"])
for(iCol in seq_along(idxExpandVar)){
idxCol <- idxExpandVar[iCol]
idxColNew <- idxCol + iCol - 1
expandIdxCol <- expandIdx[which(expandIdx[, "col"] %in% idxCol), , drop = FALSE]
expandIdxCol[, "col"] <- idxColNew
expandRow <- rep(NA_character_, nrow(dataContent))
expandRow[expandIdxCol[, "row"]] <- dataContent[expandIdxCol]
dataContent[expandIdxCol] <- '⊕'
idxBefore <- seq_len(idxColNew)
idxAfter <- setdiff(seq_len(ncol(dataContent)), idxBefore)
dataContent <- cbind(
dataContent[, idxBefore, drop = FALSE],
expandRow = expandRow,
dataContent[, idxAfter, drop = FALSE]
)
}
newIdxForExpandVar <- idxExpandVar + seq_along(idxExpandVar)-1
getCol <- function(x){x}
body(getCol) <- bquote({
xNew <- sapply(x, function(xI){
idxDiff <- xI-.(idxExpandVar)
idxDiff <- idxDiff[idxDiff > 0]
ifelse(length(idxDiff) > 0, xI + which.min(idxDiff), xI)
})
return(xNew)
})
getColFormatStyle <- function(x){x}
body(getColFormatStyle) <- bquote(.(getCol)(x)-1)
idxControl <- getCol(idxExpandVar)-1
escapeExpand <- getCol(idxExpandVar)
nonVisibleExpand <- getCol(idxExpandVar)
expandJS <- paste0("' + d[iCol + 1]+ '")
callback <- JS(
paste0("
table.column(1).nodes().to$().css({cursor: 'pointer'});
var format = function(d, iCol) {
return '<div>",
expandJS,
"</div>';
};
table.on('click', 'td.details-control', function() {
var td = $(this), row = table.row(td.closest('tr')), iCol = td[0]._DT_CellIndex['column'];
if (row.child.isShown()) {
row.child.hide();
td.html('⊕');
} else {
oldVal = format(row.data(), iCol-1);
if(oldVal === '<div>⊕</div>'){
row.child(format(row.data(), iCol)).show();
td.html('⊖');
}
}
});"
),
callback
)
}else if(!is.null(expandVar)){
idxExpandVar <- which(colnames(dataContent) %in% expandVar)
getCol <- function(x) return(x+1)
getColFormatStyle <- function(x) return(x)
dataContent <- cbind(' ' = '⊕', dataContent)
idxControl <- 0
escapeExpand <- 1
nonVisibleExpand <- idxExpandVar
expandJS <- paste(sapply(idxExpandVar, function(i){
labelI <- colnames(dataContent)[getCol(i)]
if(!is.null(colnames)){
labelCNI <- names(colnames)[match(labelI, colnames)]
if(!is.na(labelCNI)) labelI <- labelCNI
}
paste0(labelI, ": ' + d[", i, "] + '")
}), collapse = "<br>")
callback <- JS(
paste0("
table.column(1).nodes().to$().css({cursor: 'pointer'});
var format = function(d) {
return '<div>",
expandJS,
"</div>';
};
table.on('click', 'td.details-control', function() {
var td = $(this), row = table.row(td.closest('tr'));
if (row.child.isShown()) {
row.child.hide();
td.html('⊕');
} else {
row.child(format(row.data())).show();
td.html('⊖');
}
});"
),
callback
)
}
escape <- setdiff(getCol(escape), escapeExpand)
nonVisible <- union(getCol(nonVisible), nonVisibleExpand)
}else{
getColFormatStyle <- getCol <- function(x) return(x)
callback <- callback
}
if(any(nonVisible >= ncol(dataContent)))
stop(paste(
"'nonVisible' should contain indices of columns within data (< ncol(data)).",
"Are you sure you are using Javascript indexing",
"(0 for first column, 1 for second column and so on)?"
))
if(!is.null(options$columnDefs)){
options$columnDefs <- sapply(options$columnDefs, function(x){
if(is.list(x) && "targets" %in% names(x)){
x[["targets"]] <- getCol(x[["targets"]])
}
x
}, simplify = FALSE)
}
columnDefs <- c(
options$columnDefs,
if(!is.null(columnsWidth)){
list({
columnsWidths <- rep(columnsWidth, length.out = ncol(dataContent))
lapply(seq_along(columnsWidths), function(i)
list(targets = getCol(i), columnsWidth = columnsWidths[i])
)
})
},
if(!is.null(nonVisible))
list(list(targets = nonVisible, visible = FALSE, className = 'noVis')),
if(!is.null(idxControl))
columnDefs <- list(list(orderable = FALSE, className = 'details-control', targets = idxControl))
)
isOptionAvailable <- function(options, label){
isOptionAvailable <- !label %in% names(options)
if(!isOptionAvailable & verbose){
message("The", sQuote(label), " specified in 'options' overwrites the default.")
}
return(isOptionAvailable)
}
if(isOptionAvailable(options, "dom")){
domDefault <- paste0(
if(length(buttons) > 0) 'B',
if(pageLength < Inf) "l",
if(searchBox) 'f',
'rt',
if(pageLength < Inf) "ip"
)
options[["dom"]] <- domDefault
}
if(!is.null(fixedColumns)){
idx <- which(names(fixedColumns) %in% c("leftColumns", "rightColumns"))
if(length(idx) > 0)
fixedColumns[idx] <- sapply(fixedColumns[idx], getCol, simplify = FALSE)
if(isOptionAvailable(options, "fixedColumns")){
options[["fixedColumns"]] <- fixedColumns
}
}
if(isOptionAvailable(options, "fixedHeader")){
options[["fixedHeader"]] <- if(is.null(fixedColumns)) TRUE else FALSE
}
if(isOptionAvailable(options, "buttons")){
options[["buttons"]] <- buttons
}
if(isOptionAvailable(options, "searching")){
options[["searching"]] <- TRUE
}
if(isOptionAvailable(options, "scrollX")){
options[["scrollX"]] <- scrollX
}
if(isOptionAvailable(options, "autoWidth")){
options[["autoWidth"]] <- (!is.null(columnsWidth))
}
if(isOptionAvailable(options, "pageLength")){
options[["pageLength"]] <- ifelse(pageLength == Inf, nrow(dataContent), pageLength)
}
if(length(rowGroup) > 0 && isOptionAvailable(options, "rowGroup")){
rowGroup <- getCol(rowGroup)
options[["rowGroup"]] <- list(dataSrc = rowGroup)
columnDefs <- c(columnDefs,
list(list(targets = rowGroup, className = "rowGroup"))
)
}
if(length(columnDefs) > 0){
options[["columnDefs"]] <- columnDefs
}
if(length(options) == 0) options <- NULL
extensions <- c(
if(!is.null(rowGroup)) "RowGroup",
if(length(buttons) > 0) "Buttons",
if(!is.null(fixedColumns)) c("FixedColumns", "Scroller"),
if(is.null(fixedColumns)) "FixedHeader"
)
dataDT <- if(isSharedData){
if(nrow(dataContent) != length(data$key()))
stop("Key vector is of different length than the number of records in the data.")
keySD <- data$.__enclos_env__$private$.key
SharedData$new(data = dataContent, key = keySD, group = data$groupName())
}else dataContent
argsDT <- list(
data = dataDT,
rownames = FALSE,
filter = filter,
extensions = extensions,
options = options,
escape = escape
)
if(!is.null(callback)) argsDT <- c(argsDT, list(callback = callback))
extraArgsSpec <- intersect(names(extraArgs), names(argsDT))
if(length(extraArgsSpec) > 0){
warning(paste("Extra parameter(s)", toString(sQuote(extraArgsSpec)),
"are ignored because some internal defaults are set for these parameters."
))
extraArgs <- extraArgs[setdiff(names(extraArgs), extraArgsSpec)]
}
argsDT <- c(argsDT, extraArgs)
tableDT <- do.call(datatable, argsDT)
if(!is.null(percVar))
tableDT <- DT::formatPercentage(tableDT, columns = percVar, digits = 2)
tableDT <- formatDTBarVar(
tableDT = tableDT,
data = dataContent,
barVar = barVar,
barColorThr = barColorThr,
barRange = barRange,
getCol = getColFormatStyle
)
if(!is.null(vAlign)){
tableDT <- tableDT %>% formatStyle(
columns = seq_len(ncol(dataContent)),
'vertical-align' = vAlign
)
}
if(!is.null(file)){
if(file_ext(file) != "html")
stop("'file' should be of extension 'html'.")
wdInit <- getwd();on.exit(setwd(wdInit))
setwd(dirname(file))
htmlwidgets::saveWidget(widget = tableDT, file = basename(file))
}
return(tableDT)
}
formatDTBarVar <- function(
tableDT,
data,
barVar = NULL,
barColorThr = NULL,
barRange = NULL,
getCol = function(x) x){
barVar <- checkVarInData(var = barVar, data = data, label = "bar")
if(!is.null(barVar)){
barVarNotNum <- barVar[!sapply(data[, barVar, drop = FALSE], is.numeric)]
if(length(barVarNotNum) > 0){
warning(paste(toString(barVarNotNum), "variable(s)",
"not represented as bar because they are not numeric.")
)
barVar <- setdiff(barVar, barVarNotNum)
}
getElFromList <- function(param, var){
if(!is.null(param)){
if(!is.null(names(param))){
if(var %in% names(param)){
param[[var]]
}
}else param
}
}
for(var in barVar){
idxVar <- getCol(match(var, colnames(data)))
barColorThrVar <- getElFromList(param = barColorThr, var = var)
barRangeVar <- getElFromList(param = barRange, var = var)
if(is.null(barRangeVar)) barRangeVar <- range(as.numeric(data[, var]), na.rm = TRUE)
barRangeVar[1] <- barRangeVar[1] - diff(barRangeVar)*0.01
barColor <- if(!is.null(barColorThrVar)){
styleInterval(
cuts = barColorThrVar,
values = viridis(length(barColorThrVar)+1)
)
}else "black"
barBg <- styleColorBar(
data = barRangeVar,
color = "green"
)
tableDT <- tableDT %>%
formatStyle(
columns = idxVar,
color = barColor,
background = barBg
)
}
}
return(tableDT)
}
checkVarInData <- function(var, data, label){
varNotInData <- setdiff(var, colnames(data))
if(length(varNotInData) > 0)
warning(paste(label, "variable(s):",
sQuote(toString(varNotInData)),
"not used because not available in the data."),
call. = FALSE)
var <- intersect(var, colnames(data))
if(length(var) == 0) var <- NULL
return(var)
}
getClinDTButtons <- function(
type = c("copy", "csv", "excel", "pdf", "print"),
typeExtra = NULL,
opts = NULL){
type <- unique(c(type, typeExtra))
type <- match.arg(
type,
choices = c("copy", "csv", "excel",
"pdf", "print", "colvis"),
several.ok = TRUE
)
getExportButton <- function(typeBtn, ...){
if(typeBtn %in% type){
c(
list(
extend = typeBtn,
...,
exportOptions = list(columns = list(".rowGroup", ":visible"))
),
opts[[typeBtn]],
...
)
}
}
buttons <- list(
getExportButton(typeBtn = "copy"),
getExportButton(typeBtn = "csv"),
getExportButton(typeBtn = "excel"),
getExportButton(typeBtn = "pdf"),
getExportButton(typeBtn = "print"),
if("colvis" %in% type)
c(
list(
extend = "colvis",
columns = ":not(.noVis)",
text = "Show/hide columns"
),
opts[["colvis"]]
)
)
buttons <- buttons[!sapply(buttons, is.null)]
return(buttons)
} |
library(hamcrest)
a <- structure(1L, class = c("A"))
b <- structure(1L, class = c("B"))
ab <- structure(1L, class = c("A", "B"))
abc <- structure(1L, class = c("A", "B", "C"))
c <- structure(1L, class = c("C"))
assertThat(inherits(a, "A"), identicalTo(TRUE))
assertThat(inherits(c, "A"), identicalTo(FALSE))
assertThat(inherits(1L, character(0)), identicalTo(FALSE))
assertThat(inherits(a, c("A", "B")), identicalTo(TRUE))
assertThat(inherits(ab, c("A", "B")), identicalTo(TRUE))
assertThat(inherits(c, c("A", "B")), identicalTo(FALSE))
assertThat(inherits(a, c("A", "B"), which = TRUE), identicalTo(c(1L, 0L)))
assertThat(inherits(ab, c("A", "B"), which = TRUE), identicalTo(c(1L, 2L))) |
ggwithinstats <- function(data,
x,
y,
type = "parametric",
pairwise.comparisons = TRUE,
pairwise.display = "significant",
p.adjust.method = "holm",
effsize.type = "unbiased",
bf.prior = 0.707,
bf.message = TRUE,
results.subtitle = TRUE,
xlab = NULL,
ylab = NULL,
caption = NULL,
title = NULL,
subtitle = NULL,
k = 2L,
conf.level = 0.95,
nboot = 100L,
tr = 0.2,
centrality.plotting = TRUE,
centrality.type = type,
centrality.point.args = list(
size = 5,
color = "darkred"
),
centrality.label.args = list(
size = 3,
nudge_x = 0.4,
segment.linetype = 4
),
centrality.path = TRUE,
centrality.path.args = list(
size = 1,
color = "red",
alpha = 0.5
),
point.args = list(
size = 3,
alpha = 0.5
),
point.path = TRUE,
point.path.args = list(
alpha = 0.5,
linetype = "dashed"
),
outlier.tagging = FALSE,
outlier.label = NULL,
outlier.coef = 1.5,
outlier.label.args = list(size = 3),
boxplot.args = list(
width = 0.2,
alpha = 0.5
),
violin.args = list(
width = 0.5,
alpha = 0.2
),
ggsignif.args = list(
textsize = 3,
tip_length = 0.01
),
ggtheme = ggstatsplot::theme_ggstatsplot(),
package = "RColorBrewer",
palette = "Dark2",
ggplot.component = NULL,
output = "plot",
...) {
c(x, y) %<-% c(ensym(x), ensym(y))
if (!quo_is_null(enquo(outlier.label))) ensym(outlier.label)
type <- stats_type_switch(type)
data %<>%
select({{ x }}, {{ y }}, outlier.label = {{ outlier.label }}) %>%
mutate({{ x }} := droplevels(as.factor({{ x }}))) %>%
group_by({{ x }}) %>%
mutate(.rowid = row_number()) %>%
ungroup(.) %>%
anti_join(x = ., y = filter(., is.na({{ y }})), by = ".rowid")
if (!"outlier.label" %in% names(data)) data %<>% mutate(outlier.label = {{ y }})
data %<>%
outlier_df(
x = {{ x }},
y = {{ y }},
outlier.coef = outlier.coef,
outlier.label = outlier.label
)
test <- ifelse(nlevels(data %>% pull({{ x }})) < 3, "t", "anova")
if (results.subtitle && check_if_installed("afex")) {
.f.args <- list(
data = data,
x = as_string(x),
y = as_string(y),
effsize.type = effsize.type,
conf.level = conf.level,
k = k,
tr = tr,
paired = TRUE,
bf.prior = bf.prior,
nboot = nboot,
top.text = caption
)
.f <- function_switch(test)
subtitle_df <- eval_f(.f, !!!.f.args, type = type)
subtitle <- if (!is.null(subtitle_df)) subtitle_df$expression[[1]]
if (type == "parametric" && bf.message) {
caption_df <- eval_f(.f, !!!.f.args, type = "bayes")
caption <- if (!is.null(caption_df)) caption_df$expression[[1]]
}
}
if (output != "plot") {
return(switch(output,
"caption" = caption,
subtitle
))
}
plot <- ggplot(data, aes({{ x }}, {{ y }}, group = .rowid)) +
exec(geom_point, aes(color = {{ x }}), !!!point.args) +
exec(geom_boxplot, aes({{ x }}, {{ y }}), inherit.aes = FALSE, !!!boxplot.args) +
exec(geom_violin, aes({{ x }}, {{ y }}), inherit.aes = FALSE, !!!violin.args)
if (test == "t" && point.path) plot <- plot + exec(geom_path, !!!point.path.args)
if (isTRUE(outlier.tagging)) {
plot <- plot +
exec(
.fn = ggrepel::geom_label_repel,
data = ~ filter(.x, isanoutlier),
mapping = aes(x = {{ x }}, y = {{ y }}, label = outlier.label),
min.segment.length = 0,
inherit.aes = FALSE,
!!!outlier.label.args
)
}
if (isTRUE(centrality.plotting)) {
plot <- centrality_ggrepel(
plot = plot,
data = data,
x = {{ x }},
y = {{ y }},
k = k,
type = stats_type_switch(centrality.type),
tr = tr,
centrality.path = centrality.path,
centrality.path.args = centrality.path.args,
centrality.point.args = centrality.point.args,
centrality.label.args = centrality.label.args
)
}
if (isTRUE(pairwise.comparisons) && test == "anova") {
mpc_df <- pairwise_comparisons(
data = data,
x = {{ x }},
y = {{ y }},
type = type,
tr = tr,
paired = TRUE,
p.adjust.method = p.adjust.method,
k = k
)
plot <- ggsignif_adder(
plot = plot,
mpc_df = mpc_df,
data = data,
x = {{ x }},
y = {{ y }},
pairwise.display = pairwise.display,
ggsignif.args = ggsignif.args
)
caption <- pairwise_caption(
caption,
bf.message = ifelse(type == "parametric", bf.message, FALSE),
unique(mpc_df$test.details),
ifelse(type == "bayes", "all", pairwise.display)
)
}
aesthetic_addon(
plot = plot,
x = data %>% pull({{ x }}),
xlab = xlab %||% as_name(x),
ylab = ylab %||% as_name(y),
title = title,
subtitle = subtitle,
caption = caption,
ggtheme = ggtheme,
package = package,
palette = palette,
ggplot.component = ggplot.component
)
}
grouped_ggwithinstats <- function(data,
...,
grouping.var,
output = "plot",
plotgrid.args = list(),
annotation.args = list()) {
data %<>% grouped_list(grouping.var = {{ grouping.var }})
p_ls <- purrr::pmap(
.l = list(data = data, title = names(data), output = output),
.f = ggstatsplot::ggwithinstats,
...
)
if (output == "plot") p_ls <- combine_plots(p_ls, plotgrid.args, annotation.args)
p_ls
} |
`draw.subgraph` <-
function(mesa) {
code <- ""
nitem <- ncol(mesa) - 1
npatt <- nrow(mesa)
edges <- matrix("n", nrow = npatt, ncol = npatt)
rownames(edges) <- rownames(mesa)
if (npatt > 1) {
for (i in 1:(npatt - 1)) {
for (j in (i+1):npatt) {
differs <- which(mesa[i,1:nitem] != mesa[j,1:nitem])
if(length(differs) == 2) {
if ((differs[2] - differs[1]) == 1) {
edges[i,j] <- "p"
edges[j,i] <- "a"
}
}
}
}
}
orphan <- logical(npatt)
orphan <- FALSE
if (npatt > 1) orphan <- apply(edges, 1, function(x) sum(x != "n") == 0)
for (i in 1:npatt) {
if(any(edges[i,] == "p")) {
path <- paste("node", rownames(mesa)[i], sep = "", collapse = "")
j <- i
while(any(edges[j,] == "p")) {
k <- which(edges[j,] == "p")[1]
path <- paste(path, "->", "node", rownames(mesa)[k],
sep = "", collapse = "")
edges[j, k] <- "y"
j <- k
}
code <- c(code, path, "\n")
}
}
for (i in 1:npatt) {
node <- paste("node", rownames(mesa)[i], ' [label = "',
rownames(mesa)[i], "\\n", mesa[i, nitem + 1], '"]',
sep = "", collapse = "")
code <- c(code, node, "\n")
}
if(any(orphan)) {
which.orphan <- which(orphan)
if(length(which.orphan) > 1) {
path <- paste("node",
rownames(mesa)[which.orphan[1]], sep = "", collapse = "")
for (i in 2:length(which.orphan)) {
path <- paste(path, "->", "node", rownames(mesa)[which.orphan[i]],
sep = "", collapse = "")
}
code <- c(code, "edge [style = invis]\n", path, "\n")
}
}
code
} |
lm.mp <- function(Y,formula, store.fitted=FALSE) {
X = model.matrix(formula)
n = dim(X)[1]
p = dim(X)[2]
XtX.inv = solve(crossprod(X))
I.H = diag(n) - X %*% tcrossprod(XtX.inv, X)
coef = XtX.inv %*% crossprod(X, Y)
sigma2 = apply(I.H %*% Y, 2, crossprod) / (n-p)
se.coef = sqrt(diag(XtX.inv) %o% sigma2)
fitted=if (store.fitted) X %*% coef else NULL
otpt = list(coef=coef, sigma2=sigma2, se.coef=se.coef, X=X, fitted=fitted)
class(otpt) = "lm.mp"
otpt
} |
getLMs <- function(Gridnam,Famnam,xi=0.7, baseDir="C:/rtest/robast", withPrint=FALSE, withLoc = FALSE){
file <- file.path(baseDir, "branches/robast-0.9/pkg/RobAStRDA/R/sysdata.rda")
if(!file.exists(file)) stop("Fehler mit Checkout")
nE <- new.env()
load(file, envir=nE)
Gnams <- c("Sn","OMSE","RMXE","MBRE")
Fnams <- c("Generalized Pareto Family",
"GEVU Family",
"GEV Family",
"Gamma family",
"Weibull Family")
Gridnam <- Gnams[pmatch(Gridnam, Gnams)]
Famnam <- Fnams[pmatch(Famnam, Fnams)]
if(! Gridnam %in% Gnams) stop("Falscher Gittername")
if(! Famnam %in% Fnams) stop("Falscher Familienname")
Famnam0 <- gsub(" ","",Famnam)
isSn <- (Gridnam == "Sn")
GN0 <- Gridnam; if(isSn) GN0 <- "SnGrids"
GN <- paste(".",GN0, sep="")
funN <- paste("fun",".",if(getRversion()<"2.16") "O" else "N",sep="")
if(withPrint) print(c(GN, Famnam0, funN))
fct <- get(GN,envir=nE)[[Famnam0]][[funN]]
if(!isSn){
len <- length(fct)
LM <- sapply(1:len, function(i) fct[[i]](xi))
if(length(xi)==1) LM <- matrix(LM,ncol=len)
if(withLoc){
colnames(LM) <- c("b","a1.a", "a2.a", "a3.a", "a1.i", "a2.i", "a3.i",
"A11.a", "A12.a", "A13.a", "A21.a", "A22.a", "A23.a",
"A31.a", "A32.a", "A33.a", "A11.i", "A12.i", "A13.i",
"A21.i", "A22.i", "A23.i", "A31.i", "A32.i", "A33.i")
}else{
colnames(LM) <- c("b","a1.a", "a2.a", "a1.i", "a2.i", "A11.a",
"A12.a", "A21.a", "A22.a", "A11.i", "A12.i",
"A21.i", "A22.i")
}
return(cbind(xi,LM))
}else{
Sn <- fct(xi)
return(cbind(xi,Sn))
}
} |
library(ggplot2)
library(testassay)
d <- gia
tab<-table(d$sample,d$assay)
rowNames<-dimnames(tab)[[1]]
n.ones<-function(x){
length(x[x==1])
}
nOnes<-apply(tab,1,n.ones)
sample4<-names(nOnes[nOnes==4])
td7samp<- sample4[grep("3D7",sample4)]
fvosamp<- sample4[grep("FVO",sample4)]
J<- d$sample %in% td7samp
tab3d7<-table(d$sample[J],d$assay[J])
J<- d$sample %in% fvosamp
tabfvo<-table(d$sample[J],d$assay[J])
summary(gia)
ggplot(d, aes(x = gia, y = meanAAgia, color = parasite)) +
geom_abline(slope = 1, intercept = 0, color = "gray", size = 1.5) + geom_point() +
scale_x_continuous("GIA", limits = c(-5, 100), breaks = seq(0, 100, by = 20)) +
scale_y_continuous("mean GIA (per sample)", limits = c(-5, 100), breaks = seq(0, 100, by = 20)) + theme_bw() +
theme(legend.position = c(.85, .2))
treD7.test <- testassay(x = gia,
m = sample, n = assay, q = .9,
model = "normal", constant = "variance",
data = subset(gia, parasite == "3D7" & meanAAgia < 80))
treD7.test
obsD7 <- rnorm(5, mean = 50, sd = 18)
predict(treD7.test, newdata = obsD7)
FVO.test <- testassay(x = gia,
m = sample, n = assay, q = .9,
model = "normal", constant = "variance",
data = subset(gia, parasite == "FVO" & meanAAgia < 80))
FVO.test
predict(FVO.test)
predat <- cbind(subset(gia, parasite == "FVO" & meanAAgia < 80), predict(FVO.test))
ggplot(predat,
aes(x = assay, y = obs, ymin = lower, ymax = upper)) +
geom_pointrange() + facet_wrap(~ sample) + ylab("GIA")
newobs <- c(25, 40, 65)
predict(treD7.test, newobs)
cvn <- testassay(x = gia,
m = sample, n = assay, q = .9,
model = "normal", constant = "cv",
data = subset(gia, parasite == "3D7" & meanAAgia < 80))
predict(cvn, newobs)
cvln <- testassay(x = gia,
m = sample, n = assay, q = .9,
model = "lognormal", constant = "cv",
data = subset(gia, parasite == "3D7" & meanAAgia < 80))
predict(cvln, newobs) |
{
dat <- readr::read_csv('
"email", "first_name", "thing"
"[email protected]", "friend", "something good"
"[email protected]", "foe", "something bad"
',
col_types = "ccc")
msg <- '
---
subject: Your subject line
---
Hi, {first_name}
I am writing to tell you about {thing}.
HTH
Me
'
}
test_that("send mail from pre-imported dat", {
withr::local_envvar(list(mailmerge_test = TRUE))
mockery::stub(mail_merge, "gmailr::gm_has_token", TRUE)
to <- "[email protected]"
body <- "hello world"
subject <- "subject"
mm_send_mail(to = to, body = body, subject = subject) %>%
expect_type("list")
mm_read_message(msg) %>%
expect_type("list")
z <- dat %>%
mail_merge(msg, send = "preview")
expect_s3_class(z, "mailmerge_preview")
expect_true(grepl(dat$email[1], z[[1]], fixed = TRUE))
expect_true(grepl(dat$email[2], z[[2]], fixed = TRUE))
expect_equal(nrow(dat), length(z))
tf <- tempfile(fileext = ".txt")
writeLines(msg[-(1:3)], con = tf)
mm_read_message(tf) %>%
expect_type("list")
z <- mail_merge(dat, tf, send = "preview")
expect_s3_class(z, "mailmerge_preview")
expect_true(grepl(dat$email[1], z[[1]], fixed = TRUE))
expect_true(grepl(dat$email[2], z[[2]], fixed = TRUE))
expect_equal(nrow(dat), length(z))
})
test_that("error message if not authed", {
mockery::stub(mail_merge, "gmailr::gm_has_token", FALSE)
to <- "[email protected]"
body <- "hello world"
subject <- "subject"
tf <- tempfile(fileext = ".txt")
writeLines(msg[-(1:3)], con = tf)
mail_merge(dat, tf, send = "draft") %>%
expect_error(
"You must authenticate with gmailr first. Use `gmailr::gm_auth()"
)
})
test_that("yesno() messages are meaningful", {
mockery::stub(mail_merge, "gmailr::gm_has_token", TRUE)
mockery::stub(mail_merge, "yesno", TRUE)
to <- "[email protected]"
body <- "hello world"
subject <- "subject"
tf <- tempfile(fileext = ".txt")
writeLines(msg[-(1:3)], con = tf)
mail_merge(dat, tf, send = "draft") %>%
expect_output(
"Send 2 emails (draft)?"
) %>%
expect_null()
mail_merge(dat, tf, send = "immediately") %>%
expect_output(
"Send 2 emails (immediately)?"
) %>%
expect_null()
})
test_that("mail_merge returns correct list output", {
mockery::stub(mm_send_mail, "gmailr::gm_create_draft", function(...)stop("mock error"))
mockery::stub(mm_send_mail, "gmailr::gm_send_message", function(...)list(id = "mock", labelIDs = list("mock")))
to <- "[email protected]"
body <- "{first_name}"
subject <- "subject"
tf <- tempfile(fileext = ".txt")
writeLines("{first_name}", con = tf)
expect_warning(
mm_send_mail(to = to, body = body, subject = subject, draft = TRUE),
"mock error"
)
suppressWarnings(
z <- mm_send_mail(to = to, body = body, subject = subject, draft = TRUE)
)
expect_false(z$success)
z <- mm_send_mail(to = to, body = body, subject = subject, draft = FALSE)
expect_true(z$success)
})
test_that("mail_merge() correctly counts number of messages", {
mockery::stub(mail_merge, "gmailr::gm_has_token", TRUE)
tf <- tempfile(fileext = ".txt")
writeLines("{first_name}", con = tf)
mockery::stub(mm_send_mail, "gmailr::gm_send_message", function(...)stop("mock error"))
suppressWarnings(
mail_merge(dat, tf, send = "draft", confirm = TRUE)
) %>%
expect_message("Sent 0 messages to your draft folder")
})
test_that("mail_merge() correctly counts number of messages", {
to <- "[email protected]"
body <- "hello world"
subject <- "subject"
tf <- tempfile(fileext = ".txt")
writeLines(msg[-(1:3)], con = tf)
mockery::stub(mail_merge, "gmailr::gm_has_token", TRUE, depth = 1)
mockery::stub(mail_merge, "gmailr::gm_send_message", function(...)list(id = "mock", labelIDs = list("mock")), depth = 2)
expect_message(
suppressWarnings(
z <- mail_merge(dat, tf, send = "immediately", confirm = TRUE)
),
"Sent 0 messages to email"
)
}) |
wflow_publish <- function(
files = NULL,
message = NULL,
all = FALSE,
force = FALSE,
update = FALSE,
republish = FALSE,
combine = "or",
view = getOption("workflowr.view"),
delete_cache = FALSE,
seed = 12345,
verbose = FALSE,
dry_run = FALSE,
project = "."
) {
files <- process_input_files(files, allow_null = TRUE, files_only = FALSE,
convert_to_relative_paths = TRUE)
if (is.null(message)) {
message <- deparse(sys.call())
message <- paste(message, collapse = "\n")
} else if (is.character(message)) {
message <-create_newlines(message)
} else {
stop("message must be NULL or a character vector")
}
assert_is_flag(all)
assert_is_flag(force)
assert_is_flag(update)
assert_is_flag(republish)
combine <- match.arg(combine, choices = c("or", "and"))
assert_is_flag(view)
assert_is_flag(delete_cache)
if (!(is.numeric(seed) && length(seed) == 1))
stop("seed must be a one element numeric vector")
assert_is_flag(verbose)
assert_is_flag(dry_run)
check_wd_exists()
assert_is_single_directory(project)
project <- absolute(project)
if (isTRUE(getOption("workflowr.autosave"))) autosave()
s0 <- wflow_status(project = project)
r <- git2r::repository(path = s0$git)
commit_current <- git2r::commits(r, n = 1)[[1]]
if (!dry_run) check_git_config(project, "`wflow_publish`")
if (is.null(files) && !all && !update && !republish && !dry_run)
stop("You did not tell wflow_publish() what to publish.\n",
"Unlike wflow_build(), it requires that you name the Rmd files you want to publish.\n")
scenario1 <- !is.null(files) &&
any(unlist(s0$status[files, c("mod_unstaged", "mod_staged", "scratch")]),
na.rm = TRUE)
scenario2 <- all &&
any(unlist(s0$status[s0$status$tracked, c("mod_unstaged", "mod_staged")]),
na.rm = TRUE)
scenario3 <- !is.null(files) &&
any(!(files %in% rownames(s0$status)))
if (scenario1 || scenario2 || scenario3) {
step1 <- wflow_git_commit_(files = files, message = message,
all = all, force = force,
dry_run = dry_run, project = project)
on.exit(git2r::reset(commit_current, reset_type = "mixed"), add = TRUE)
s1 <- wflow_status(project = project)
} else {
step1 <- NULL
s1 <- s0
}
files_to_build <- character()
files_to_build <- union(files_to_build,
files[files %in% rownames(s1$status)])
files_to_build <- union(files_to_build,
step1$commit_files[
step1$commit_files %in% rownames(s1$status)])
if (combine == "and" && length(files_to_build) == 0) {
stop("combine = \"and\" can only be used when explicitly specifying Rmd files to build with the argument `files`")
}
if (combine == "and") {
combine_files_function <- intersect
} else if (combine == "or") {
combine_files_function <- union
}
if (republish) {
files_to_build <- combine_files_function(files_to_build,
rownames(s1$status)[s1$status$published])
}
if (update) {
files_to_build <- combine_files_function(files_to_build,
rownames(s1$status)[s1$status$mod_committed])
}
files_to_build <- files_to_build[!s1$status[files_to_build, "mod_unstaged"]]
files_to_build <- files_to_build[!s1$status[files_to_build, "mod_staged"]]
if (length(files_to_build) > 0) {
if (fs::dir_exists(s1$docs) && !dry_run) {
docs_backup <- tempfile(pattern = sprintf("docs-backup-%s-",
format(Sys.time(),
"%Y-%m-%d-%Hh-%Mm-%Ss")))
fs::dir_create(docs_backup)
docs_backup <- absolute(docs_backup)
file.copy(from = file.path(s1$docs, "."), to = docs_backup,
recursive = TRUE, copy.date = TRUE)
on.exit(unlink(s1$docs, recursive = TRUE), add = TRUE)
on.exit(fs::dir_create(s1$docs), add = TRUE)
on.exit(file.copy(from = file.path(docs_backup, "."), to = s1$docs,
recursive = TRUE, copy.date = TRUE), add = TRUE)
}
step2 <- wflow_build_(files = files_to_build, make = FALSE,
update = update, republish = republish,
combine = combine,
view = view, clean_fig_files = TRUE,
delete_cache = delete_cache, seed = seed,
local = FALSE, verbose = verbose,
log_dir = use_default_log_dir(),
dry_run = dry_run, project = project)
} else {
step2 <- NULL
}
if (length(step2$built) > 0) {
figs_path <- vapply(step2$built, create_figure_path, character(1))
dir_figure <- file.path(s0$docs, figs_path)
site_libs <- file.path(s0$docs, "site_libs")
docs_nojekyll <- file.path(s0$docs, ".nojekyll")
docs_css <- list.files(path = s0$docs, pattern = "css$", full.names = TRUE)
docs_js <- list.files(path = s0$docs, pattern = "js$", full.names = TRUE)
files_to_commit <- c(step2$html, dir_figure, site_libs, docs_nojekyll,
docs_css, docs_js)
step3 <- wflow_git_commit_(files = files_to_commit, message = "Build site.",
all = FALSE, force = force,
dry_run = dry_run, project = project)
} else {
step3 <- NULL
}
o <- list(step1 = step1, step2 = step2, step3 = step3)
class(o) <- "wflow_publish"
on.exit()
return(o)
}
print.wflow_publish <- function(x, ...) {
cat("Summary from wflow_publish\n\n")
cat("**Step 1: Commit analysis files**\n\n")
if (is.null(x$step1)) {
cat("No files to commit\n\n")
} else {
print(x$step1)
}
cat("\n**Step 2: Build HTML files**\n\n")
if (is.null(x$step2)) {
cat("No files to build\n\n")
} else {
print(x$step2)
}
cat("\n**Step 3: Commit HTML files**\n\n")
if (is.null(x$step3)) {
cat("No HTML files to commit\n\n")
} else {
print(x$step3)
}
return(invisible(x))
} |
explore_space_pca <- function(dt, details = FALSE, pca = TRUE, group = NULL, color = NULL,
..., animate = FALSE) {
if (rlang::quo_is_null(dplyr::enquo(color))) color <- dplyr::enexpr(group)
if (pca) dt <- compute_pca(dt, group = {{ group }}, ...) %>% purrr::pluck("aug")
p <- ggplot2::ggplot() +
add_space(dt = get_space_param(dt, ...), ...) +
add_start(dt = get_start(dt), start_color = {{ color }}, ...) +
add_end(dt = get_best(dt, group = {{ group }}), end_color = {{ color }}, ...) +
add_interp(
dt = get_interp(dt, group = {{ group }}),
interp_alpha = .data[["id"]], interp_color = {{ color }}, interp_group = {{ group }}, ...
) +
ggplot2::scale_alpha_continuous(range = c(0.3, 1), guide = "none") +
ggplot2::theme_void() +
ggplot2::theme(aspect.ratio = 1, legend.position = "bottom", legend.title = ggplot2::element_blank())
if (details) {
p <- p +
add_anchor(dt = get_anchor(dt), anchor_color = {{ color }}, ...) +
add_interp_last(dt = get_interp_last(dt, group = {{ group }}), interp_last_color = {{ color }}, ...) +
add_interrupt(
dt = get_interrupt(dt, group = {{ group }}),
interrupt_color = {{ color }}, interrupt_group = interaction(.data[["tries"]], {{ group }}), ...
)
p <- p +
add_search(dt = get_search(dt), search_color = {{ color }}, ...)
if (!is.null(get_dir_search(dt, ...))){
p <- p + add_dir_search(dt = get_dir_search(dt, ...), dir_color = {{ color }}, ...)
}
if (nrow(get_start(dt)) > 1) p <- p + add_anno(dt = get_start(dt), ...)
}
if (animate) {
p <- ggplot2::ggplot() +
add_space(dt = get_space_param(dt), ...) +
add_start(dt = get_start(dt) %>% dplyr::select(-.data[["id"]]), start_color = {{ color }}, ...) +
add_interp(
dt = get_interp(dt, group = {{ group }}),
interp_alpha = .data[["id"]], interp_color = {{ color }}, interp_group = {{ group }}, ...
) +
ggplot2::scale_alpha_continuous(range = c(0.3, 1), guide = "none") +
ggplot2::theme_void() +
ggplot2::theme(aspect.ratio = 1, legend.position = "bottom", legend.title = ggplot2::element_blank()) +
gganimate::transition_reveal(along = .data[["id"]])
}
if ("theoretical" %in% dt$info) p <- p + add_theo(dt = get_theo(dt), ...)
p
}
flip_sign <- function(dt, group = NULL, ...) {
if (!rlang::quo_is_null(dplyr::enquo(group))) {
group_name <- dt %>%
get_best(group = {{ group }}) %>%
dplyr::pull({{ group }})
num_method <- group_name %>% length()
max_bases <- dt %>%
get_best(group = {{ group }}) %>%
dplyr::pull(basis)
max_id <- max_bases %>% vapply(function(x) abs(x) %>% which.max(), numeric(1))
extract <- function(matrix, pos) matrix[(pos - 1) %% nrow(matrix) + 1, ((pos - 1) %/% nrow(matrix)) + 1]
max_sign <- mapply(extract, max_bases, max_id) %>% sign()
group_to_flip <- group_name[max_sign < 0]
group_to_flip <- group_to_flip[group_to_flip != "theoretical"]
if (length(group_to_flip) == 0) {
message("there's no flip of the sign")
basis <- dt %>% get_basis_matrix()
dt_obj <- dt
} else {
message(paste("signs in all the bases will be flipped in group", group_to_flip, "\n"))
basis <- dt %>%
dplyr::mutate(basis = ifelse({{ group }} %in% group_to_flip & {{ group }} != "theoretical",
purrr::map(basis, ~ -.x), basis
)) %>%
get_basis_matrix()
dt_obj <- dt
}
} else {
basis <- dt %>% get_basis_matrix()
dt_obj <- dt
}
return(list(
basis = basis,
flip = !rlang::quo_is_null(dplyr::enquo(group)),
dt = dt_obj
))
}
compute_pca <- function(dt, group = NULL, random = TRUE, flip = TRUE, ...) {
if (!"basis" %in% colnames(dt)) {
stop("You need to have a basis column that contains the projection basis!")
}
num_col <- ncol(dt$basis[[1]])
num_row <- nrow(dt$basis[[1]])
group <- dplyr::enexpr(group)
dt <- dt %>% dplyr::mutate(row_num = dplyr::row_number())
if (flip) {
flip <- flip_sign(dt, group = {{ group }})
basis <- flip$basis
} else {
flip <- list(
basis = dt %>% get_basis_matrix(),
flip = FALSE
)
basis <- flip$basis
}
if (num_col == 1) {
pca <- basis %>%
bind_random_matrix() %>%
stats::prcomp(scale. = TRUE)
v <- suppressMessages(pca$x %>% tibble::as_tibble(.name_repair = "minimal"))
if (flip$flip) dt_flip <- flip$dt else dt_flip <- dt
aug <- dt_flip %>%
bind_random() %>%
dplyr::bind_cols(v)
aug <- aug %>% clean_method()
} else if (num_col == 2) {
message("Ferrn will perform PCA separately on each dimension")
basis_2d <- basis %>% bind_random_matrix()
pca1 <- stats::prcomp(basis_2d[, 1:num_row], scale. = TRUE)
pca2 <- stats::prcomp(basis_2d[, (num_row + 1):(2 * num_row)], scale. = TRUE)
pca <- list(pca1, pca2)
v1 <- suppressMessages(-pca1$x %>% tibble::as_tibble(.name_repair = "minimal"))
v2 <- suppressMessages(-pca2$x %>% tibble::as_tibble(.name_repair = "minimal"))
colnames(v2)[1:num_row] <- c(paste0("PC", seq(num_row + 1, 2 * num_row)))
if (flip$flip) dt_flip <- flip$dt else dt_flip <- dt
aug <- dt_flip %>%
bind_random() %>%
dplyr::bind_cols(v1) %>%
dplyr::bind_cols(v2)
aug <- aug %>% clean_method()
} else {
stop("ferrn can only handle 1d or 2d bases!")
}
return(list(pca_summary = pca, aug = aug))
}
explore_space_tour <- function(...) {
prep <- prep_space_tour(...)
tourr::animate_xy(prep$basis,
col = prep$col, cex = prep$cex, pch = prep$pch,
edges = prep$edges, edges.col = prep$edges_col,
axes = "bottomleft"
)
}
prep_space_tour <- function(dt, group = NULL, flip = FALSE,
color = NULL, rand_size = 1, point_size = 1.5, end_size = 5,
theo_size = 3, theo_shape = 17, theo_color = "black",
palette = botanical_palettes$fern, ...) {
if (rlang::quo_is_null(dplyr::enquo(color))) {
message("map method to color")
color <- dplyr::sym("method")
}
dt <- dt %>%
dplyr::mutate(row_num = dplyr::row_number()) %>%
clean_method()
if (flip){
flip <- dt %>% flip_sign(group = {{ group }})
basis <- flip$basis %>% bind_random_matrix(front = TRUE)
} else{
flip = list(dt = dt)
basis <- dt %>% get_basis_matrix() %>% bind_random_matrix(front = TRUE)
}
n_rand <- nrow(basis) - nrow(dt)
n_end <- get_best(flip$dt, group = {{ group }}) %>% dplyr::pull(.data$row_num) + n_rand
edges_dt <- flip$dt %>%
dplyr::mutate(id = dplyr::row_number()) %>%
dplyr::filter(.data$info == "interpolation") %>%
dplyr::group_by(.data$method) %>%
dplyr::mutate(id2 = dplyr::lead(.data$id, defualt = NA)) %>%
dplyr::ungroup() %>%
dplyr::filter(!is.na(.data$id2))
edges <- edges_dt %>%
dplyr::select(.data$id, .data$id2) %>%
dplyr::mutate(id = .data$id + n_rand, id2 = .data$id2 + n_rand) %>%
as.matrix()
edges_col <- palette[as.factor(edges_dt %>% dplyr::pull({{ color }}))]
col <- c(
rep("
palette[as.factor(dt %>% dplyr::pull({{ color }}))]
)
cex <- c(
rep(rand_size, n_rand),
rep(point_size, nrow(dt))
)
cex[n_end] <- end_size
pch <- rep(20, nrow(basis))
if ("theoretical" %in% dt$info) {
theo_row_num <- dt %>%
dplyr::filter(.data$info == "theoretical") %>%
dplyr::pull(.data$row_num)
col[theo_row_num + n_rand] <- theo_color
cex[theo_row_num + n_rand] <- theo_size
pch[theo_row_num + n_rand] <- theo_shape
}
return(list(
basis = basis,
col = col,
cex = cex,
pch = pch,
edges = edges,
edges_col = edges_col
))
} |
add_header_above <- function(kable_input, header = NULL,
bold = FALSE, italic = FALSE, monospace = FALSE,
underline = FALSE, strikeout = FALSE,
align = "c", color = NULL, background = NULL,
font_size = NULL, angle = NULL,
escape = TRUE, line = TRUE, line_sep = 3,
extra_css = NULL, include_empty = FALSE,
border_left = FALSE, border_right = FALSE) {
if (is.null(header)) return(kable_input)
kable_format <- attr(kable_input, "format")
if (!kable_format %in% c("html", "latex")) {
warning("Please specify format in kable. kableExtra can customize either ",
"HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
"for details.")
return(kable_input)
}
if ((length(align) != 1L) & (length(align) != length(header))) {
warning("Length of align vector supplied to add_header_above must either be 1 ",
"or the same length as the header supplied. The length of the align ",
sprintf("vector supplied is %i and the header length is %i.",
length(align), length(header)),
"Using default of centering each element of row.")
align <- 'c'
}
if (is.null(header)) return(kable_input)
if (is.data.frame(header)){
if(ncol(header) == 2 & is.character(header[[1]]) & is.numeric(header[[2]])){
header <- data.frame(header = header[[1]], colspan = header[[2]],
stringsAsFactors = FALSE)
}
else {
stop("If header input is provided as a data frame instead of a named",
"vector it must consist of only two columns: ",
"The first should be a character vector with ",
"header names and the second should be a numeric vector with ",
"the number of columns the header should span.")
}
}
else {
header <- standardize_header_input(header)
}
if (kable_format == "html") {
return(htmlTable_add_header_above(
kable_input, header, bold, italic, monospace, underline, strikeout,
align, color, background, font_size, angle, escape, line, line_sep,
extra_css, include_empty
))
}
if (kable_format == "latex") {
return(pdfTable_add_header_above(
kable_input, header, bold, italic, monospace, underline, strikeout,
align, color, background, font_size, angle, escape, line, line_sep,
border_left, border_right))
}
}
htmlTable_add_header_above <- function(kable_input, header, bold, italic,
monospace, underline, strikeout,
align, color, background, font_size,
angle, escape, line, line_sep,
extra_css, include_empty) {
kable_attrs <- attributes(kable_input)
kable_xml <- read_kable_as_xml(kable_input)
kable_xml_thead <- xml_tpart(kable_xml, "thead")
if (escape) {
header$header <- escape_html(header$header)
}
if (is.null(kable_xml_thead)) {
xml_add_child(kable_xml, 'thead', .where = 0)
kable_xml_thead <- xml_tpart(kable_xml, 'thead')
kable_xml_tbody <- xml_tpart(kable_xml, 'tbody')
body_rows <- xml_children(kable_xml_tbody)
kable_ncol <- max(xml_length(body_rows))
} else {
header_rows <- xml_children(kable_xml_thead)
bottom_header_row <- header_rows[[length(header_rows)]]
kable_ncol <- length(xml_children(bottom_header_row))
}
if (sum(header$colspan) != kable_ncol) {
stop("The new header row you provided has a total of ", sum(header$colspan),
" columns but the original kable_input has ", kable_ncol, ".")
}
new_header_row <- htmlTable_new_header_generator(
header, bold, italic, monospace, underline, strikeout, align,
color, background, font_size, angle, line, line_sep, extra_css,
include_empty, attr(kable_input, 'lightable_class')
)
xml_add_child(kable_xml_thead, new_header_row, .where = 0)
out <- as_kable_xml(kable_xml)
if (is.null(kable_attrs$header_above)) {
kable_attrs$header_above <- 1
} else {
kable_attrs$header_above <- kable_attrs$header_above + 1
}
attributes(out) <- kable_attrs
if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
return(out)
}
standardize_header_input <- function(header) {
header_names <- names(header)
if (is.null(header_names)) {
return(data.frame(header = header, colspan = 1, row.names = NULL))
}
names(header)[header_names == ""] <- header[header_names == ""]
header[header_names == ""] <- 1
header_names <- names(header)
header <- as.numeric(header)
names(header) <- header_names
return(data.frame(header = names(header), colspan = header, row.names = NULL, stringsAsFactors = F))
}
htmlTable_new_header_generator <- function(header_df, bold, italic, monospace,
underline, strikeout, align,
color, background, font_size,
angle, line, line_sep, extra_css,
include_empty, lightable_class) {
align <- vapply(align, switch_align, 'x', USE.NAMES = FALSE)
row_style <- paste0(
"text-align: %s; ",
ifelse(bold, "font-weight: bold; ", ""),
ifelse(italic, "font-style: italic; ", ""),
ifelse(monospace, "font-family: monospace; ", ""),
ifelse(underline, "text-decoration: underline; ", ""),
ifelse(strikeout, "text-decoration: line-through; ", "")
)
if (!is.null(color)) {
row_style <- paste0(row_style, "color: ", html_color(color), " !important;")
}
if (!is.null(background)) {
row_style <- paste0(
row_style,
"padding-right: 4px; padding-left: 4px; ",
"background-color: ", html_color(background), " !important;"
)
}
if (!is.null(font_size)) {
if (is.numeric(font_size)) font_size <- paste0(font_size, "px")
row_style <- paste0(row_style, "font-size: ", font_size, ";")
}
if (!is.null(extra_css)) {
row_style <- paste0(row_style, extra_css)
}
if (!is.null(angle)) {
angle <- paste0("-webkit-transform: rotate(", angle,
"deg); -moz-transform: rotate(", angle,
"deg); -ms-transform: rotate(", angle,
"deg); -o-transform: rotate(", angle,
"deg); transform: rotate(", angle,
"deg); display: inline-block; ")
header_df$header <- ifelse(
trimws(header_df$header) == "" | include_empty,
header_df$header,
paste0('<span style="', angle, '">', header_df$header, '</span>')
)
}
if (is.null(lightable_class)) {
border_hidden <- 'border-bottom:hidden;'
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 1px solid
} else {
border_hidden <- ''
if (lightable_class %in% c("lightable-classic", "lightable-classic-2")) {
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 1px solid
}
if (lightable_class %in% c("lightable-minimal")) {
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 2px solid
}
if (lightable_class %in% c("lightable-paper")) {
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 1px solid
}
if (lightable_class %in% c("lightable-material")) {
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 1px solid
}
if (lightable_class %in% c("lightable-material-dark")) {
line <- ifelse(ez_rep(line, nrow(header_df)),
"border-bottom: 1px solid
}
}
line_sep <- ez_rep(line_sep, nrow(header_df))
line_sep <- glue::glue('padding-left:{line_sep}px;padding-right:{line_sep}px;')
row_style <- sprintf(row_style, align)
header_items <- ifelse(
trimws(header_df$header) == "" | include_empty,
paste0('<th style="empty-cells: hide;', border_hidden, '" colspan="', header_df$colspan,
'"></th>'),
paste0(
'<th style="', border_hidden, 'padding-bottom:0; ',
line_sep, row_style, '" colspan="',
header_df$colspan, '"><div style="', line, '">', header_df$header,
'</div></th>')
)
header_text <- paste(c("<tr>", header_items, "</tr>"), collapse = "")
header_xml <- read_xml(header_text, options = c("COMPACT"))
return(header_xml)
}
pdfTable_add_header_above <- function(kable_input, header, bold, italic,
monospace, underline, strikeout, align,
color, background, font_size, angle,
escape, line, line_sep,
border_left, border_right) {
table_info <- magic_mirror(kable_input)
if (is.data.frame(header)){
if(ncol(header) == 2 & is.character(header[[1]]) & is.numeric(header[[2]])){
header <- data.frame(header = header[[1]], colspan = header[[2]],
stringsAsFactors = FALSE)
}
else {
stop("If header input is provided as a data frame instead of a named vector ",
"it must consist of only two columns: ",
"The first should be a character vector with ",
"header names and the second should be a numeric vector with ",
"the number of columns the header should span.")
}
}
else {
header <- standardize_header_input(header)
}
if (escape) {
header$header <- input_escape(header$header, align)
}
align <- vapply(align, match.arg, 'a', choices = c("l", "c", "r"))
hline_type <- switch(table_info$booktabs + 1, "\\\\hline", "\\\\toprule")
new_header_split <- pdfTable_new_header_generator(
header, table_info$booktabs, bold, italic, monospace, underline, strikeout,
align, color, background, font_size, angle, line_sep,
border_left, border_right)
if (line) {
new_header <- paste0(new_header_split[1], "\n", new_header_split[2])
} else {
new_header <- new_header_split[1]
}
out <- str_replace(solve_enc(kable_input),
hline_type,
paste0(hline_type, "\n", new_header))
out <- structure(out, format = "latex", class = "knitr_kable")
if (is.null(table_info$new_header_row)) {
table_info$new_header_row <- new_header_split[1]
table_info$header_df <- list(header)
} else {
table_info$new_header_row <- c(table_info$new_header_row, new_header_split[1])
table_info$header_df[[length(table_info$header_df) + 1]] <- header
}
attr(out, "kable_meta") <- table_info
return(out)
}
ez_rep <- function(x, n) {
if (is.null(x)) return(NULL)
if (length(x) == 1) return(rep(x, n))
return(x)
}
pdfTable_new_header_generator <- function(header_df, booktabs = FALSE,
bold, italic, monospace,
underline, strikeout, align,
color, background, font_size, angle,
line_sep, border_left, border_right) {
n <- nrow(header_df)
bold <- ez_rep(bold, n)
italic <- ez_rep(italic, n)
monospace <- ez_rep(monospace, n)
underline <- ez_rep(underline, n)
strikeout <- ez_rep(strikeout, n)
align <- ez_rep(align, n)
color <- ez_rep(color, n)
background <- ez_rep(background, n)
font_size <- ez_rep(font_size, n)
angle <- ez_rep(angle, n)
if (!booktabs & n != 1) {
align[1:(n - 1)] <- paste0(align[1:(n - 1)], "|")
}
if (border_left) {
align[1] <- paste0("|", align[1])
}
if (border_right) {
align[n] <- paste0(align[n], "|")
}
header <- header_df$header
colspan <- header_df$colspan
header <- ifelse(bold, paste0('\\\\textbf\\{', header, '\\}'), header)
header <- ifelse(italic, paste0('\\\\em\\{', header, '\\}'), header)
header <- ifelse(monospace, paste0('\\\\ttfamily\\{', header, '\\}'), header)
header <- ifelse(underline, paste0('\\\\underline\\{', header, '\\}'), header)
header <- ifelse(strikeout, paste0('\\\\sout\\{', header, '\\}'), header)
if (!is.null(color)) {
color <- latex_color(color)
header <- paste0("\\\\textcolor", color, "\\{", header, "\\}")
}
if (!is.null(background)) {
background <- latex_color(background)
header <- paste0("\\\\cellcolor", background, "\\{", header, "\\}")
}
if (!is.null(font_size)) {
header <- paste0("\\\\bgroup\\\\fontsize\\{", font_size, "\\}\\{",
as.numeric(font_size) + 2,
"\\}\\\\selectfont ", header, "\\\\egroup\\{\\}")
}
if (!is.null(angle)) {
header <- paste0("\\\\rotatebox\\{", angle, "\\}\\{", header, "\\}")
}
header_items <- paste0(
'\\\\multicolumn\\{', colspan, '\\}\\{', align, '\\}\\{', header, '\\}'
)
header_text <- paste(paste(header_items, collapse = " & "), "\\\\\\\\")
cline <- cline_gen(header_df, booktabs, line_sep)
return(c(header_text, cline))
}
cline_gen <- function(header_df, booktabs, line_sep) {
cline_end <- cumsum(header_df$colspan)
cline_start <- c(0, cline_end) + 1
cline_start <- cline_start[-length(cline_start)]
cline_type <- switch(
booktabs + 1,
"\\\\cline{",
glue::glue("\\\\cmidrule(l{[line_sep]pt}r{[line_sep]pt}){",
.open = "[", .close = "]"))
cline <- paste0(cline_type, cline_start, "-", cline_end, "}")
cline <- cline[trimws(header_df$header) != ""]
cline <- paste(cline, collapse = " ")
return(cline)
}
switch_align <- function(x) {
if (x %in% c('l', 'c', 'r')) {
return(switch(x, l = 'left', c = 'center', r = 'right'))
}
return(x)
} |
get_fields <- function(endpoint, groups = NULL) {
validate_endpoint(endpoint)
if (is.null(groups)) {
fieldsdf[fieldsdf$endpoint == endpoint, "field"]
} else {
validate_groups(groups = groups)
fieldsdf[fieldsdf$endpoint == endpoint & fieldsdf$group %in% groups, "field"]
}
}
get_endpoints <- function() {
c(
"assignees", "cpc_subsections", "inventors", "locations",
"nber_subcategories", "patents", "uspc_mainclasses"
)
} |
output$processSankey <- renderEcharts4r({
processDataSpecific() %>%
e_charts() %>%
e_sankey(source, target, value, focusNodeAdjacency = T) %>%
e_theme("essos") %>%
e_color(background = "
e_grid(left = "1%") %>%
e_tooltip()
})
processDataSpecific <- reactive({
processData[date == input$selectProcessDay]
}) |
braun <- function(U, simpletest, m) {
n <- length(U)
if(n < 2 * m) stop("Unsufficient data for Braun's method")
group <- factor(sample(seq_len(n) %% m))
zz <- by(data=U, INDICES=group, FUN=simpletest, simplify=FALSE)
statistics <- sapply(zz, getElement, "statistic")
pvalues <- sapply(zz, getElement, "pvalue")
statname <- zz[[1]]$statname
statistic <- max(statistics)
pvalue <- 1 - (1 - min(pvalues))^m
statname <- paste0(statname, "max")
return(list(statistic=statistic, pvalue=pvalue, statname=statname))
} |
AQSysPlot <- function (dataSET,
Order = "xy",
xlbl = "",
ylbl = "",
seriesNames = NULL,
save = FALSE,
filename = NULL,
HR = FALSE,
wdir = NULL,
silent = FALSE) {
nSys <- (ncol(dataSET) / 2)
SysNames <- FALSE
if ((ncol(dataSET) %% 2) == 0) {
if (is.null(seriesNames) || !(length(seriesNames) == nSys)) {
print(paste("The array seriesNames must have", nSys,
"elements. Default names will be used instead."))
seriesNames <- sapply(seq(1, nSys), function(x) paste("Series", x))
} else {
SysNames <- TRUE
}
SysList <- list()
for (i in seq(1, nSys)) {
SysList[[i]] <- unname(na.exclude(dataSET[, (i * 2 - 1):(i * 2)]))
names(SysList[[i]]) <- c("X", "Y")
SysList[[i]]["System"] <- seriesNames[i]
}
output <- bind_rows(SysList)
output_plot <- bndOrthPlot(output, Order, xlbl, ylbl)
saveConfig(output_plot, save, HR, filename, wdir, silent)
if (silent == FALSE) {
print(output_plot)
invisible(list("data" = SysList, "plot" = output_plot))
} else {
invisible(list("data" = SysList, "plot" = output_plot))
}
}
else{
AQSys.err(9)
}
}
bndOrthPlot <- function(dataSET, Order, xlbl = "", ylbl = "") {
xmax <- ceiling(round(max(dataSET[, 1]) / 0.92, 1) / 5) * 5
ymax <- ceiling(round(max(dataSET[, 2]) / 0.92, 1) / 5) * 5
outputPLOT <- ggplot() + scale_colour_grey() +
geom_line(data = dataSET, size = 1,
aes_string(color = "System", x = "X", y = "Y")) +
geom_point(data = dataSET, size = 2,
aes_string(color = "System", x = "X", y = "Y")) +
xlab(paste(xlbl, "(%, m/m)")) +
ylab(paste(ylbl, "(%, m/m)")) +
theme_light() +
theme(
validate = FALSE,
plot.margin = unit(c(1, 1, 1, 1), "cm"),
text = element_text(size = 16),
legend.position = "top",
axis.title.y = element_text(vjust = 5),
axis.title.x = element_text(vjust = -2),
panel.grid.major = element_line(size = .70, colour = "black"),
panel.grid.minor = element_line(size = .70),
panel.border = element_rect(size = .5, colour = "white"),
axis.text.x = element_text(size = 15),
axis.text.y = element_text(size = 15),
axis.line = element_line(colour = 'black', size = 1.25),
legend.title = element_blank(),
legend.text = element_text(
colour = "black",
size = 12,
face = "plain"
)
) +
scale_y_continuous(
expand = c(0, 0),
limits = c(0, ymax),
breaks = seq(0, ymax, by = 5),
labels = seq(0, ymax, by = 5)
) +
scale_x_continuous(
expand = c(0, 0),
limits = c(0, xmax),
breaks = seq(0, xmax, by = xmax / 10),
labels = seq(0, xmax, by = xmax / 10)
)
return(outputPLOT)
} |
lgRR.vcov <- function(r, nt, nc, st, sc, n_rt = NA, n_rc = NA)
{
ft <- nt - st
fc <- nc - sc
if (length(as.vector(ft)) == length(as.matrix(ft)[, 1])) {
colum.number <- 1} else {colum.number <- ncol(ft)}
if (length(as.vector(ft)) == length(as.matrix(ft)[, 1])) {
K <- length(ft)} else { K <- nrow(ft)}
col.vac.number <- (colum.number + 1)*colum.number/2
if (is.na(n_rt)&(length(n_rt) == 1)){
n_rt <- rep(list(matrix(NA, colum.number, colum.number)), K) }
for (k in 1:K) {
for (i in 1:colum.number){
for (j in 1:colum.number){
if (is.na(n_rt[[k]][i, j]))
n_rt[[k]][i, j] <- min(nt[k, i], nt[k, j])
}
}
}
if (is.na(n_rc)&(length(n_rc) == 1)){
n_rc <- rep(list(matrix(NA, colum.number, colum.number)), K) }
for (k in 1:K) {
for (i in 1:colum.number){
for (j in 1:colum.number){
if (is.na(n_rc[[k]][i, j]))
n_rc[[k]][i, j] <- min(nc[k, i], nc[k, j])
}
}
}
list.corr.st.varcovar <- list()
for (k in 1:K){
list.corr.st.varcovar[[k]] <- matrix(NA, colum.number, colum.number)
for (i in 1:colum.number){
for (j in 1:colum.number)
{ tmp <- r[[k]][i, j]*n_rc[[k]][i, j]*sqrt(fc[k, i]*fc[k, j]/sc[k, i]/sc[k, j])/sqrt(nc[k, i]*nc[k, j]) +
r[[k]][i, j]*n_rt[[k]][i, j]*sqrt(ft[k, i]*ft[k, j]/st[k, i]/st[k, j])/sqrt(nt[k, i]*nt[k, j])
list.corr.st.varcovar[[k]][i, j]<- unlist(tmp) }
}
}
lgRR <- matrix(NA, K, colum.number)
for (k in 1:K) {
for (i in 1:colum.number){
lgRR[k, i] <- unlist(log((st[k, i]/nt[k, i])/(sc[k, i]/nc[k, i])))
}}
corr.st.varcovar <- matrix(unlist(lapply(1:K, function(k){
smTovec(list.corr.st.varcovar[[k]])})), K, col.vac.number, byrow = TRUE)
list(list.vcov = list.corr.st.varcovar,
matrix.vcov = corr.st.varcovar,
ef = as.data.frame(lgRR))
} |
cProb <- function(data, censored, gamma1, q, plot = FALSE, add = FALSE,
main = "Estimates of small exceedance probability", ...) {
.checkInput(data, gamma1)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
n <- length(X)
prob <- numeric(n)
K <- 1:(n-1)
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
prob[K] <- km * (q/X[n-K])^(-1/gamma1[K])
prob[prob < 0 | prob > 1] <- NA
.plotfun(K, prob[K], type="l", xlab="k", ylab="1-F(x)", main=main, plot=plot, add=add, ...)
.output(list(k=K, P=prob[K], q=q), plot=plot, add=add)
}
cReturn <- function(data, censored, gamma1, q, plot = FALSE, add = FALSE,
main = "Estimates of large return period", ...) {
.checkInput(data, gamma1)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
n <- length(X)
R <- numeric(n)
K <- 1:(n-1)
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
R[K] <- 1 / ( km * (q/X[n-K])^(-1/gamma1[K]) )
R[R < 1] <- NA
.plotfun(K, R[K], type="l", xlab="k", ylab="1/(1-F(x))", main=main, plot=plot, add=add, ...)
.output(list(k=K, R=R[K], q=q), plot=plot, add=add)
}
cQuant <- function(data, censored, gamma1, p, plot = FALSE, add = FALSE,
main = "Estimates of extreme quantile", ...) {
.checkInput(data, gamma1)
censored <- .checkCensored(censored, length(data))
.checkProb(p)
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
n <- length(X)
quant <- numeric(n)
K <- 1:(n-1)
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
quant[K] <- X[n-K] * (km/p)^(gamma1[K])
.plotfun(K, quant[K], type="l", xlab="k", ylab="Q(1-p)", main=main, plot=plot, add=add, ...)
.output(list(k=K, Q=quant[K], p=p), plot=plot, add=add)
}
cQuantGH <- function(data, censored, gamma1, p, plot = FALSE, add = FALSE,
main = "Estimates of extreme quantile", ...) {
.checkInput(data, gamma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
.checkProb(p)
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
quant <- numeric(n)
K <- 1:length(gamma1)
pk <- cumsum(delta[n-K+1])/K
H <- Hill(X)$gamma
S <- Moment(X)$gamma - Hill(X)$gamma
a <- X[n-K] * H[K] * (1-S[K]) / pk[K]
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
quant[K] <- X[n-K] + a/gamma1[K] * ( (km/p)^gamma1[K] - 1 )
.plotfun(K, quant[K], type="l", xlab="k", ylab="Q(1-p)", main=main, plot=plot, add=add, ...)
.output(list(k=K, Q=quant[K], p=p), plot=plot, add=add)
}
cProbGH <- function(data, censored, gamma1, q, plot = FALSE, add = FALSE,
main = "Estimates of small exceedance probability", ...) {
.checkInput(data, gamma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
prob <- numeric(n)
K <- 1:length(gamma1)
pk <- cumsum(delta[n-K+1])/K
H <- Hill(X)$gamma
a <- X[n-K] * H[K] * (1-pmin(gamma1[K], 0)) / pk[K]
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
prob[K] <- km * (1 + gamma1[K]/a[K]*(q-X[n-K]))^(-1/gamma1[K])
prob[prob < 0 | prob > 1] <- NA
.plotfun(K, prob[K], type="l", xlab="k", ylab="1-F(x)", main=main, plot=plot, add=add, ...)
.output(list(k=K, P=prob[K], q=q), plot=plot, add=add)
}
cReturnGH <- function(data, censored, gamma1, q, plot = FALSE, add = FALSE,
main = "Estimates of large return period", ...) {
.checkInput(data, gamma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
R <- numeric(n)
K <- 1:length(gamma1)
pk <- cumsum(delta[n-K+1])/K
H <- Hill(X)$gamma
a <- X[n-K] * H[K] * (1-pmin(gamma1[K], 0)) / pk[K]
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
R[K] <- 1 / ( km * (1 + gamma1[K]/a[K]*(q-X[n-K]))^(-1/gamma1[K]) )
R[R < 1] <- NA
.plotfun(K, R[K], type="l", xlab="k", ylab="1/(1-F(x))", main=main, plot=plot, add=add, ...)
.output(list(k=K, R=R[K], q=q), plot=plot, add=add)
}
cQuantMOM <- cQuantGH
cProbMOM <- cProbGH
cReturnMOM <- cReturnGH
cQuantGPD <- function(data, censored, gamma1, sigma1, p, plot = FALSE, add = FALSE,
main = "Estimates of extreme quantile", ...) {
.checkInput(data, gamma1, scale=sigma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
.checkProb(p)
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
quant <- numeric(n)
K <- 1:(n-1)
pk <- cumsum(delta[n-K+1])/K
a <- sigma1[K]/pk
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
quant[K] <- X[n-K] + a/gamma1[K] * ( (km/p)^gamma1[K] - 1 )
.plotfun(K, quant[K], type="l", xlab="k", ylab="Q(1-p)", main=main, plot=plot, add=add, ...)
.output(list(k=K, Q=quant[K], p=p), plot=plot, add=add)
}
cProbGPD <- function(data, censored, gamma1, sigma1, q, plot = FALSE, add = FALSE,
main = "Estimates of small exceedance probability", ...) {
.checkInput(data, gamma1, scale=sigma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
prob <- numeric(n)
K <- 1:(n-1)
pk <- cumsum(delta[n-K+1])/K
a <- sigma1[K]/pk
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
prob[K] <- km * (1 + gamma1[K]/a[K]*(q-X[n-K]))^(-1/gamma1[K])
prob[prob < 0 | prob > 1] <- NA
.plotfun(K, prob[K], type="l", xlab="k", ylab="1-F(x)", main=main, plot=plot, add=add, ...)
.output(list(k=K, P=prob[K], q=q), plot=plot, add=add)
}
cReturnGPD <- function(data, censored, gamma1, sigma1, q, plot = FALSE, add = FALSE,
main = "Estimates of large return period", ...) {
.checkInput(data, gamma1, scale=sigma1, gammapos=FALSE)
censored <- .checkCensored(censored, length(data))
if (length(q) > 1) {
stop("q should be a numeric of length 1.")
}
s <- sort(data, index.return = TRUE)
X <- s$x
sortix <- s$ix
delta <- !(censored[sortix]*1)
n <- length(X)
R <- numeric(n)
K <- 1:(n-1)
pk <- cumsum(delta[n-K+1])/K
a <- sigma1[K]/pk
km <- KaplanMeier(X[n-K], data = X, censored = censored[sortix])$surv
R[K] <- 1 / ( km * (1 + gamma1[K]/a[K]*(q-X[n-K]))^(-1/gamma1[K]) )
R[R < 1] <- NA
.plotfun(K, R[K], type="l", xlab="k", ylab="1/(1-F(x))", main=main, plot=plot, add=add, ...)
.output(list(k=K, R=R[K], q=q), plot=plot, add=add)
} |
isoweek <- function(x, type="both_num", sep="-", inv=FALSE, colnames=c("isoyear","isoweek")) {
alts=c("week","year","both_text","both_num","matrix")
if(!(type %in% alts)) stop("Unknown isoweek type requested!")
x.date<-as.Date(x)
x.weekday<-as.integer(format(x.date,"%w"))
x.weekday[x.weekday==0]=7
x.nearest.thu<-x.date-x.weekday+4
x.isoyear<-as.integer(substring(x.nearest.thu,1,4))
x.isoweek<-(as.integer(x.nearest.thu-as.Date(paste(x.isoyear,"-1-1",sep="")))%/%7)+1
switch(type,
week = x.isoweek,
year = x.isoyear,
both_text = if (inv) {
ifelse((is.na(x.isoyear) | is.na(x.isoweek)),NA,paste(x.isoweek,x.isoyear,sep=sep))
} else {
ifelse((is.na(x.isoyear) | is.na(x.isoweek)),NA,paste(x.isoyear,x.isoweek,sep=sep))
},
both_num = ifelse((is.na(x.isoyear) | is.na(x.isoweek)),NA,x.isoyear*100+x.isoweek),
matrix = if (inv) {
`colnames<-`(cbind(x.isoweek, x.isoyear), rev(colnames))
} else {
`colnames<-`(cbind(x.isoyear, x.isoweek), colnames)
}
)
} |
umxACEv <- function(name = "ACEv", selDVs, selCovs = NULL, sep = NULL, dzData, mzData, dzAr = .5, dzCr = 1, type = c("Auto", "FIML", "cov", "cor", "WLS", "DWLS", "ULS"), allContinuousMethod = c("cumulants", "marginals"), data = NULL, zyg = "zygosity", weightVar = NULL, numObsDZ = NULL, numObsMZ = NULL, addStd = TRUE, addCI = TRUE, boundDiag = NULL, equateMeans = TRUE, bVector = FALSE, autoRun = getOption("umx_auto_run"), tryHard = c("no", "yes", "ordinal", "search"), optimizer = NULL, nSib = 2) {
type = match.arg(type)
allContinuousMethod = match.arg(allContinuousMethod)
if(dzCr == .25 & name == "ACEv"){ name = "ADEv" }
if(nSib != 2){umx_msg(paste0("I can only handle 2 sibs, you gave me ", nSib)) }
if(!is.null(data)){
if(is.null(sep)){ sep = "_T" }
if("tbl" %in% class(data)){
data = as.data.frame(data)
}
if(is.null(dzData)){ dzData = "DZ"; mzData = "MZ" }
mzData = data[data[,zyg] %in% mzData, ]
dzData = data[data[,zyg] %in% dzData, ]
}else{
if("tbl" %in% class(mzData)){
mzData = as.data.frame(mzData)
dzData = as.data.frame(dzData)
}
}
xmu_twin_check(selDVs= selDVs, sep = sep, dzData = dzData, mzData = mzData, enforceSep = TRUE, nSib = nSib, optimizer = optimizer)
selVars = tvars(selDVs, sep = sep, suffixes= 1:nSib)
nVar = length(selVars)/nSib;
model = xmu_make_TwinSuperModel(name=name, mzData = mzData, dzData = dzData, selDVs = selDVs, selCovs= selCovs, sep = sep, type = type, allContinuousMethod = allContinuousMethod, numObsMZ = numObsMZ, numObsDZ = numObsDZ, nSib= nSib, equateMeans = equateMeans, weightVar = weightVar)
tmp = xmu_starts(mzData, dzData, selVars = selDVs, sep = sep, nSib = nSib, varForm = "Cholesky", equateMeans= equateMeans, SD= TRUE, divideBy = 3)
if(nSib==2){
expCovMZ = mxAlgebra(rbind (cbind(ACE, AC), cbind( AC, ACE)), dimnames = list(selVars, selVars), name = "expCovMZ")
expCovDZ = mxAlgebra(rbind (cbind(ACE, hAC), cbind(hAC, ACE)), dimnames = list(selVars, selVars), name = "expCovDZ")
} else if (nSib==3) {
expCovMZ = mxAlgebra(name="expCovMZ", dimnames = list(selVars, selVars), rbind(
cbind(ACE, AC, hAC),
cbind(AC , ACE, hAC),
cbind(hAC, hAC, ACE))
)
expCovDZ = mxAlgebra(name= "expCovDZ", dimnames = list(selVars, selVars), rbind(
cbind(ACE, hAC, hAC),
cbind(hAC, ACE, hAC),
cbind(hAC, hAC, ACE))
)
}else{
stop("3 sibs is experimental, but ", nSib, "? ... Maybe come back in 2022, best tim :-)")
}
top = mxModel(model$top,
umxMatrix("A", type = "Symm", nrow = nVar, ncol = nVar, free = TRUE, values = tmp$varStarts, byrow = TRUE),
umxMatrix("C", type = "Symm", nrow = nVar, ncol = nVar, free = TRUE, values = tmp$varStarts, byrow = TRUE),
umxMatrix("E", type = "Symm", nrow = nVar, ncol = nVar, free = TRUE, values = tmp$varStarts, byrow = TRUE),
umxMatrix("dzAr", "Full", 1, 1, free = FALSE, values = dzAr),
umxMatrix("dzCr", "Full", 1, 1, free = FALSE, values = dzCr),
mxAlgebra(name = "ACE", A+C+E),
mxAlgebra(name = "AC" , A+C ),
mxAlgebra(name = "hAC", (dzAr %x% A) + (dzCr %x% C)),
expCovMZ, expCovDZ
)
model = mxModel(model, top)
if(!is.null(boundDiag)){
if(!is.numeric(boundDiag)){
stop("boundDiag must be a digit or vector of numbers. You gave me a ", class(boundDiag))
} else {
newLbound = model$top$matrices$A@lbound
if(length(boundDiag) > 1 ){
if(length(boundDiag) != length(diag(newLbound)) ){
stop("Typically boundDiag is 1 digit: if more, must be size of diag(A)")
}
}
diag(newLbound) = boundDiag;
model$top$A$lbound = newLbound
model$top$C$lbound = newLbound
model$top$E$lbound = newLbound
}
}
if(addStd){
newTop = mxModel(model$top,
mxMatrix(name = "I", "Iden", nVar, nVar),
mxAlgebra(name = "Vtot", A + C+ E),
mxAlgebra(name = "InvSD", sqrt(solve(I * Vtot))),
mxAlgebra(name = "A_std", InvSD %&% A),
mxAlgebra(name = "C_std", InvSD %&% C),
mxAlgebra(name = "E_std", InvSD %&% E)
)
model = mxModel(model, newTop)
if(addCI){
model = mxModel(model, mxCI(c('top.A_std', 'top.C_std', 'top.E_std')))
}
}
model = omxAssignFirstParameters(model)
model = as(model, "MxModelACEv")
model = xmu_safe_run_summary(model, autoRun = autoRun, tryHard = tryHard, summary = TRUE, comparison = FALSE)
return(model)
}
umxSummaryACEv <- function(model, digits = 2, file = getOption("umx_auto_plot"), comparison = NULL, std = TRUE, showRg = FALSE, CIs = TRUE, report = c("markdown", "html"), returnStd = FALSE, extended = FALSE, zero.print = ".", show = c("std", "raw"), ...) {
show = match.arg(show, c("std", "raw"))
if(show != "std"){
std = FALSE
}
report = match.arg(report)
commaSep = paste0(umx_set_separator(silent = TRUE), " ")
if(typeof(model) == "list"){
for(thisFit in model) {
message("Output for Model: ", thisFit$name)
umxSummaryACE(thisFit, digits = digits, file = file, showRg = showRg, std = std, comparison = comparison, CIs = CIs, returnStd = returnStd, extended = extended, zero.print = zero.print, report = report)
}
} else {
umx_has_been_run(model, stop = TRUE)
xmu_show_fit_or_comparison(model, comparison = comparison, digits = digits)
selDVs = dimnames(model$top.expCovMZ)[[1]]
nVar = length(selDVs)/2;
A = mxEval(top.A, model)
C = mxEval(top.C, model)
E = mxEval(top.E, model)
if(std){
caption = paste0("Standardized parameter estimates from a ", dim(A)[2], "-factor Direct variance ACE model. ")
Vtot = A + C + E;
I = diag(nVar);
InvSD = sqrt(solve(I * Vtot));
A_std = InvSD %&% A
C_std = InvSD %&% C
E_std = InvSD %&% E
AClean = A_std
CClean = C_std
EClean = E_std
} else {
caption = paste0("Raw parameter estimates from a ", dim(A)[2], "-factor direct-variance ACE model. ")
AClean = A
CClean = C
EClean = E
}
AClean[upper.tri(AClean)] = NA
CClean[upper.tri(CClean)] = NA
EClean[upper.tri(EClean)] = NA
rowNames = sub("(_T)?1$", "", selDVs[1:nVar])
Estimates = data.frame(cbind(AClean, CClean, EClean), row.names = rowNames, stringsAsFactors = FALSE);
if(model$top$dzCr$values == .25){
colNames = c("A", "D", "E")
caption = paste0(caption, "A: additive genetic; D: dominance effects; E: unique environment.")
} else {
colNames = c("A", "C", "E")
caption = paste0(caption, "A: additive genetic; C: common environment; E: unique environment.")
}
names(Estimates) = paste0(rep(colNames, each = nVar), rep(1:nVar))
umx_print(Estimates, digits = digits, caption = caption, append=FALSE, sortableDF=TRUE, both=TRUE, na.print="NA", file=report, zero.print = zero.print)
xmu_twin_print_means(model, digits = digits, report = report)
if(extended == TRUE) {
AClean = A
CClean = C
EClean = E
AClean[upper.tri(AClean)] = NA
CClean[upper.tri(CClean)] = NA
EClean[upper.tri(EClean)] = NA
unStandardizedEstimates = data.frame(cbind(AClean, CClean, EClean), row.names = rowNames);
names(unStandardizedEstimates) = paste0(rep(colNames, each = nVar), rep(1:nVar));
umx_print(unStandardizedEstimates, caption = "Unstandardised path coefficients", digits = digits, zero.print = zero.print)
}
if(showRg) {
NAmatrix <- matrix(NA, nVar, nVar);
rA = tryCatch(solve(sqrt(I*A)) %*% A %*% solve(sqrt(I*A)), error = function(err) return(NAmatrix));
rC = tryCatch(solve(sqrt(I*C)) %*% C %*% solve(sqrt(I*C)), error = function(err) return(NAmatrix));
rE = tryCatch(solve(sqrt(I*E)) %*% E %*% solve(sqrt(I*E)), error = function(err) return(NAmatrix));
rAClean = rA
rCClean = rC
rEClean = rE
rAClean[upper.tri(rAClean)] = NA
rCClean[upper.tri(rCClean)] = NA
rEClean[upper.tri(rEClean)] = NA
genetic_correlations = data.frame(cbind(rAClean, rCClean, rEClean), row.names = rowNames);
names(genetic_correlations) = rowNames
names(genetic_correlations) = paste0(rep(c("rA", "rC", "rE"), each = nVar), rep(1:nVar));
umx_print(genetic_correlations, caption = "Genetic correlations", digits = digits, zero.print = zero.print)
}
hasCIs = umx_has_CIs(model)
if(hasCIs & CIs) {
message("Creating CI-based report!")
CIlist = data.frame(model$output$confidenceIntervals)
CIlist = CIlist[(CIlist$lbound != 0 & CIlist$ubound != 0), ]
CIlist = CIlist[!grepl("^NA", row.names(CIlist)), ]
CIlist <- CIlist[, c("lbound", "estimate", "ubound")]
CIlist$fullName = row.names(CIlist)
rows = dim(model$top$matrices$A$labels)[1]
cols = dim(model$top$matrices$A$labels)[2]
A_CI = C_CI = E_CI = matrix(NA, rows, cols)
labelList = imxGenerateLabels(model)
rowCount = dim(CIlist)[1]
for(n in 1:rowCount) {
thisName = row.names(CIlist)[n]
if(!umx_has_square_brackets(thisName)) {
nameParts = labelList[which(row.names(labelList) == thisName),]
CIlist$fullName[n] = paste(nameParts$model, ".", nameParts$matrix, "[", nameParts$row, ",", nameParts$col, "]", sep = "")
}
fullName = CIlist$fullName[n]
thisMatrixName = sub(".*\\.([^\\.]*)\\[.*", replacement = "\\1", x = fullName)
thisMatrixRow = as.numeric(sub(".*\\[(.*),(.*)\\]", replacement = "\\1", x = fullName))
thisMatrixCol = as.numeric(sub(".*\\[(.*),(.*)\\]", replacement = "\\2", x = fullName))
CIparts = round(CIlist[n, c("estimate", "lbound", "ubound")], digits)
thisString = paste0(CIparts[1], " [",CIparts[2], commaSep, CIparts[3], "]")
if(grepl("^A", thisMatrixName)) {
A_CI[thisMatrixRow, thisMatrixCol] = thisString
} else if(grepl("^C", thisMatrixName)){
C_CI[thisMatrixRow, thisMatrixCol] = thisString
} else if(grepl("^E", thisMatrixName)){
E_CI[thisMatrixRow, thisMatrixCol] = thisString
} else{
stop(paste("Illegal matrix name: must begin with A, C, or E. You sent: ", thisMatrixName))
}
}
Estimates = data.frame(cbind(A_CI, C_CI, E_CI), row.names = rowNames, stringsAsFactors = FALSE)
names(Estimates) = paste0(rep(colNames, each = nVar), rep(1:nVar));
Estimates = umx_print(Estimates, digits = digits, zero.print = zero.print)
if(report == "html"){
R2HTML::HTML(Estimates, file = "tmpCI.html", Border = 0, append = F, sortableDF = T);
umx_open("tmpCI.html")
}
CI_Fit = model
CI_Fit$top$A$values = A_CI
CI_Fit$top$C$values = C_CI
CI_Fit$top$E$values = E_CI
}
}
if(!is.na(file)) {
if(hasCIs & CIs){
umxPlotACEv(CI_Fit, file = file, std = FALSE)
} else {
umxPlotACEv(model, file = file, std = std)
}
}
if(returnStd) {
if(CIs){
message("If you asked for CIs, returned model is not runnable (contains CIs not parameter values)")
}
umx_standardize(model)
}
}
umxSummary.MxModelACEv <- umxSummaryACEv
umxPlotACEv <- function(x = NA, file = "name", digits = 2, means = FALSE, std = TRUE, strip_zero = TRUE, ...) {
model = x
if(std){ model = umx_standardize(model) }
selDVs = xmu_twin_get_var_names(model)
nVar = length(selDVs)
selDVs = selDVs[1:(nVar)]
parameterKeyList = omxGetParameters(model)
out = ""
latents = c()
for(thisParam in names(parameterKeyList) ) {
value = parameterKeyList[thisParam]
if(class(value) == "numeric") {
value = round(value, digits)
}
if (grepl("^[ACE]_r[0-9]+c[0-9]+", thisParam)) {
from = sub('([ACE])_r([0-9]+)c([0-9]+)', '\\1\\3', thisParam, perl = TRUE);
target = sub('([ACE])_r([0-9]+)c([0-9]+)', '\\1\\2', thisParam, perl = TRUE);
latents = append(latents, c(from, target))
out = paste0(out, "\t", from, " -> ", target, " [dir=both, label = \"", value, "\"]", ";\n")
} else {
from = thisParam;
target = sub('r([0-9])c([0-9])', 'var\\2', thisParam, perl=TRUE)
if(means){
out = paste0(out, "\t", from, " -> ", target, " [label = \"", value, "\"]", ";\n")
}
}
}
preOut = "\t
latents = unique(latents)
for(var in latents) {
preOut = paste0(preOut, "\t", var, " [shape = circle];\n")
}
preOut = paste0(preOut, "\n\t
for(var in selDVs[1:nVar]) {
preOut = paste0(preOut, "\t", var, " [shape = square];\n")
}
selDVs[1:nVar]
l_to_v_at_1 = ""
for(l in latents) {
var = as.numeric(sub('([ACE])([0-9]+)', '\\2', l, perl = TRUE));
l_to_v_at_1 = paste0(l_to_v_at_1, "\t ", l, "-> ", selDVs[var], " [label = \"@1\"];\n")
}
rankVariables = paste("\t{rank = same; ", paste(selDVs[1:nVar], collapse = "; "), "};\n")
rankA = paste("\t{rank = min; ", paste(grep('A' , latents, value = TRUE), collapse = "; "), "};\n")
rankCE = paste("\t{rank = max; ", paste(grep('[CE]', latents, value = TRUE), collapse = "; "), "};\n")
label = model$name
splines = "FALSE"
digraph = paste0(
"digraph G {\n\t",
'label="', label, '";\n\t',
"splines = \"", splines, "\";\n",
preOut,
out,
l_to_v_at_1,
rankVariables,
rankA,
rankCE, "\n}"
)
message("\n?umxPlotACEv options: std=, means=, digits=, strip_zero=, file=, min=, max =")
xmu_dot_maker(model, file, digraph, strip_zero = strip_zero)
}
plot.MxModelACEv <- umxPlotACEv
xmu_standardize_ACEv <- function(model, ...) {
message("Standardized variance-based models may yield negative variances...")
if(typeof(model) == "list"){
for(thisFit in model) {
message("Output for Model: ", thisFit$name)
umx_standardize(thisFit)
}
} else {
if(!umx_has_been_run(model)){
stop("I can only standardize ACEv models that have been run. Just do\n",
"yourModel = mxRun(yourModel)")
}
selDVs = dimnames(model$top.expCovMZ)[[1]]
nVar <- length(selDVs)/2;
A <- mxEval(top.A, model);
C <- mxEval(top.C, model);
E <- mxEval(top.E, model);
Vtot = A + C + E;
I = diag(nVar);
InvSD <- sqrt(solve(I * Vtot));
model$top$A$values = InvSD %&% A;
model$top$C$values = InvSD %&% C;
model$top$E$values = InvSD %&% E;
return(model)
}
}
umx_standardize.MxModelACEv <- xmu_standardize_ACEv |
getMVptr <- function(rPtr, dll)
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelValuesPtrFromModel, rPtr))
getMVName <- function(modelValuePtr, dll)
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getMVBuildName, modelValuePtr))
CmodelBaseClass <- setRefClass('CmodelBaseClass',
contains = 'modelBaseClass',
fields = list(
.basePtr = 'ANY',
.namedObjectsPtr = 'ANY',
.ModelBasePtr = 'ANY',
dll = 'ANY',
Rmodel = 'ANY',
cppNames = 'ANY',
cppCopyTypes = 'ANY',
compiledModel = 'ANY',
.nodeFxnPointers_byDeclID = 'ANY',
nodeFunctions = 'ANY'
),
methods = list(
show = function() {
cat('CmodelBaseClass object\n')
},
finalizeInternal = function() {
for(vn in cppNames) {
vPtrName <- paste(".", vn, "_Ptr", sep = "")
assign(vPtrName, NULL, inherits = TRUE)
}
finalize()
.basePtr <<- NULL
.namedObjectsPtr <<- NULL
.ModelBasePtr <<- NULL
.nodeFxnPointers_byDeclID <<- NULL
nimbleProject <<- NULL
},
finalize = function() {
for(i in ls(Rmodel$nodes)) {
if(is.null(nodes[[i]])) next
if(is.list(nodes[[i]]))
nodes[[i]][[1]]$finalizeInstance(nodes[[i]][[2]])
else
nodes[[i]]$finalize()
nodes[[i]] <<- NULL
}
if(!is.null(.nodeFxnPointers_byDeclID))
.nodeFxnPointers_byDeclID$finalize()
if(!is.null(.namedObjectsPtr))
nimbleInternalFunctions$nimbleFinalize(.namedObjectsPtr)
},
setModel = function(model) {
Rmodel <<- model
model$CobjectInterface <- .self
},
copyFromModel = function(model) {
if(missing(model)) model <- Rmodel
for(v in cppNames) {
if(cppCopyTypes[[v]] == 'numeric') {
.self[[v]] <<- model[[v]]
next
}
}
},
setupNodes = function(where = classEnvironment, dll = NULL) {
nodesEnv <- new.env()
asTopLevel <- getNimbleOption('buildInterfacesForCompiledNestedNimbleFunctions')
nodeFunctions <<- vector('list', length(Rmodel$nodeFunctions))
for(i in seq_along(Rmodel$nodeFunctions)) {
thisNodeFunName <- names(Rmodel$nodeFunctions)[i]
nodesEnv[[thisNodeFunName]] <- nimbleProject$instantiateNimbleFunction(Rmodel$nodes[[thisNodeFunName]], dll = dll, asTopLevel = asTopLevel)
nodeFunctions[[i]] <<- nodesEnv[[thisNodeFunName]]
}
nodes <<- nodesEnv
names(nodeFunctions) <<- names(Rmodel$nodeFunctions)
.nodeFxnPointers_byDeclID <<- new('numberedObjects', dll = dll)
maxID = length(modelDef$declInfo)
.nodeFxnPointers_byDeclID$resize(maxID)
for(declID in seq_along(nodes)) {
thisNodeFunctionName <- names(Rmodel$nodeFunctions)[declID]
basePtr <- if(is.list(nodes[[thisNodeFunctionName]]))
nodes[[thisNodeFunctionName]][[1]]$basePtrList[[ nodes[[thisNodeFunctionName]][[2]] ]]
else
nodes[[thisNodeFunctionName]]$.basePtr
.self$.nodeFxnPointers_byDeclID[declID] <- basePtr
}
}
)
)
makeModelCppCopyTypes <- function(symTab) {
ans <- list()
for(s in symTab$symbols) {
ans[[s$name]] <- 'numeric'
}
ans
}
makeModelBindingFields <- function(symTab) {
fieldList = list(.modelValues_Ptr = "ANY", .DUMMY = "ANY")
vNames = names(symTab$symbols)
for(vn in vNames){
ptrName = paste(".", vn, "_Ptr", sep = "")
fieldList[[ptrName]] <- "ANY"
eval(substitute( fieldList$VARNAME <- function(x){
if(missing(x) )
nimbleInternalFunctions$getNimValues(VPTR, 2, dll = dll)
else
nimbleInternalFunctions$setNimValues(VPTR, x, 2, allowResize = FALSE, dll = dll)
}, list(VPTR = as.name(ptrName), VARNAME = vn) ) )
}
return(fieldList)
}
buildModelInterface <- function(refName, compiledModel, basePtrCall, project = NULL, dll = NULL, where = globalenv()){
defaults <- list()
if(inherits(compiledModel, 'symbolTable')) {
symTab <- compiledModel
defaults$cm <- NULL
warning('No compiled model provided, so interface will be incomplete')
} else {
symTab <- compiledModel$model$modelDef$symTab
defaults$cm <- compiledModel
}
defaults$cppCT <- makeModelCppCopyTypes(symTab)
defaults$project <- project
defaults$extPtrTypeIndex <- compiledModel$getExtPtrTypeIndex()
if(!is.null(dll) && is.character(basePtrCall))
basePtrCall = getNativeSymbolInfo(basePtrCall, dll)
else
warning("creating an initialization method that calls a C routine without any DLL information")
eval(substitute( newClass <- setRefClass(refName,
fields = FIELDS,
contains = "CmodelBaseClass",
methods = list(initialize = function(model, defaults, basePtrCall, ..., dll = NULL) {
nodes <<- list()
isDataEnv <<- new.env()
classEnvironment <<- new.env()
callSuper(dll = dll, ...)
newPtrPair <- eval(parse(text = ".Call(basePtrCall)"))
.basePtr <<- newPtrPair[[1]]
.ModelBasePtr <<- newPtrPair[[ defaults$extPtrTypeIndex['ModelBase'] ]]
.namedObjectsPtr <<- newPtrPair[[ defaults$extPtrTypeIndex['NamedObjects'] ]]
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$register_namedObjects_Finalizer,
.namedObjectsPtr,
dll[['handle']], model$name))
.modelValues_Ptr <<- nimbleInternalFunctions$getMVptr(.ModelBasePtr, dll = dll)
defaultModelValues <<- nimbleInternalFunctions$CmodelValues$new(existingPtr = .modelValues_Ptr,
buildCall = nimbleInternalFunctions$getMVName(.modelValues_Ptr, dll),
initialized = TRUE, dll = dll )
modelDef <<- model$modelDef
graph <<- model$graph
vars <<- model$vars
isDataVars <<- model$isDataVars
nimbleProject <<- defaults$project
for(v in ls(model$isDataEnv)) isDataEnv[[v]] <<- model$isDataEnv[[v]]
setData(modelDef$constantsList, warnAboutMissingNames = FALSE)
cppNames <<- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getAvailableNames, .namedObjectsPtr))
cppCopyTypes <<- defaults$cppCT
compiledModel <<- defaults$cm
for(vn in cppNames)
{
vPtrName <- paste(".", vn, "_Ptr", sep = "")
.self[[vPtrName]] <<- nimbleInternalFunctions$newObjElementPtr(.namedObjectsPtr, vn, dll = dll)
}
if(!missing(model)) {
setModel(model)
copyFromModel()
setupNodes(dll = dll)
}
},
show = function() {
writeLines(paste0("Derived CmodelBaseClass created by buildModelInterface for model ", modelDef$name))
}),
where = where
), list(FIELDS = makeModelBindingFields(symTab), where = where ) ) )
ans <- function(model, where = globalenv(), dll = NULL, ...) {
newClass$new(model, defaults, basePtrCall, classEnvironment = where, dll = dll, ...)
}
formals(ans)$where = where
formals(ans)$dll = dll
ans
} |
library(phylotate)
test.eq.phylo <- function (test.data, test.data2) {
for (e in c("edge", "edge.length", "Nnode", "tip.label",
"node.comment", "node.distance.comment")) {
e1 <- test.data[[e]]
e2 <- test.data2[[e]]
r <- test.data[[e]] != test.data2[[e]]
r[is.na(e1)] <- TRUE
r[is.na(e2)] <- TRUE
r[is.na(e1) & is.na(e2)] <- FALSE
if (sum(r) > 0) {
print("")
print(e1)
print(e2)
stop(sprintf("%s doesn't match", e))
}
}
}
test.newick.named <- function () {
test.str <- paste0(
"(1[Z]:100[Q],((ABC,((8,(7,(Xyz,(5,(4,(2:200,3:300)))))),(9,10))),",
"((22,((18,(17,(16,",
"(15,(14,(12,13)))))),(21:2100,(Foo,20)))),(23,24))),(53,(52,(((27,",
"(25,26)),(30,(28,29))),(((41[X]:4100[D],(40,(39,(((31,(34,(32,33))),",
"(35,36)),(37[Y],38))))),((44,(42,43[A])),(45,46))),(51,(50,(49,(47,",
"48)))))))))[XYZ]")
print(test.str)
test.data <- parse_annotated(test.str, format="newick")
str(test.data)
test.str2 <- print_annotated(test.data, format="newick.named")
print(test.str2)
if (test.str != test.str2) { stop("Strings don't match!") }
test.data2 <- parse_annotated(test.str2, format="newick")
str(test.data2)
test.eq.phylo(test.data, test.data2)
print("All ok")
}
test.newick <- function () {
test.str <- paste0(
"(1[Z]:100[Q],((11,((8,(7,(6,(5,(4,(2:200,3:300)))))),(9,10))),",
"((22,((18,(17,(16,",
"(15,(14,(12,13)))))),(21:2100,(19,20)))),(23,24))),(53,(52,(((27,",
"(25,26)),(30,(28,29))),(((41[X]:4100[D],(40,(39,(((31,(34,(32,33))),",
"(35,36)),(37[Y],38))))),((44,(42,43[A])),(45,46))),(51,(50,(49,(47,",
"48)))))))))[XYZ]")
print(test.str)
test.data <- parse_annotated(test.str, format="newick")
str(test.data)
test.str2 <- print_annotated(test.data, format="newick")
print(test.str2)
if (test.str != test.str2) { stop("Strings don't match!") }
test.data2 <- parse_annotated(test.str2, format="newick")
str(test.data2)
test.eq.phylo(test.data, test.data2)
print("All ok")
}
test.nexus <- function () {
data(finches)
test <- parse_annotated(finches, format="nexus")
str(test)
test$edge.length <- round(test$edge.length * 100)
if (length(test$tip.label) < 1) {
stop("missing tips")
}
n1 <- print_annotated(test, format="nexus")
print(n1)
p1 <- parse_annotated(n1, format="nexus")
str(p1)
n2 <- print_annotated(p1, format="nexus")
if (n1 != n2) { stop("Strings don't match!") }
p2 <- parse_annotated(n2, format="nexus")
test.eq.phylo(p1, p2)
print("All ok")
}
test.newick()
test.nexus()
test.newick.named() |
noiseOut <-
function(noise, mu, varsigma) {
fhandle = get(paste(noise$type, "NoiseOut", sep=""), mode="function")
y = fhandle(noise, mu, varsigma)
return (y)
} |
inlib <- function(lib, expr, add = TRUE){
oldlib <- .libPaths();
on.exit(setlib(oldlib), add = TRUE)
if(isTRUE(add)){
lib <- c(lib, .libPaths())
}
lib <- unique(normalizePath(lib, mustWork = FALSE))
lib <- Filter(function(x){
isTRUE(file.info(x)$isdir)
}, lib)
setlib(lib)
force(expr)
}
setlib <- function(lib){
assign(".lib.loc", lib, envir = environment(.libPaths))
} |
lsHu2.chi <- function(x, c0){
beta.c0 <- 2*pnorm(c0) - 1 - 2*c0*dnorm(c0) + 2*c0^2*pnorm(-c0)
return(pmin(x^2, c0^2) - beta.c0)
}
.Hu2rlsGetbias <- function(x, k, c0){
beta.c0 <- 2*pnorm(c0) - 1 - 2*c0*dnorm(c0) + 2*c0^2*pnorm(-c0)
sqrt(pmin(k^2, x^2)/(2*pnorm(k)-1)^2 + (pmin(c0^2, x^2) - beta.c0)^2/
(2*(2*pnorm(c0) - 1) - 4*c0*dnorm(c0))^2)
}
.Hu2rlsGetvar <- function(k, c0){
beta.c0 <- 2*pnorm(c0) - 1 - 2*c0*dnorm(c0) + 2*c0^2*pnorm(-c0)
Var.loc <- (2*pnorm(k) - 1 - 2*k*dnorm(k) + 2*k^2*(1-pnorm(k)))/(2*pnorm(k)-1)^2
hilf <- 3*(2*pnorm(c0)-1) - 2*c0^3*dnorm(c0) - 6*c0*dnorm(c0) + 2*c0^4*pnorm(-c0)
Var.sc <- (hilf - beta.c0^2)/(2*(2*pnorm(c0) - 1) - 4*c0*dnorm(c0))^2
return(Var.loc + Var.sc)
}
.Hu2rlsGetmse <- function(kc0, r, MAX){
k <- kc0[1]; c0 <- kc0[2]
if(k < 0 || c0 < 0) return(MAX)
beta.c0 <- 2*pnorm(c0) - 1 - 2*c0*dnorm(c0) + 2*c0^2*pnorm(-c0)
A.loc <- 1/(2*pnorm(k)-1)
A.sc <- 1/(2*(2*pnorm(c0) - 1) - 4*c0*dnorm(c0))
bias <- max(.Hu2rlsGetbias(x = 0, k = k, c0 = c0),
.Hu2rlsGetbias(x = k, k = k, c0 = c0),
.Hu2rlsGetbias(x = c0, k = k, c0 = c0),
.Hu2rlsGetbias(x = sqrt(beta.c0), k = k, c0 = c0),
.Hu2rlsGetbias(x = sqrt(max(0, beta.c0-0.5*A.loc^2/A.sc^2)),
k = k, c0 = c0))
Var <- .Hu2rlsGetvar(k = k, c0 = c0)
return(Var + r^2*bias^2)
}
rlsOptIC.Hu2 <- function(r, k.start = 1.5, c.start = 1.5, delta = 1e-6, MAX = 100){
res <- optim(c(k.start, c.start), .Hu2rlsGetmse, method = "Nelder-Mead",
control = list(reltol=delta), r = r, MAX = MAX)
k <- res$par[1]; c0 <- res$par[2]
beta.c0 <- 2*pnorm(c0) - 1 - 2*c0*dnorm(c0) + 2*c0^2*pnorm(-c0)
A.loc <- 1/(2*pnorm(k)-1)
A.sc <- 1/(2*(2*pnorm(c0) - 1) - 4*c0*dnorm(c0))
bias <- max(.Hu2rlsGetbias(x = 0, k = k, c0 = c0),
.Hu2rlsGetbias(x = k, k = k, c0 = c0),
.Hu2rlsGetbias(x = c0, k = k, c0 = c0),
.Hu2rlsGetbias(x = sqrt(beta.c0), k = k, c0 = c0),
.Hu2rlsGetbias(x = sqrt(max(0, beta.c0-0.5*A.loc^2/A.sc^2)),
k = k, c0 = c0))
fct1 <- function(x){ A.loc*sign(x)*pmin(abs(x), k) }
body(fct1) <- substitute({ A.loc*sign(x)*pmin(abs(x), k) },
list(k = k, A.loc = A.loc))
fct2 <- function(x){ A.sc*(pmin(x^2, c0^2) - beta.c0) }
body(fct2) <- substitute({ A.sc*(pmin(x^2, c0^2) - beta.c0) },
list(c0 = c0, beta.c0 = beta.c0, A = A.sc))
return(IC(name = "IC of Hu2 type",
Curve = EuclRandVarList(RealRandVariable(Map = list(fct1, fct2), Domain = Reals())),
Risks = list(asMSE = res$value, asBias = bias, asCov = res$value - r^2*bias^2),
Infos = matrix(c("rlsOptIC.Hu2", "optimally robust IC for Hu2 estimators and 'asMSE'",
"rlsOptIC.Hu2", paste("where k =", round(k, 3), "and c =", round(c0, 3))),
ncol=2, byrow = TRUE, dimnames=list(character(0), c("method", "message"))),
CallL2Fam = call("NormLocationScaleFamily")))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.