code
stringlengths 1
13.8M
|
---|
msle = function(truth, response, sample_weights = NULL, na_value = NaN, ...) {
assert_regr(truth, response = response, na_value = na_value)
if (min(truth, response) <= -1) {
return(na_value)
}
wmean(sle(truth, response), sample_weights)
}
add_measure(msle, "Mean Squared Log Error", "regr", 0, Inf, TRUE)
|
df_to_json_list <- function(df) {
if (!requireNamespace("jsonlite", quietly = TRUE)) {
stop(
"Package \"jsonlite\" needed for this function to work. Please install it.",
call. = FALSE
)
}
result <- vector("list", nrow(df))
for (i in seq_len(nrow(df))) {
result[[i]] <- jsonlite::toJSON(jsonlite::unbox(df[i, , drop = FALSE]))
}
result
}
|
grab_reich_lab_deaths <- function(){
library(httr)
req <- httr::GET("https://api.github.com/repos/reichlab/covid19-forecast-hub/git/trees/master?recursive=1")
httr::stop_for_status(req)
filelist<- unlist(lapply(content(req)$tree, "[", "path"), use.names = F)
filelist <- grep("data-processed/", filelist, value = TRUE, fixed = TRUE)
filelist <- grep(".csv", filelist, value = TRUE, fixed = TRUE)
filelist <- lapply(filelist, function(x) paste0("https://raw.githubusercontent.com/reichlab/covid19-forecast-hub/master/",x))
foo <- data.table::rbindlist(lapply(filelist, read_reich))
foo <- foo %>%
data.table::dcast.data.table(target_end_date + target + model_team + forecast_date ~ measure,value.var = "value") %>%
.[, maxdate :=max(forecast_date), by=.(model_team)] %>%
.[forecast_date == maxdate & as.Date(target_end_date) <= Sys.Date() + 30,
.(model_team, pointNA, target_end_date)]
return(foo)
}
|
library(ggplot2)
load('output/result-model11-8.RData')
ms <- rstan::extract(fit_vb)
probs <- c(0.1, 0.25, 0.5, 0.75, 0.9)
idx <- expand.grid(tag=1:K, item=1:I)
qua <- apply(idx, 1, function(x) quantile(ms$phi[,x[1],x[2]], probs=probs))
d_est <- data.frame(idx, t(qua), check.names=FALSE)
p <- ggplot(data=d_est, aes(x=item, y=`50%`)) +
theme_bw(base_size=18) +
theme(axis.text.x=element_text(angle=40, vjust=1, hjust=1)) +
facet_wrap(~tag, ncol=3) +
coord_flip() +
scale_x_reverse(breaks=c(1, seq(20, 120, 20))) +
geom_bar(stat='identity') +
labs(x='ItemID', y='phi[k,y]')
ggsave(file='output/fig11-11-left.png', plot=p, dpi=300, w=7, h=5)
|
`screeplot.epplab` <- function(x,type="lines",which=1:10,main="",ylab="Objective criterion",xlab="Simulation run",...){
which <- which[which<=length(x$PPindexVal)]
temp <- x$PPindexVal[which]
names(temp) <- colnames(x$PPdir)[which]
type<-match.arg(type,c("barplot","lines"))
if (type=="barplot")
{
barplot(temp,ylab=ylab,xlab=xlab,main=main,...)
} else{
plot(temp,type="b",ylab=ylab,xlab=xlab,main=main,...)
}
invisible()
}
|
LRC <- function(X,costs){
if (missingArg(X))
stop("The X argument is missing.")
if (missingArg(costs))
stop("The cost vector argument 'costs' is missing.")
rate <- TRUE
indicator <- LimDist(X,rate)$indicator
if(indicator==1){
occup_dist <- LimDist(X,rate)$Lim_dist
output <- list("It was possible to calculate the long-run cost rate!", LRCR=occup_dist%*%costs)
return(output)
}
else{return(list(indicator=0,"It was not possible to calculate the long-run cost rate."))}
}
|
simple <- function(src,...){
noquotes <- gsub("([\"'`]).*\\1","",src)
print(noquotes)
comments <- grep("
pat <- "[^
tags <- gsub(pat,"\\1",comments)
docs <- as.list(gsub(pat,"\\2",comments))
names(docs) <- tags
docs[tags!=""]
}
.parsers <- list(simple=inlinedocs::forfun(simple))
testfun <- function(x,y,z){
a <- (x+y)*z
a
}
.result <- list(
testfun=list(
`item{x}`="the first arg",
value="the sum of the first two times the third",
description="a useless formula"),
simple=list(
title="a simple Parser Function",
value="all the tags with a single pound sign"))
.dontcheck <- TRUE
|
as_vegaspec.altair.vegalite.v4.api.TopLevelMixin <- function(spec, ...) {
spec <- spec$to_json()
vegawidget::as_vegaspec(spec, ...)
}
print.altair.vegalite.v4.api.TopLevelMixin <- function(x, ...) {
x <- as_vegaspec(x)
print(x, ...)
}
format.altair.vegalite.v4.api.TopLevelMixin <- function(x, ...) {
x <- as_vegaspec(x)
format(x, ...)
}
knit_print.altair.vegalite.v4.api.TopLevelMixin <- function(spec, ..., options = NULL) {
spec <- as_vegaspec(spec)
knitr::knit_print(spec, ..., options = options)
}
|
determination <- function(xreg, bruteforce=TRUE, ...){
nVariables <- ncol(xreg);
nSeries <- nrow(xreg);
vectorCorrelationsMultiple <- rep(NA,nVariables);
names(vectorCorrelationsMultiple) <- colnames(xreg);
if(nSeries<=nVariables & bruteforce){
warning(paste0("The number of variables is larger than the number of observations. ",
"Sink regression cannot be constructed. Using stepwise."),
call.=FALSE);
bruteforce <- FALSE;
}
if(!bruteforce){
determinationCalculator <- function(residuals, actuals){
return(1 - sum(residuals^2) / sum((actuals-mean(actuals))^2));
}
}
if(any(class(xreg) %in% c("tbl","tbl_df","data.table"))){
class(xreg) <- "data.frame";
}
if(bruteforce & nVariables>1){
if(!is.numeric(xreg) && !all(unlist(lapply(xreg,is.numeric)))){
for(i in 1:nVariables){
vectorCorrelationsMultiple[i] <- suppressWarnings(mcor(xreg[,-i,drop=FALSE],xreg[,i])$value^2);
}
}
else{
corMatrix <- cor(xreg, ...);
for(i in 1:nVariables){
vectorCorrelationsMultiple[i] <- tryCatch(corMatrix[i,-i,drop=FALSE] %*%
chol2inv(chol(corMatrix[-i,-i,drop=FALSE])) %*%
corMatrix[-i,i,drop=FALSE], error=function(e) 1);
}
}
}
else if(!bruteforce & nVariables>1){
testXreg <- xreg;
colnames(testXreg) <- paste0("x",c(1:nVariables));
testModel <- suppressWarnings(stepwise(testXreg));
vectorCorrelationsMultiple[1] <- determinationCalculator(residuals(testModel),
actuals(testModel));
for(i in 2:nVariables){
testXreg[] <- xreg;
testXreg[,1] <- xreg[,i];
testXreg[,i] <- xreg[,1];
testModel <- suppressWarnings(stepwise(testXreg));
vectorCorrelationsMultiple[i] <- determinationCalculator(residuals(testModel),
actuals(testModel));
}
}
else{
vectorCorrelationsMultiple <- 0;
}
return(vectorCorrelationsMultiple);
}
determ <- function(object, ...) UseMethod("determ")
determ.default <- function(object, ...){
return(determination(object, ...));
}
determ.lm <- function(object, ...){
return(determination(object$model[,-1], ...));
}
determ.alm <- function(object, ...){
return(determination(object$data[,-1], ...));
}
|
eval_sbo_predictor <- function(model, test, L = attr(model, "L")){
msg <- if (!is.object(model) || class(model)[1] != "sbo_predictor") {
"'model' must be a 'sbo_predictor' class object."
} else if (!is.character(test)) {
"'test' must be a character vector."
} else if (length(test) < 1) {
"'test' must be of length at least 1."
} else if (!is.numeric(L) | length(L) != 1) {
"'L' must be a length one integer."
} else if (L < 1) {
"'L' must be greater than one."
}
if (!is.null(msg))
rlang::abort(class = "sbo_domain_error", message = msg)
test_kgrams <- sample_kgrams(model, test)
if (nrow(test_kgrams) == 0) {
return(tibble(input = character(), true = character(),
preds = matrix(nrow = 0, ncol = 3),
correct = logical(0))
)
}
test_kgrams %>%
group_by(row_number()) %>%
mutate(preds = matrix(predict(model, .data$input)[1:L], ncol = L
),
correct = .data$true %in% .data$preds) %>%
ungroup %>%
select(.data$input, .data$true, .data$preds, .data$correct)
}
sample_kgrams <- function(model, test) {
N <- attr(model, "N")
wrap <- c(paste0(rep("<BOS>", N - 1), collapse = " "), "<EOS>")
EOS <- attr(model, "EOS")
test <- attr(model, ".preprocess")(test)
lapply(test, function(x) {
if (EOS != "")
x <- tokenize_sentences(x, EOS = EOS)
if (length(x) == 0)
return(tibble(input = character(0), true = input))
x <- sample(x, 1) %>%
paste(wrap[[1]], ., wrap[[2]], sep = " ") %>%
strsplit(" ", fixed = TRUE) %>%
unlist %>%
.[. != ""]
if (length(x) < N + 1)
return(tibble(input = character(0), true = input))
i <- sample(1:(length(x) - N + 1), 1)
input <- paste0(x[i + seq_len(N - 1) - 1], collapse = " ")
tibble(input = input, true = x[i + N - 1])
}
) %>%
bind_rows %>%
mutate(input = gsub("<BOS>", "", .data$input))
}
|
aw_get_dimensions <- function(rsid = Sys.getenv("AW_REPORTSUITE_ID"),
locale = 'en_US',
segmentable = FALSE,
reportable = FALSE,
classifiable = FALSE,
expansion = NA,
debug = FALSE,
company_id = Sys.getenv("AW_COMPANY_ID") ){
if(is.na(paste(expansion,collapse=","))) {
vars <- tibble::tibble(locale, segmentable)
}
if(!is.na(paste(expansion,collapse=","))) {
vars <- tibble::tibble(locale, segmentable, reportable, classifiable, expansion = paste(expansion,collapse=","))
}
prequery <- list(vars %>% dplyr::select_if(~ any(!is.na(.))))
query_param <- stringr::str_remove_all(stringr::str_replace_all(stringr::str_remove_all(paste(prequery, collapse = ''), '\\"'), ', ', '&'), 'list\\(| |\\)')
urlstructure <- glue::glue('dimensions?rsid={rsid}&{query_param}')
res <- aw_call_api(req_path = urlstructure, debug = debug, company_id = company_id)
res <- jsonlite::fromJSON(res)
res$id <- stringr::str_sub(res$id, 11)
res
}
|
add_fpsim <- function(data, keep) {
if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("dyad_year", "leader_dyad_year")) {
if (!all(i <- c("ccode1", "ccode2") %in% colnames(data))) {
stop("add_fpsim() merges on two Correlates of War codes (ccode1, ccode2), which your data don't have right now. Make sure to run create_dyadyears() at the top of the pipe. You'll want the default option, which returns Correlates of War codes.")
} else {
if (!file.exists(system.file("extdata", "dyadic_fp_similarity.rds", package="peacesciencer"))) {
stop("Dyadic foreign policy similarity data are stored remotely and must be downloaded separately.\nThis error disappears after successfully running `download_extdata()`. Thereafter, the function works with no problem and the dyadic trade data (`cow_trade_ddy`) can be loaded for additional exploration.")
} else {
fpsim_data <- readRDS(system.file("extdata", "dyadic_fp_similarity.rds", package="peacesciencer"))
if (!missing(keep)) {
fpsim_data <- subset(fpsim_data, select = c("year", "ccode1", "ccode2", keep))
} else {
fpsim_data <- fpsim_data
}
fpsim_data %>%
left_join(data, .) -> data
return(data)
}
}
} else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("state_year", "leader_year")) {
stop("add_fpsim() right now only works with dyadic data (either dyad-year or leader-dyad-year).")
} else {
stop("add_fpsim() requires a data/tibble with attributes$ps_data_type of leader_dyad_year or dyad_year. Try running create_dyadyears() or create_leaderdyadyears() at the start of the pipe.")
}
return(data)
}
|
pvals.ridgeLogistic <- function(x, ...)
{
automatic <- x$automatic
chosen.nPCs <- x$chosen.nPCs
max.nPCs <- x$max.nPCs
isScaled <- x$isScaled
B <- x$coef
Inter <- x$Inter
if(Inter)
{
X <- cbind(1,x$x)
} else {
X <- x$x
}
lambda <- x$lambda
xb <- apply(B, 2, function(x){X %*% x})
expXB <- exp(xb)
p <- expXB / (1 + expXB)
W <- vector("list", length = ncol(p))
for(i in seq(ncol(p)))
{
W[[i]] <- diag(p[,i]*(1-p[,i]),length(p[,i]),length(p[,i]))
}
KI <- lapply(lambda, function(x){diag(2 * x, dim(X)[2], dim(X)[2])})
if(Inter)
{
for(i in seq(length(lambda)))
{
KI[[i]][1,1] <- 0
}
}
computeV <- function(W, KI)
{
V <- solve(t(X)%*%W%*%X+KI) %*% (t(X)%*%W%*%X) %*% solve(t(X)%*%W%*%X+KI)
return(V)
}
V <- mapply("computeV", W, KI, SIMPLIFY = FALSE)
se <- sapply(V, function(x){sqrt(diag(x))})
tstat <-B/se
pval <- 2*(1 - pnorm(abs(tstat)))
if(Inter)
{
B <- B[-1, ]
se <- se[-1, ]
tstat <- tstat[-1, ]
pval <- pval[-1, ]
}
res <- list(coef = cbind(B), se = cbind(se), tstat = cbind(tstat), pval = cbind(pval), isScaled = isScaled, automatic = automatic, lambda = lambda, chosen.nPCs = chosen.nPCs, max.nPCs = max.nPCs)
class(res) <- "pvalsRidgeLogistic"
res
}
|
sampleDelta2 <-
function(pos, x, q, B, S, sig2, alphad2, betad2){
plus = 0
if(sum(S[pos,]) > 0){
Bi = B[pos, which(S[pos,] == 1)]
xi = x[, which(S[pos,] == 1)]
plus = Bi %*% t(xi) %*% xi %*% Bi / (2* sig2)
}
out = rinvgamma(1, shape=sum(S[pos,1:q]) + alphad2,
scale=betad2 + plus)
return(out)
}
|
teamERAcrossOversAllOppnAllMatches <- function(matches,t1,plot=1) {
team=ball=totalRuns=total=ER=type=meanER=str_extract=NULL
ggplotly=NULL
a <-filter(matches,team==t1)
a1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9))
a2 <- select(a1,team,date,totalRuns)
a3 <- a2 %>% group_by(team,date) %>% summarise(total=sum(totalRuns),count=n())
a3$ER=a3$total/a3$count * 6
a4 = a3 %>% select(team,ER) %>% summarise(meanER=mean(ER))
a4$type="1-Power Play"
b1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9))
b2 <- select(b1,team,date,totalRuns)
b3 <- b2 %>% group_by(team,date) %>% summarise(total=sum(totalRuns),count=n())
b3$ER=b3$total/b3$count * 6
b4 = b3 %>% select(team,ER) %>% summarise(meanER=mean(ER))
b4$type="2-Middle Overs"
c1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0))
c2 <- select(c1,team,date,totalRuns)
c3 <- c2 %>% group_by(team,date) %>% summarise(total=sum(totalRuns),count=n())
c3$ER=c3$total/c3$count * 6
c4 = c3 %>% select(team,ER) %>% summarise(meanER=mean(ER))
c4$type="3-Death Overs"
m=rbind(a4,b4,c4)
plot.title= paste("Wickets across 20 overs by ",t1,"in all matches against all teams", sep=" ")
if(plot ==1){
ggplot(m,aes(x=type, y=meanER, fill=t1)) +
geom_bar(stat="identity", position = "dodge") +
ggtitle(bquote(atop(.(plot.title),
atop(italic("Data source:http://cricsheet.org/"),""))))
}else {
g <- ggplot(m,aes(x=type, y=meanER, fill=t1)) +
geom_bar(stat="identity", position = "dodge") +
ggtitle(plot.title)
ggplotly(g)
}
}
|
fit2list=function(fit){
data=fit2model(fit)
mode=1
if("glm" %in% attr(fit,"class")) {
mode=2
family = fit$family$family
}
xvars = attr(fit$terms, "term.labels")
xno = length(xvars)
yvar = as.character(attr(fit$terms, "variables"))[2]
xvars
yvar
data
fitlist=map(xvars,function(x){
myformula=paste0(yvar,"~",x)
if(mode==1){
fit=lm(as.formula(myformula),data=data)
} else if(mode==2) {
fit=glm(as.formula(myformula),family=family,data=data)
}
})
class(fitlist)="fitlist"
fitlist
}
|
get.range.rLNLN <-
function(method,prev.result,dataset,n,TY,fix.mu,fixed.mu) {
stochprof.results <- NULL
calculate.ci <- NULL
rm(stochprof.results)
rm(calculate.ci)
if (((method=="none") || (nrow(prev.result)==0)) || (is.null(prev.result))) {
return(NULL)
}
m <- (ncol(prev.result)+1)/TY - 2
res <- stochprof.results(prev.result=prev.result,TY=TY,show.plots=F)
if (is.null(res)) {
return(NULL)
}
best <- res[1,-ncol(res),drop=F]
if (method=="best") {
ranges <- cbind(t(best),t(best))
}
else if (substr(method,2,3)=="se") {
this.se <- apply(X=res[,-ncol(res)],MARGIN=2,FUN=sd)
a <- as.double(substr(method,1,1))
ranges <- cbind(t(best)-a*this.se,t(best)+a*this.se)
}
else if (method=="top20") {
toptargets <- res[1:min(20,nrow(res)),1:(ncol(res)-1),drop=F]
lower <- apply(X=toptargets,MARGIN=2,FUN=min)
upper <- apply(X=toptargets,MARGIN=2,FUN=max)
ranges <- cbind(lower,upper)
}
else if (method=="quant") {
lower <- rep(NA,ncol(res)-1)
upper <- lower
for (i in 1:length(lower)) {
this.par <- res[,i]
this.par <- this.par[order(this.par)]
lower.pos <- min(length(this.par),round(1,0.2 * length(this.par)+1))
upper.pos <- max(1,round(0.8 * length(this.par)-1))
lower[i] <- this.par[lower.pos]
upper[i] <- this.par[upper.pos]
}
ranges <- cbind(lower,upper)
}
else if (method=="mlci") {
ranges <- calculate.ci(alpha=0.05,parameter=best,dataset=dataset,n=n,TY=TY,fix.mu=fix.mu,fixed.mu=fixed.mu)
return(ranges)
}
if (method!="best") {
if (TY>1) {
ranges[1:(TY-1),1] <- pmax(0,ranges[1:(TY-1),1])
ranges[1:(TY-1),2] <- pmin(1,ranges[1:(TY-1),2])
}
ranges[nrow(ranges)-((TY-1):0),1] <- pmax(ranges[nrow(ranges)-((TY-1):0),1],0.01)
ranges[nrow(ranges)-((TY-1):0),2] <- pmax(ranges[nrow(ranges)-((TY-1):0),2],ranges[nrow(ranges)-((TY-1):0),1]+0.05)
}
return(ranges)
}
|
`mstlines` <-
function(mst, x, y = NULL, pts.names = NULL, ...) {
a <- colnames(mst)
if (ncol(as.matrix(x)) >= 2 & nrow(as.matrix(x)) >= 2 & is.null(y) == TRUE) b <- x[,1:2]
else b <- cbind(x,y)
if (is.null(pts.names) == FALSE) rownames(b) <- pts.names
else rownames(b) <- colnames(mst)
v <- colnames(mst)
for (i in 1:nrow(mst)) {
for (j in 1:ncol(mst)) {
if (mst[i, j] == 1) {
lines(c(b[v[i], 1], b[v[j],1]), c(b[v[i], 2], b[v[j],2]), ...)
}
}
}
}
|
positive_definite <- function(m, c=NULL){
if(!is.null(c) && c<=0) stop("Parameter c must be a nonegative number.")
ei <- eigen(m)
if(any(ei$values<0)){
cc<-10^{seq(-5,10,by=1)}
ord<-min(abs(ei$values))/cc
if(is.null(c)) c<-cc[max(which(ord>100))]
neigen <- ei$values+abs(min(ei$values))+c
m <- ei$vectors%*%diag(neigen,2,2)%*%t(ei$vectors)
}
return(list(m=m, c=c))
}
|
fregre.basis.cv.old <- function(fdataobj,y,basis.x=NULL,basis.b=NULL,
type.basis=NULL,lambda=0,Lfdobj=vec2Lfd(c(0,0),rtt),
type.CV=GCV.S,par.CV=list(trim=0),weights= rep(1,n),
verbose=FALSE,...){
call<-match.call()
if (!is.fdata(fdataobj)) fdataobj=fdata(fdataobj)
tol<-sqrt(.Machine$double.eps)
x<-fdataobj[["data"]]
tt<-fdataobj[["argvals"]]
rtt<-fdataobj[["rangeval"]]
n = nrow(x)
np <- ncol(x)
W<-diag(weights)
tol<-sqrt(.Machine$double.eps)
if (n != (length(y))) stop("ERROR IN THE DATA DIMENSIONS")
if (is.null(rownames(x))) rownames(x) <- 1:n
if (is.null(colnames(x))) colnames(x) <- 1:np
if (is.matrix(y)) y=as.vector(y)
fou<-FALSE
if (is.null(basis.x)) {
nbasis1=seq(5,max(floor(np/5),11),by=2)
lenbasis.x=length(nbasis1)
basis.x=list()
for (nb.x in 1:lenbasis.x) {
if (!is.null(type.basis)) {
aa1 <- paste("create.", type.basis[1], ".basis", sep = "")
as <- list()
as[[1]] <- range(tt)
names(as)[[1]] <- "rangeval"
as[[2]] <- nbasis1[nb.x]
names(as)[[2]] <- "nbasis"
if (verbose) basis.x[[nb.x]]=do.call(aa1, as)
else basis.x[[nb.x]]=suppressWarnings(do.call(aa1,as))
}
else basis.x[[nb.x]]=create.bspline.basis(rangeval=rtt,nbasis=nbasis1[nb.x],...)
}
}
else nbasis1<-basis.x
if (is.null(basis.b)) {
basis.b<-basis.x
nbasis2<-nbasis1
fou<-TRUE
}
else nbasis2<-basis.b
lenlambda=length(lambda)
a1=list() ;a2=list()
if (!is.null(type.basis)){
if (type.basis=="fourier") fou<-TRUE}
if (!is.list(basis.x)) {
lenbasis.x=length(basis.x)
for (nb.x in 1:lenbasis.x) {
if (!is.null(type.basis)) {
aa1 <- paste("create.", type.basis[1], ".basis", sep = "")
as <- list()
as[[1]] <- rtt
names(as)[[1]] <- "rangeval"
as[[2]] <- basis.x[nb.x]
names(as)[[2]] <- "nbasis"
if (verbose) a1[[nb.x]]=do.call(aa1, as)
else a1[[nb.x]]=suppressWarnings(do.call(aa1, as))
}
else a1[[nb.x]]=create.bspline.basis(rangeval=rtt,nbasis=basis.x[[nb.x]])
}
basis.x=a1
}
else lenbasis.x=length(nbasis1)
if (!is.list(basis.b)) {
lenbasis.y=length(basis.b)
maxbasis.y<-which.max(basis.b)
for (nb.y in 1:lenbasis.y) {
if (!is.null(type.basis)) {
if (length(type.basis)>1) aa1 <- paste("create.", type.basis[2], ".basis", sep = "")
else aa1 <- paste("create.", type.basis[1], ".basis", sep = "")
as <- list()
as[[1]] <- rtt
names(as)[[1]] <- "rangeval"
as[[2]] <- basis.b[nb.y]
names(as)[[2]] <- "nbasis"
if (verbose) a2[[nb.y]]=do.call(aa1, as)
else a2[[nb.y]]=suppressWarnings(do.call(aa1, as))
}
else a2[[nb.y]]=create.bspline.basis(rangeval=rtt,nbasis=basis.b[[nb.y]])
}
basis.b=a2
}
else {
lenbasis.y=length(nbasis2)
maxbasis.y<-which.max(nbasis2)
}
pr=Inf
i.lambda.opt=1;i.nb.y.opt=1;i.nb.x.opt=1
xx<-fdata.cen(fdataobj)
xmean=xx[[2]]
xcen=xx[[1]]
ymean=mean(y)
ycen=y-ymean
if (fou) {
basis.x<-basis.b
nbasis1<-nbasis2
if (verbose) warning("Same number of basis elements in the basis.x and basis.b")
lenbasis.x<-lenbasis.y
nbasis12<-rep(NA,lenbasis.x)
nbasis22<-rep(NA,lenbasis.y)
x.fdfou<-Cfou<-Cmfou<- list()
for (nb.x in 1:lenbasis.x) {
x.fd=x.fdfou[[nb.x]] =Data2fd(argvals=tt,y=t(xcen$data),basisobj=basis.x[[nb.x]])
Cfou[[nb.x]]=t(x.fdfou[[nb.x]]$coefs)
Cmfou[[nb.x]]=matrix(t(mean.fd(x.fdfou[[nb.x]])$coefs))
nbasis12[nb.x]<-basis.x[[nb.x]]$type
}
}
else {
nbasis12<-rep(NA,lenbasis.x)
nbasis22<-rep(NA,lenbasis.y)
x.fdfou<-Cfou<-Cmfou<- list()
for (nb.x in 1:lenbasis.x) {
x.fd=x.fdfou[[nb.x]] =Data2fd(argvals=tt,y=t(xcen$data),basisobj=basis.x[[nb.x]])
Cfou[[nb.x]]=t(x.fdfou[[nb.x]]$coefs)
Cmfou[[nb.x]]=matrix(t(mean.fd(x.fdfou[[nb.x]])$coefs))
nbasis12[nb.x]<-basis.x[[nb.x]]$type
}
}
gcv=array(NA,dim=c(lenbasis.x,lenbasis.y,lenlambda))
for (nb.x in 1:lenbasis.x) {
if (fou) {ifou<-nb.x;iifou<-nb.x}
else {ifou<-1;iifou<-lenbasis.y }
for (nb.y in ifou:iifou) {
nbasis22[nb.y]<-basis.b[[nb.y]]$type
C<-Cfou[[nb.x]]
Cm<-Cmfou[[nb.x]]
J<-inprod(basis.x[[nb.x]],basis.b[[nb.y]])
Z=C%*%J
Z=cbind(rep(1,len=n),Z)
if (min(lambda,na.rm=TRUE)!=0) {
R=diag(0,ncol= basis.b[[nb.y]]$nbasis+1,nrow=basis.b[[nb.y]]$nbasis+1)
R[-1,-1]<-eval.penalty(basis.b[[nb.y]],Lfdobj)
}
else R=0
for (k in 1:lenlambda) {
Sb=t(Z)%*%W%*%Z+lambda[k]*R
Cinv<-Minverse(Sb)
Sb2=Cinv%*%t(Z)%*%W
par.CV$S <-Z%*%Sb2
par.CV$y<-y
gcv[nb.x,nb.y,k]<- do.call(type.CV,par.CV)
if ((gcv[nb.x,nb.y,k]+tol)<pr) {
pr=gcv[nb.x,nb.y,k]
lambda.opt=lambda[k]
basis.b.opt=basis.b[[nb.y]]
basis.x.opt=basis.x[[nb.x]]
Sb.opt=Sb2
Z.opt=Z
Cm.opt=Cm
J.opt=J
Cinv.opt=Cinv
}
}
} }
if (all(is.na(gcv))) stop("System is computationally singular. Try to reduce the number of basis elements")
l = which.min(gcv)[1]
gcv.opt=min(gcv,na.rm=TRUE)
S=Z.opt%*%Sb.opt
DD<-t(Z.opt)%*%y
yp=S%*%y
b.est=Sb.opt%*%y
bet<-Cinv.opt%*%DD
rownames(b.est)<-1:nrow(b.est)
rownames(b.est)[1]<- "(Intercept)"
beta.est=fd(b.est[-1,1],basis.b.opt)
a.est=b.est[1,1]
e=drop(y)-drop(yp)
names(e)<-rownames(x)
df=basis.b.opt$nbasis+1
sr2=sum(e^2)/(n-df)
Vp<-sr2*Cinv.opt
r2=1-sum(e^2)/sum(ycen^2)
object.lm=list()
object.lm$coefficients<-drop(b.est)
object.lm$residuals<-drop(e)
object.lm$fitted.values<-yp
object.lm$y<-y
object.lm$x<-Z.opt
object.lm$rank<-df
object.lm$df.residual<-n-df
vfunc=call[[2]]
colnames(Z.opt)<-1:ncol(Z.opt)
colnames(Z.opt)[2:ncol(Z.opt)]= paste(vfunc,".",basis.b.opt$names, sep = "")
colnames(Z.opt)[1]="(Intercept)"
vcov2=sr2*Cinv.opt
std.error=sqrt(diag(vcov2))
t.value=b.est/std.error
p.value= 2 * pt(abs(t.value),n-df, lower.tail = FALSE)
coefficients<-cbind(b.est,std.error,t.value,p.value)
colnames(coefficients) <- c("Estimate", "Std. Error", "t value", "Pr(>|t|)")
rownames(coefficients)<-colnames(Z.opt)
class(object.lm) <- "lm"
b.est=b.est[-1]
names(b.est)<-rownames(coefficients)[-1]
lambda2<-paste("lambda=",lambda,sep="")
if (fou) {
nbasis12<-paste(nbasis12,nbasis2,sep="")
gcv<-as.matrix(apply(gcv,3,diag))
rownames(gcv)<-nbasis12
colnames(gcv)<-lambda2
}
else{
nbasis12<-paste(nbasis12,nbasis1,sep="")
nbasis22<-paste(nbasis22,nbasis2,sep="")
dimnames(gcv)<-list(nbasis12,nbasis22,lambda2)
}
x.fd=Data2fd(argvals=tt,y=t(xcen$data),basisobj=basis.x.opt)
out<-list("call"=call,"coefficients"=coefficients,"residuals"=e,
"fitted.values"=yp,"beta.est"=beta.est,weights= weights,
"df"=df,"r2"=r2,"sr2"=sr2,"Vp"=Vp,"H"=S,"y"=y,
"fdataobj"=fdataobj,x.fd=x.fd,"gcv"=gcv,"lambda.opt"=lambda.opt,
"gcv.opt"=gcv.opt,"b.est"=b.est,"a.est"=a.est,
"basis.x.opt"=basis.x.opt,"basis.b.opt"=basis.b.opt,
"J"=J.opt,"lm"=object.lm,"mean"=xmean)
class(out)="fregre.fd"
return(invisible(out))
}
|
syn_mice_create_design_matrix <- function(x, xp, formula=NULL)
{
if (is.null(formula)){
formula <- as.formula( paste0("~ ", paste0( colnames(x), collapse="+") ) )
}
x <- stats::model.matrix(formula, data=x)
xp <- stats::model.matrix(formula, data=xp)
if (colnames(x)[1]=="(Intercept)"){
x <- x[,-1]
xp <- xp[,-1]
}
colnames(xp) <- colnames(x) <- paste0("x",1:ncol(x))
res <- list(x=x, xp=xp)
return(res)
}
|
plot.sigProb <- function(x, prob, xvar, main="", ylab, xlab, col="blue", pch=16, ...){
object <- x
if(missing(prob)){
stop("The y-variable prob must be specified")
}else{
prob <- stringr::str_to_lower(prob)
}
ntheta <- nrow(object$par)
ndata <- nrow(object$model)
if(ndata <=1 & ntheta <= 1){
stop("Only one row or less found for both model data and parameters. Not enough variation to plot")
}
if(ndata <= 1 & ntheta > 1){
if(missing(xvar)){
search <- lapply(object$par, unique)
search$Row <- NULL
xvar <- names(which(sapply(search, function(x){length(x)>1})))
if(length(xvar)>1){
stop("More than one candidate for xvar found, please specify it directly")
}
xvar <- stringr::str_to_lower(xvar)
}else{
xvar <- stringr::str_to_lower(xvar)
}
object <- lapply(object,
function(x){
colnames(x) <- stringr::str_to_lower(colnames(x));
return(x)
}
)
merged.data <- merge(object$predicted, object$par, by="row")
Xdata <- merged.data[,xvar]
}
if(ndata > 1 & ntheta <= 1){
if(missing(xvar)){
search <- lapply(object$model, unique)
search$Row <- NULL
xvar <- names(which(sapply(search, function(x){length(x)>1})))
if(length(xvar)>1){
stop("More than one candidate for xvar found, please specify it directly")
}
xvar <- stringr::str_to_lower(xvar)
}else{
xvar <- stringr::str_to_lower(xvar)
}
object <- lapply(object,
function(x){
colnames(x) <- stringr::str_to_lower(colnames(x));
return(x)
}
)
merged.data <- merge(object$predicted, object$model, by="row")
Xdata <- merged.data[,xvar]
}
Ydata <- merged.data[,prob]
if(missing(ylab)){ylab=prob}
if(missing(xlab)){xlab=xvar}
return(
plot(Ydata~Xdata, col=col, main=main, xlab=xlab, ylab=ylab, pch=pch, ...)
)
}
|
bandit4arm_lapse_decay <- hBayesDM_model(
task_name = "bandit4arm",
model_name = "lapse_decay",
model_type = "",
data_columns = c("subjID", "choice", "gain", "loss"),
parameters = list(
"Arew" = c(0, 0.1, 1),
"Apun" = c(0, 0.1, 1),
"R" = c(0, 1, 30),
"P" = c(0, 1, 30),
"xi" = c(0, 0.1, 1),
"d" = c(0, 0.1, 1)
),
regressors = NULL,
postpreds = c("y_pred"),
preprocess_func = bandit4arm_preprocess_func)
|
context('test changepoint')
test_that('fortify.cpt works for AirPassengers', {
skip_on_cran()
skip_on_travis()
skip_if_not_installed("changepoint")
library(changepoint)
result <- changepoint::cpt.mean(AirPassengers)
p <- ggplot2::autoplot(result)
expect_true(is(p, 'ggplot'))
fortified <- ggplot2::fortify(result)
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Data', 'mean'))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
filtered <- dplyr::filter(fortified, !is.na(mean))
expect_equal(filtered$Index[1], as.Date('1955-05-01'))
expect_equal(filtered$Index[nrow(filtered)], as.Date('1960-12-01'))
fortified <- ggplot2::fortify(changepoint::cpt.var(AirPassengers))
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Data', 'mean', 'variance'))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
filtered <- dplyr::filter(fortified, !is.na(variance))
expect_equal(filtered$Index[1], as.Date('1960-12-01'))
expect_equal(filtered$Index[nrow(filtered)], as.Date('1960-12-01'))
fortified <- ggplot2::fortify(changepoint::cpt.meanvar(AirPassengers))
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Data', 'mean', 'variance'))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
filtered <- dplyr::filter(fortified, !is.na(mean) | !is.na(variance))
expect_equal(filtered$Index[1], as.Date('1955-05-01'))
expect_equal(filtered$Index[nrow(filtered)], as.Date('1960-12-01'))
})
test_that('fortify.breakpoints works for Nile', {
skip_on_cran()
skip_on_travis()
skip_if_not_installed("strucchange")
library(strucchange)
bp.nile <- strucchange::breakpoints(Nile ~ 1)
p <- ggplot2::autoplot(breakpoints(bp.nile, breaks = 2), data = Nile)
expect_true(is(p, 'ggplot'))
fortified <- ggplot2::fortify(bp.nile, is.date = TRUE)
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Data', 'Breaks'))
expect_equal(fortified$Index[1], as.Date('1871-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1970-01-01'))
filtered <- dplyr::filter(fortified, !is.na(Breaks))
expect_equal(filtered$Index[1], as.Date('1898-01-01'))
bp.pts <- strucchange::breakpoints(bp.nile, breaks = 2)
fortified <- ggplot2::fortify(bp.pts, is.date = TRUE)
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Breaks'))
expect_equal(fortified$Index[1], as.Date('1871-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1970-01-01'))
filtered <- dplyr::filter(fortified, !is.na(Breaks))
expect_equal(filtered$Index[1], as.Date('1898-01-01'))
expect_equal(filtered$Index[nrow(filtered)], as.Date('1953-01-01'))
fortified <- ggplot2::fortify(bp.pts, data = Nile, is.date = TRUE)
expect_equal(is.data.frame(fortified), TRUE)
expect_equal(names(fortified), c('Index', 'Data', 'Breaks'))
expect_equal(fortified$Index[1], as.Date('1871-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1970-01-01'))
})
|
have_rqdatatable <- FALSE
if (requireNamespace("rqdatatable", quietly = TRUE)) {
library("rqdatatable")
have_rqdatatable <- TRUE
}
have_db <- FALSE
if (requireNamespace("RSQLite", quietly = TRUE) &&
requireNamespace("DBI", quietly = TRUE)) {
have_db <- TRUE
}
library("rquery")
group_nm <- "am"
num_nm <- as.name("hp")
den_nm <- as.name("cyl")
derived_nm <- as.name(paste0(num_nm, "_per_", den_nm))
mean_nm <- as.name(paste0("mean_", derived_nm))
count_nm <- as.name("group_count")
mtcars %.>%
extend(.,
.(derived_nm) := .(num_nm)/.(den_nm)) %.>%
project(.,
.(mean_nm) := mean(.(derived_nm)),
.(count_nm) := length(.(derived_nm)),
groupby = group_nm) %.>%
orderby(.,
group_nm)
td <- mk_td("mtcars",
as.character(list(group_nm, num_nm, den_nm)))
count <- function(v) { length(v) }
ops <- td %.>%
extend(.,
.(derived_nm) := .(num_nm)/.(den_nm)) %.>%
project(.,
.(mean_nm) := mean(.(derived_nm)),
.(count_nm) := count(.(derived_nm)),
groupby = group_nm) %.>%
orderby(.,
group_nm)
mtcars %.>% ops
cat(format(ops))
raw_connection <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
dbopts <- rq_connection_tests(raw_connection)
db <- rquery_db_info(connection = raw_connection,
is_dbi = TRUE,
connection_options = dbopts)
print(db)
tr <- rquery::rq_copy_to(db, "mtcars", mtcars,
temporary = TRUE,
overwrite = TRUE)
print(tr)
res <- materialize(db, ops)
DBI::dbReadTable(raw_connection, res$table_name)
execute(db, ops)
sql <- to_sql(ops, db)
cat(sql)
DBI::dbDisconnect(raw_connection)
rm(list = c("raw_connection", "db"))
|
library(DiffusionRjgqd)
JGQD.remove()
a00 = function(t){0.5*5}
a10 = function(t){-0.5}
a01 = function(t){-0.1}
c10 = function(t){0.4^2}
b00 = function(t){0.4*6}
b01 = function(t){-0.4}
b10 = function(t){-0.1}
f01 = function(t){0.3^2}
Lam00= function(t){1}
Jmu1=function(t){0.75*(1+sin(2*pi*t))}
Jmu2=function(t){0.75*(1+sin(2*pi*t))}
Jsig11=function(t){0.75^2*(1+0.8*sin(2*pi*t))^2}
Jsig22=function(t){0.75^2*(1+0.8*sin(2*pi*t))^2}
xx=seq(3,11,1/10)
yy=seq(3,11,1/10)
res= BiJGQD.density(7,7,xx,yy,0,1,1/100,Dtype='Saddlepoint')
mux = function(x,y,t){a00(t)+a10(t)*x+a01(t)*y}
sigmax = function(x,y,t){sqrt(c10(t)*x)}
muy = function(x,y,t){b00(t)+b10(t)*x+b01(t)*y}
sigmay = function(x,y,t){sqrt(f01(t)*y)}
lambda1 = function(x,y,t){Lam00(t)}
lambda2 = function(x,y,t){rep(0,length(x))}
j11 = function(x,y,z){z}
j12 = function(x,y,z){z}
j21 = function(x,y,z){z}
j22 = function(x,y,z){z}
simulate=function(x0=7,y0=7,N=10000,TT=5,delta=1/1000,pts,brks=30,plt=FALSE)
{
library(colorspace)
colpal=function(n){rev(sequential_hcl(n,power=0.8,l=c(40,100)))}
d=0
tt=seq(0,TT,delta)
X=rep(x0,N)
Y=rep(y0,N)
x.traj = rep(x0,length(tt))
y.traj = rep(y0,length(tt))
x.jump = rep(0,length(tt))
y.jump = rep(0,length(tt))
evts = rep(0,N)
for(i in 2:length(tt))
{
X=X+mux(X,Y,d)*delta+sigmax(X,Y,d)*rnorm(N,sd=sqrt(delta))
Y=Y+muy(X,Y,d)*delta+sigmay(X,Y,d)*rnorm(N,sd=sqrt(delta))
events1 = (lambda1(X,Y,d)*delta>runif(N))
if(any(events1))
{
wh=which(events1)
evts[wh]=evts[wh]+1
X[wh]=X[wh]+j11(X[wh],Y[wh],rnorm(length(wh),Jmu1(d),sqrt(Jsig11(d))))
Y[wh]=Y[wh]+j21(X[wh],Y[wh],rnorm(length(wh),Jmu2(d),sqrt(Jsig22(d))))
}
events2 = (lambda2(X,Y,d)*delta>runif(N))
d=d+delta
if(sum(round(pts,3)==round(d,3))!=0)
{
if(plt)
{
expr1 = expression(X_t)
expr2 = expression(Y_t)
color.palette=colorRampPalette(c('green','blue','red'))
filled.contour(res$Xt,res$Yt,res$density[,,i],
main=paste0('Transition Density \n (t = ',round(d,2),')'),
color.palette=colpal,
nlevels=41,xlab=expression(X[t]),ylab=expression(Y[t]),plot.axes=
{
points(Y~X,pch=c(20,3)[(evts>0)+1],col=c('black','red')[(evts>0)+1],cex=c(0.9,0.6)[(evts>0)+1])
if(any(events2))
{
wh=which(events2)
segments(xpreee[wh],ypreee[wh],X[wh],Y[wh],col='gray')
}
axis(1);axis(2);
legend('topright',col=c('black','red'),pch=c(20,3),
legend=c('Simulated Trajectories','Jumped'))
yy=contourLines(res$Xt,res$Yt,res$density[,,i],levels=seq(0.01,0.1,length=10))
if(length(yy)>0)
{
for(j in 1:length(yy))
{
lines(yy[[j]])
}
}
})
}
}
}
}
sim=simulate(7,7,N=200,TT=0.75,delta=1/100,plt=TRUE,pts=c(0.13,0.28,0.38,0.51,0.63,0.75))
|
.subsetCorpus <- function(save) {
if(save)
doItAndPrint("origCorpus <- corpus")
doItAndPrint("corpus <- corpus[keep]")
if(exists("dtm")) {
processing <- meta(corpus, type="corpus", tag="processing")
lang <- meta(corpus, type="corpus", tag="language")
if(save)
doItAndPrint("origDtm <- dtm")
doItAndPrint('dtmAttr <- attributes(dtm)')
doItAndPrint('origDictionary <- attr(dtm, "dictionary")')
doItAndPrint("dtm <- dtm[keep,]")
.buildDictionary(FALSE, processing["customStemming"], lang)
if(processing["stemming"] || processing["customStemming"])
doItAndPrint('dictionary[[2]] <- origDictionary[rownames(dictionary), 2]')
.prepareDtm(processing["stopwords"], processing["stemming"] || processing["customStemming"], FALSE, lang)
if(processing["customStemming"])
doItAndPrint('dtm <- dtm[, Terms(dtm) != ""]')
doItAndPrint('attr(dtm, "language") <- dtmAttr$lang')
doItAndPrint('attr(dtm, "processing") <- dtmAttr$processing')
doItAndPrint("rm(dtmAttr, origDictionary)")
}
if(exists("wordsDtm")) {
if(save)
doItAndPrint("origWordsDtm <- wordsDtm")
doItAndPrint("wordsDtm <- wordsDtm[keep,]")
doItAndPrint("wordsDtm <- wordsDtm[,col_sums(wordsDtm) > 0]")
}
doItAndPrint("corpusVars <- corpusVars[keep,, drop=FALSE]")
objects <- c("keep", "voc", "termFreqs", "corpusClust", "corpusSubClust", "corpusCa", "plottingCa")
doItAndPrint(paste('rm(list=c("', paste(objects[sapply(objects, exists)], collapse='", "'), '"))', sep=""))
gc()
doItAndPrint("corpus")
doItAndPrint("dtm")
}
subsetCorpusByVarDlg <- function() {
nVars <- ncol(meta(corpus)[colnames(meta(corpus)) != "MetaID"])
if(nVars == 0) {
.Message(message=.gettext("No corpus variables have been set. Use Text mining->Manage corpus->Set corpus variables to add them."),
type="error")
return()
}
initializeDialog(title=.gettext("Subset Corpus by Variable"))
vars <- colnames(meta(corpus))
varsFrame <- tkframe(top)
varsBox <- tklistbox(varsFrame, height=getRcmdr("variable.list.height"),
selectmode="single", export=FALSE)
varsScrollbar <- ttkscrollbar(varsFrame, command=function(...) tkyview(varsBox, ...))
tkconfigure(varsBox, yscrollcommand=function(...) tkset(varsScrollbar, ...))
for(var in vars) tkinsert(varsBox, "end", var)
tkselection.set(varsBox, 0)
levelsFrame <- tkframe(top)
levelsBox <- tklistbox(levelsFrame, height=getRcmdr("variable.list.height"),
selectmode=getRcmdr("multiple.select.mode"), export=FALSE)
levelsScrollbar <- ttkscrollbar(levelsFrame, command=function(...) tkyview(levelsBox, ...))
tkconfigure(levelsBox, yscrollcommand=function(...) tkset(levelsScrollbar, ...))
for(level in unique(meta(corpus, vars[1])[[1]])) tkinsert(levelsBox, "end", level)
tkselection.set(levelsBox, 0)
onSelect <- function() {
var <- vars[as.numeric(tkcurselection(varsBox))+1]
tkdelete(levelsBox, "0", "end")
levs <- unique(meta(corpus, var)[[1]])
for(level in levs) tkinsert(levelsBox, "end", level)
}
tkbind(varsBox, "<<ListboxSelect>>", onSelect)
tclSave <- tclVar("1")
checkSave <- tkcheckbutton(top, text=.gettext("Save original corpus to restore it later"),
variable=tclSave)
onOK <- function() {
var <- vars[as.numeric(tkcurselection(varsBox))+1]
levs <- unique(meta(corpus, var)[[1]])[as.numeric(tkcurselection(levelsBox))+1]
save <- tclvalue(tclSave) == "1"
closeDialog()
setBusyCursor()
on.exit(setIdleCursor())
doItAndPrint(sprintf('keep <- meta(corpus, "%s")[[1]] %%in%% c("%s")',
var, paste(levs, collapse='", "')))
.subsetCorpus(save)
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="subsetCorpusByVarDlg")
tkgrid(labelRcmdr(top, text=.gettext("Select a variable and one or more levels to retain:")),
columnspan=2, sticky="w", pady=6)
tkgrid(.titleLabel(varsFrame, text=.gettext("Variable:")),
sticky="w")
tkgrid(varsBox, varsScrollbar, sticky="ewns", pady=6)
tkgrid(.titleLabel(levelsFrame, text=.gettext("Levels:")),
sticky="w")
tkgrid(levelsBox, levelsScrollbar, sticky="ewns", pady=6)
tkgrid(varsFrame, levelsFrame, sticky="wns", pady=6)
tkgrid(checkSave, sticky="w", pady=6)
tkgrid(buttonsFrame, columnspan=2, sticky="ew", pady=6)
dialogSuffix(focus=varsBox)
}
subsetCorpusByTermsDlg <- function() {
initializeDialog(title=.gettext("Subset Corpus by Terms"))
tclKeep <- tclVar("")
entryKeep <- ttkentry(top, width="40", textvariable=tclKeep)
tclKeepFreq <- tclVar(1)
spinKeep <- tkwidget(top, type="spinbox", from=1, to=.Machine$integer.max,
inc=1, textvariable=tclKeepFreq,
validate="all", validatecommand=.validate.uint)
tclExclude <- tclVar("")
entryExclude <- ttkentry(top, width="40", textvariable=tclExclude)
tclExcludeFreq <- tclVar(1)
spinExclude <- tkwidget(top, type="spinbox", from=1, to=.Machine$integer.max,
inc=1, textvariable=tclExcludeFreq,
validate="all", validatecommand=.validate.uint)
tclSave <- tclVar("1")
checkSave <- tkcheckbutton(top, text=.gettext("Save original corpus to restore it later"),
variable=tclSave)
onOK <- function() {
keepList <- strsplit(tclvalue(tclKeep), " ")[[1]]
excludeList <- strsplit(tclvalue(tclExclude), " ")[[1]]
keepFreq <- as.numeric(tclvalue(tclKeepFreq))
excludeFreq <- as.numeric(tclvalue(tclExcludeFreq))
save <- tclvalue(tclSave) == "1"
if(length(keepList) == 0 && length(excludeList) == 0) {
.Message(.gettext("Please enter at least one term."), "error", parent=top)
return()
}
else if(!all(c(keepList, excludeList) %in% colnames(dtm))) {
wrongTerms <- c(keepList, excludeList)[!c(keepList, excludeList) %in% colnames(dtm)]
.Message(sprintf(.ngettext(length(wrongTerms),
"Term \'%s\' does not exist in the corpus.",
"Terms \'%s\' do not exist in the corpus."),
paste(wrongTerms, collapse=.gettext("\', \'"))),
"error", parent=top)
return()
}
else if((length(keepList) > 0 && length(excludeList) > 0 &&
!any(row_sums(dtm[, keepList] >= keepFreq) > 0 &
row_sums(dtm[, excludeList] >= excludeFreq) == 0)) ||
(length(keepList) > 0 && length(excludeList) == 0 &&
!any(row_sums(dtm[, keepList] >= keepFreq) > 0)) ||
(length(keepList) == 0 && length(excludeList) > 0 &&
!any(row_sums(dtm[, excludeList] >= excludeFreq) == 0))) {
.Message(.gettext("Specified conditions would exclude all documents from the corpus."),
"error", parent=top)
return()
}
closeDialog()
if(length(keepList) > 0 && length(excludeList) > 0)
doItAndPrint(sprintf('keep <- row_sums(dtm[, c("%s")] >= %i) > 0 & row_sums(dtm[, c("%s")] >= %i) == 0',
paste(keepList, collapse='", "'), keepFreq,
paste(excludeList, collapse='", "'), excludeFreq))
else if(length(keepList) > 0)
doItAndPrint(sprintf('keep <- row_sums(dtm[, c("%s")] >= %i) > 0',
paste(keepList, collapse='", "'), keepFreq))
else
doItAndPrint(sprintf('keep <- row_sums(dtm[, c("%s")] >= %i) == 0',
paste(excludeList, collapse='", "'), excludeFreq))
.subsetCorpus(save)
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="subsetCorpusByTermsDlg")
tkgrid(labelRcmdr(top, text=.gettext("Keep documents containing one of these terms (space-separated):")),
sticky="w", columnspan=4)
tkgrid(entryKeep,
labelRcmdr(top, text=.gettext("at least")),
spinKeep,
labelRcmdr(top, text=.gettext("time(s)")),
sticky="w", pady=c(0, 6))
tkgrid(labelRcmdr(top, text=.gettext("Exclude documents containing one of these terms (space-separated):")),
sticky="w", pady=c(6, 0), columnspan=4)
tkgrid(entryExclude,
labelRcmdr(top, text=.gettext("at least")),
spinExclude,
labelRcmdr(top, text=.gettext("time(s)")),
sticky="w", pady=c(0, 6))
tkgrid(labelRcmdr(top, text=.gettext("(Only documents matching both conditions will be retained in the new corpus.)")),
sticky="w", pady=6, columnspan=4)
tkgrid(checkSave, sticky="w", pady=c(12, 6), columnspan=4)
tkgrid(buttonsFrame, sticky="ew", pady=6, columnspan=4)
dialogSuffix(focus=entryKeep)
}
restoreCorpus <- function() {
if(!exists("origCorpus"))
.Message(message=.gettext("No saved corpus to restore was found."), type="error")
doItAndPrint("corpus <- origCorpus")
if(exists("origDtm"))
doItAndPrint("dtm <- origDtm")
if(exists("origWordsDtm"))
doItAndPrint("wordsDtm <- origWordsDtm")
objects <- c("keep", "voc", "termFreqs", "absTermFreqs", "varTermFreqs",
"corpusClust", "corpusSubClust", "corpusCa", "plottingCa",
"origCorpus", "origDtm", "origWordsDtm")
doItAndPrint(paste("rm(", paste(objects[sapply(objects, exists)], collapse=", "), ")", sep=""))
doItAndPrint("corpus")
doItAndPrint("dtm")
gc()
}
|
CatDynPar <-
function(x,method,partial=TRUE)
{
if(class(x) != "catdyn")
{stop("'x' must be an object of class 'catdyn' (created by function CatDynFit)")}
sdistr.set <- c("poisson","apnormal","aplnormal")
if(x$Data$Properties$Units["Time Step"]=="month")
{
if(length(x$Data$Properties$Fleets$Fleet)==1)
{
month.F1 <- x$Model[[method]]$Dates[2:(x$Model[[method]]$Type+1)]
years.F1 <- as.numeric(format(as.Date(x$Data$Properties$Dates["StartDate"]),"%Y"))+floor(month.F1/12)
month.F1 <- as.integer((month.F1/12-floor(month.F1/12))*12)
if(x$Model[[method]]$Distr%in%sdistr.set)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",paste(years.F1,month.F1,sep="-"),"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(!x$Model[[method]]$Distr%in%sdistr.set)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",paste(years.F1,month.F1,sep="-"),"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
if(length(x$Data$Properties$Fleets$Fleet)==2)
{
month.F1 <- x$Model[[method]]$Dates[2:(x$Model[[method]]$Type[1]+1)]
month.F2 <- x$Model[[method]]$Dates[(x$Model[[method]]$Type[1]+2):(x$Model[[method]]$Type[1]+1+x$Model[[method]]$Type[2])]
years.F1 <- as.numeric(format(as.Date(x$Data$Properties$Dates["StartDate"]),"%Y"))+floor(month.F1/12)
years.F2 <- as.numeric(format(as.Date(x$Data$Properties$Dates["StartDate"]),"%Y"))+floor(month.F2/12)
month.F1 <- as.integer((month.F1/12-floor(month.F1/12))*12)
month.F2 <- as.integer((month.F2/12-floor(month.F2/12))*12)
if(any(month.F1==0)){month.F1[which(month.F1==0)] <- 12}
if(any(month.F2==0)){month.F2[which(month.F2==0)] <- 12}
if(sum(x$Model[[method]]$Distr%in%sdistr.set)==2)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Timing.F1=c("","",paste(years.F1,month.F1,sep="-"),"","",""),
Estimates.F1=unlist(x$Model[[method]]$bt.par[1:(2+length(years.F1)+3)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[1:(2+length(years.F1)+3)])/
unlist(x$Model[[method]]$bt.par[1:(2+length(years.F1)+3)]),1),
Timing.F2=c("","",paste(years.F2,month.F2,sep="-"),"","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):length(x$Model[[method]]$bt.par))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+length(years.F2)+4):(length(x$Model[[method]]$bt.stdev)))])/
unlist(x$Model[[method]]$bt.par[(c(1,2,(2+length(years.F2)+4):length(x$Model[[method]]$bt.par)))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==-1)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",paste(years.F1,month.F1,sep="-"),"","","",""),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3))]),NA),
CVpCent.F1=round(c(100*unlist(x$Model[[method]]$bt.stdev[c(1:(2+length(years.F1)+3))])/
unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3))]),NA),1),
Timing.F2=c("","",paste(years.F2,month.F2,sep="-"),"","","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):length(x$Model[[method]]$bt.par))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+length(years.F2)+3+1):length(x$Model[[method]]$bt.stdev))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):length(x$Model[[method]]$bt.par))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==1)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",paste(years.F1,month.F1,sep="-"),"","","",""),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.par)))]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.stdev)))])/
unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.par)))]),1),
Timing.F2=c("","",paste(years.F2,month.F2,sep="-"),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.par)-1))]),NA),
CVpCent.F2=c(round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.stdev)-1))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.par)-1))]),1),NA),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(sum(x$Model[[method]]$Distr%in%sdistr.set)==0)
{
partable <- data.frame(Parameter=c("M.1/month",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".",years.F1,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",paste(years.F1,month.F1,sep="-"),"","","",""),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.par))-1)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.stdev))-1)])/
unlist(x$Model[[method]]$bt.par[c(1:(2+length(years.F1)+3),length(unlist(x$Model[[method]]$bt.par))-1)]),1),
Timing.F2=c("","",paste(years.F2,month.F2,sep="-"),"","","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.par)-2),(length(x$Model[[method]]$bt.par)))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.stdev)-2),(length(x$Model[[method]]$bt.stdev)))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(2+length(years.F2)+3+1):(length(x$Model[[method]]$bt.par)-2),(length(x$Model[[method]]$bt.par)))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
if(x$Data$Properties$Units["Time Step"]=="day" | x$Data$Properties$Units["Time Step"]=="week")
{
if(length(x$Data$Properties$Fleets$Fleet)==1)
{
if(x$Model[[method]]$Type==0)
{
if(x$Model[[method]]$Distr%in%sdistr.set)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
if(!x$Model[[method]]$Distr%in%sdistr.set)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
}
if(x$Model[[method]]$Type!=0)
{
waves <- abs(x$Model[[method]]$Type)
if(x$Model[[method]]$Distr %in% sdistr.set)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
finalweek.year1 <- as.numeric(format(as.Date(paste(year1,"-12-31",sep="")), "%W"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(partial & x$Model[[method]]$Type < 0)
{
dates.ranges <- vector("character",2*waves)
if(year2 > year1)
{
weeks <- x$Model[[method]]$Dates[2:(2*waves+1)] - finalweek.year1
for(w in 1:2*waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year2, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
if(year2 == year1)
{
weeks <- x$Model[[method]]$Dates[2:(2*waves+1)]
for(w in 1:(2*waves))
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Recruitment.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("Spawning.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",dates.ranges,"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(partial & x$Model[[method]]$Type > 0)
{
dates.ranges <- vector("character",waves)
if(year2 > year1)
{
weeks <- x$Model[[method]]$Dates[2:(2*waves+1)] - finalweek.year1
for(w in 1:waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year2, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
if(year2 == year1)
{
weeks <- x$Model[[method]]$Dates[2:(waves+1)]
for(w in 1:(waves))
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Recruitment.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",dates.ranges,"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(!partial)
{
weeks <- x$Model[[method]]$Dates[2:(waves+1)]
dates.ranges <- vector("character",waves)
for(w in 1:waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",dates.ranges,"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
if(partial & x$Model[[method]]$Type < 0)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("Spawning.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+2)]),
"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(partial & x$Model[[method]]$Type > 0)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+1)]),
"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(!partial)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta"),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+1)]),"","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
}
if(!x$Model[[method]]$Distr %in% sdistr.set)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
finalweek.year1 <- as.numeric(format(as.Date(paste(year1,"-12-31",sep="")), "%W"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(partial & x$Model[[method]]$Type < 0)
{
dates.ranges <- vector("character",2*waves)
if(year2 > year1)
{
weeks <- x$Model[[method]]$Dates[2:(2*waves+1)] - finalweek.year1
for(w in 1:2*waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year2, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
if(year2 == year1)
{
weeks <- x$Model[[method]]$Dates[2:(2*waves+1)]
for(w in 1:2*waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Recruitment.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("Spawning.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",dates.ranges,"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(partial & x$Model[[method]]$Type > 0)
{
dates.ranges <- vector("character",waves)
if(year2 > year1)
{
weeks <- x$Model[[method]]$Dates[2:(waves+1)] - finalweek.year1
for(w in 1:waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year2, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
if(year2 == year1)
{
weeks <- x$Model[[method]]$Dates[2:(waves+1)]
for(w in 1:waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Recruitment.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",dates.ranges,"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(!partial)
{
weeks <- x$Model[[method]]$Dates[2:(waves+1)]
dates.ranges <- vector("character",waves)
for(w in 1:waves)
{
dates.ranges[w] <- paste(range(days[sprintf("%d %02d", year1, weeks[w]) == format(days, "%Y %U")]),collapse=' ')
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",dates.ranges,"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
if(partial & x$Model[[method]]$Type < 0)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("Spawning.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+2)]),
"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(partial & x$Model[[method]]$Type > 0)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+1)]),
"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
if(!partial)
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units,sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves+1)]),"","","",""),
Estimates=unlist(x$Model[[method]]$bt.par),
CVpCent=round(100*unlist(x$Model[[method]]$bt.stdev)/unlist(x$Model[[method]]$bt.par),1),row.names=NULL)
}
}
}
}
}
if(length(x$Data$Properties$Fleets$Fleet)==2)
{
if(sum(x$Model[[method]]$Type)==0)
{
if(sum(x$Model[[method]]$Distr%in%sdistr.set)==2)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Estimates.F1=unlist(x$Model[[method]]$bt.par[1:5]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[1:5])/
unlist(x$Model[[method]]$bt.par[1:5]),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Estimates.F1=unlist(x$Model[[method]]$bt.par[1:5]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[1:5])/
unlist(x$Model[[method]]$bt.par[1:5]),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==-1)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[1:5]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[1:5]),NA)/
c(unlist(x$Model[[method]]$bt.par[1:5]),NA),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:9)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:9)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:9)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[1:5]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[1:5]),NA)/
c(unlist(x$Model[[method]]$bt.par[1:5]),NA),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:9)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:9)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:9)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==1)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:5,9)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:5,9)])/
unlist(x$Model[[method]]$bt.par[c(1:5,9)]),1),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8)]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),NA),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:5,9)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:5,9)])/
unlist(x$Model[[method]]$bt.par[c(1:5,9)]),1),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8)]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:8)]),NA),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(sum(x$Model[[method]]$Distr%in%sdistr.set)==0)
{
if(x$Data$Properties$Units["Time Step"]=="week")
{
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:5,9)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:5,9)])/
unlist(x$Model[[method]]$bt.par[c(1:5,9)]),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:8,10)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8,10)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:8,10)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=unlist(x$Model[[method]]$bt.par[c(1:5,9)]),
CVpCent.F1=round(100*unlist(x$Model[[method]]$bt.stdev[c(1:5,9)])/
unlist(x$Model[[method]]$bt.par[c(1:5,9)]),1),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:8,10)]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:8,10)])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:8,10)]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:5] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
if(sum(x$Model[[method]]$Type)!=0)
{
year <- as.numeric(substring(x$Data$Properties$Dates[["StartDate"]],1,4))
waves.F1 <- x$Model[[method]]$Type[1]
waves.F2 <- x$Model[[method]]$Type[2]
if(sum(x$Model[[method]]$Distr%in%sdistr.set)==2)
{
if(waves.F1==0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks2 <- x$Model[[method]]$Dates[2:(waves.F2+1)]
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5])),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]))/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5])),1),
Timing.F2=c("","",dates.ranges.F2,"","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5])),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]))/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5])),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F2+1)]),"","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))])/
unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(waves.F1!=0 & waves.F2!=0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks1 <- x$Model[[method]]$Dates[2:(waves.F1+1)]
weeks2 <- x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+waves.F2+1)]
dates.ranges.F1 <- vector("character",waves.F1)
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F1)
{
if(weeks1[w] <= 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year1, weeks1[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks1[w] > 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year2, weeks1[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Timing.F1=c("","",dates.ranges.F1,rep("",3+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)])),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)])),1),
Timing.F2=c("","",dates.ranges.F2,"","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+3))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+3))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+3))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta"),
Timing.F1=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F1+1)]),rep("",3+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)])),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)])),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+1+waves.F2)]),"","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(waves.F1+6):(waves.F1+5+waves.F2+3))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(waves.F1+6):(waves.F1+5+waves.F2+3))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==-1)
{
if(waves.F1==0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks2 <- x$Model[[method]]$Dates[2:(waves.F2+1)]
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),NA),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),NA),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F2+1)]),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(waves.F1!=0 & waves.F2!=0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks1 <- x$Model[[method]]$Dates[2:(waves.F1+1)]
weeks2 <- x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+waves.F2+1)]
dates.ranges.F1 <- vector("character",waves.F1)
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F1)
{
if(weeks1[w] <= 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year1, weeks1[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks1[w] > 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year2, weeks1[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",dates.ranges.F1,rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),NA),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+4))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+4))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+4):(2+waves.F1+3+waves.F2+4))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F1+1)]),rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),NA),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),NA),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+1+waves.F2)]),"","","",""),
Estimates.F2=unlist(x$Model[[method]]$bt.par[c(1,2,(waves.F1+6):((waves.F1+6+waves.F2+3)))]),
CVpCent.F2=round(100*unlist(x$Model[[method]]$bt.stdev[c(1,2,(waves.F1+6):((waves.F1+6+waves.F2+3)))])/
unlist(x$Model[[method]]$bt.par[c(1,2,(waves.F1+6):((waves.F1+6+waves.F2+3)))]),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
if(diff(x$Model[[method]]$Distr%in%sdistr.set)==1)
{
if(waves.F1==0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks2 <- x$Model[[method]]$Dates[2:(waves.F2+1)]
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),1)),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+length(waves.F2)+3))]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),NA),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),1)),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F2+1)]),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),NA),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
if(waves.F1!=0 & waves.F2!=0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks1 <- x$Model[[method]]$Dates[2:(waves.F1+1)]
weeks2 <- x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+waves.F2+1)]
dates.ranges.F1 <- vector("character",waves.F1)
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F1)
{
if(weeks1[w] <= 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year1, weeks1[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks1[w] > 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year2, weeks1[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",dates.ranges.F1,rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),1)),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F1+1)]),rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),1)),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+1+waves.F2)]),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA)/
c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),NA),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
else if(sum(x$Model[[method]]$Distr%in%sdistr.set)==0)
{
if(waves.F1==0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks2 <- x$Model[[method]]$Dates[2:(waves.F2+1)]
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),tail(unlist(x$Model[[method]]$bt.stdev),2)[1])/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2)]),rep(0,waves.F2),unlist(x$Model[[method]]$bt.stdev[3:5]),tail(unlist(x$Model[[method]]$bt.stdev),2)[1])/
c(unlist(x$Model[[method]]$bt.par[c(1,2)]),rep(1,waves.F2),unlist(x$Model[[method]]$bt.par[3:5]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F2+1)]),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,6:(5+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:3] <- paste(c("Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[4:6] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
else if(waves.F1!=0 & waves.F2!=0)
{
year1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["StartDate"]]), "%Y"))
year2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[["EndDate"]]), "%Y"))
days <- as.Date(paste(year1, 1, 1, sep = "-"))+0:365*(year2-year1+1)
if(x$Data$Properties$Units["Time Step"]=="week")
{
weeks1 <- x$Model[[method]]$Dates[2:(waves.F1+1)]
weeks2 <- x$Model[[method]]$Dates[2:(waves.F2+1)]
dates.ranges.F1 <- vector("character",waves.F1)
dates.ranges.F2 <- vector("character",waves.F2)
for(w in 1:waves.F1)
{
if(weeks1[w] <= 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year1, weeks1[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks1[w] > 53)
{
dates.ranges.F1[w] <- paste(range(days[sprintf("%d %02d", year2, weeks1[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
for(w in 1:waves.F2)
{
if(weeks2[w] <= 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year1, weeks2[w]) == format(days, "%Y %U")]),collapse=' ')
}
if(weeks2[w] > 53)
{
dates.ranges.F2[w] <- paste(range(days[sprintf("%d %02d", year2, weeks2[w]-53) == format(days, "%Y %U")]),collapse=' ')
}
}
partable <- data.frame(Parameter=c("M.1/week",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",dates.ranges.F1,rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.stdev),2)[1])/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),1),
Timing.F2=c("","",dates.ranges.F2,"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
if(x$Data$Properties$Units["Time Step"]=="day")
{
partable <- data.frame(Parameter=c("M.1/day",
paste("N0.",x$Data$Properties$Units["NumbersMultiplier"],sep=""),
paste("Rec.",x$Data$Properties$Units["NumbersMultiplier"],".Wave",1:waves.F2,sep=""),
paste("k.1/",x$Data$Properties$Fleets$Units[1],sep=""),
"alpha","beta",
paste("psi.",x$Data$Properties$Units["NumbersMultiplier"],".squared",sep="")),
Timing.F1=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[2:(waves.F1+1)]),rep("",4+waves.F2-waves.F1)),
Estimates.F1=c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),
CVpCent.F1=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.stdev[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.stdev),2)[1])/
c(unlist(x$Model[[method]]$bt.par[c(1,2,3:(waves.F1+2))]),rep(0,waves.F2-waves.F1),unlist(x$Model[[method]]$bt.par[(waves.F1+3):(waves.F1+5)]),tail(unlist(x$Model[[method]]$bt.par),2)[1]),1),
Timing.F2=c("","",as.character(as.Date(x$Data$Properties$Dates[["StartDate"]])+x$Model[[method]]$Dates[(waves.F1+2):(waves.F1+1+waves.F2)]),"","","",""),
Estimates.F2=c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),
CVpCent.F2=round(100*c(unlist(x$Model[[method]]$bt.stdev[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.stdev),1))/
c(unlist(x$Model[[method]]$bt.par[c(1,2,(2+waves.F1+3+1):(2+waves.F1+3+waves.F2+3))]),tail(unlist(x$Model[[method]]$bt.par),1)),1),row.names=NULL)
names(partable)[2:4] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[1],sep="")
names(partable)[5:7] <- paste(c("Timing.","Estimates.","CVpCent."),x$Data$Properties$Fleets$Fleet[2],sep="")
}
}
}
}
}
}
return(partable)
}
|
NULL
locpolAND_x0<-function(x,y,p1=1,p2=1,h, alpha=0.5,x0,tol=1e-08)
{
n<-length(y)
x<-as.matrix(x)
u1<-matrix(0,n,p1)
for (j in 1:p1)
{
for (i in 1:n)
{
u1[i,j]<-(x[i,1]-x0)^j
}
}
X1<-cbind(1, u1)
irls <-function(x,y,p,h, alpha,x0,maxit=25, tol=1e-08)
{
n<-length(y)
x<-as.matrix(x)
u<-matrix(0,n,p)
for (j in 1:p)
{
for (i in 1:n)
{
u[i,j]<-(x[i,1]-x0)^j
}
}
X<-cbind(1, u)
z <- x - x0
K_h <- dnorm(z/h)
W <-as.vector(array(NA,length(y)))
U <-as.vector(array(NA,length(y)))
b = rep(0,ncol(X))
for(j in 1:maxit)
{
mu = X %*% b
for (i in 1:length(y))
{
if(y[i]-mu[i]>0) W[i]=alpha^2*K_h[i] else W[i]=(1-alpha)^2*K_h[i]
}
b_old = b
b = solve(crossprod(X,W*X), crossprod(X,W*y), tol=2*.Machine$double.eps)
if(sqrt(crossprod(b-b_old)) < tol) break
}
fitted.values = X %*% b
for (i in 1:length(y))
{
if(y[i]-fitted.values[i]>0) W[i]=alpha^2*K_h[i]
else W[i]=(1-alpha)^2*K_h[i]
}
for (i in 1:length(y))
{
if(y[i]-fitted.values[i]>0) U[i]=alpha^2
else U[i]=(1-alpha)^2
}
SSE<-crossprod((y-fitted.values)^2,W)
phi2<-sum((y-fitted.values)^2*U*K_h)/(sum(K_h))
phi<-sqrt(phi2)
list(b1=b,phi=phi,phi2=phi2,iterations=j)
}
if (p2==0) {
b1=irls(x,y,p=p1,h,alpha,x0)$b
theta2<-(1/2)*log(irls(x,y,p=p1,h,alpha,x0)$phi2)
X2<-rep(1, length(x))
} else if(p2==1){
u2<-matrix(0,n,p2)
for (j in 1:p2)
{
for (i in 1:n)
{
u2[i,j]<-(x[i,1]-x0)^j
}
}
X2<-cbind(1, u2)
z <- x - x0
K_h <- dnorm(z/h)
b1=irls(x,y,p=p1,h,alpha,x0)$b
theta2_initial=c((1/2)*log(irls(x,y,p=p1,h,alpha,x0)$phi2),rep(0.005,p2))
for(j in 1:100) {
W<-ifelse(y>X1%*% as.vector(b1),alpha^2*K_h,(1-alpha)^2*K_h)
SqError<-((y-X1%*%as.vector(b1))^2*W)
fr<- function(theta2) {
theta20 <- theta2[1]
theta21 <- theta2[2]
sum(theta20+theta21*(x-x0)*K_h)+sum(SqError/(2*exp(2*theta20+2*theta21*(x-x0))))
}
gr<- function(theta2) {
theta20 <- theta2[1]
theta21 <- theta2[2]
c(-sum(SqError/exp(2*theta20+2*theta21*(x-x0)))+sum(K_h),sum(SqError*(x-x0)/(exp(2*theta20+2*theta21*(x-x0))))-sum((x-x0)*K_h))
}
theta2<-optim(theta2_initial, fr, gr, method = "BFGS")$par
W1<-ifelse(y>X1%*% as.vector(b1),alpha^2*K_h/(2*exp(2*X2%*% as.vector(theta2))),(1-alpha)^2*K_h/(2*exp(2*X2%*% as.vector(theta2))))
b1_old = b1
theta2_old = theta2
b1=solve(crossprod(X1,diag(c(W1))%*%X1), crossprod(X1,diag(c(W1))%*%y))
if(sqrt(crossprod(b1-b1_old)+crossprod(theta2-theta2_old)) < tol) break
}
} else {
u2<-matrix(0,n,p2)
for (j in 1:p2)
{
for (i in 1:n)
{
u2[i,j]<-(x[i,1]-x0)^j
}
}
X2<-cbind(1, u2)
theta1_initial=irls(x,y,p=p1,h,alpha,x0)$b
theta2_initial=c((1/2)*log(irls(x,y,p=p1,h,alpha,x0)$phi2),rep(0.005,p2))
fn<-function(theta){
mu<- as.matrix(X1)%*%as.vector(theta[1:(p1+1)])
phi<-exp(as.matrix(X2)%*%as.vector(theta[(p1+2):(p1+p2+2)]))
LL<-log(dAND(y,mu,phi,alpha))
return(-sum(LL[!is.infinite(LL)]))}
theta0<-c(theta1_initial,theta2_initial)
Est.par=optim(par=theta0,fn = fn)$par
b1<-Est.par[1:(p1+1)]
theta2<-Est.par[(p1+2):(p1+p2+2)]
}
a=2;
u_p1_2<-matrix(0,n,p1+a)
u_p2_2<-matrix(0,n,p2+a)
for (j in 1:(p1+a))
{
for (i in 1:n)
{
u_p1_2[i,j]<-(x[i]-x0)^j
}
}
for (j in 1:(p2+a))
{
for (i in 1:n)
{
u_p2_2[i,j]<-(x[i]-x0)^j
}
}
X1_p1_2<-cbind(1, u_p1_2)
X2_p2_2<-cbind(1, u_p2_2)
K_h <- dnorm((x-x0)/h)
theta1_p1_2=irls(x,y,p=(p1+a),h,alpha,x0)$b
theta2_p2_2=c((1/2)*log(irls(x,y,p=p1,h,alpha,x0)$phi2),rep(0.005,(p2+a)))
fn<-function(theta){
mu<- as.matrix(X1_p1_2)%*%as.vector(theta[1:(p1+3)])
phi<-exp(as.matrix(X2_p2_2)%*%as.vector(theta[(p1+4):(p1+p2+6)]))
LL<-log(dAND(y,mu,phi,alpha))
return(-sum(LL[!is.infinite(LL)]))}
theta0_2<-c(theta1_p1_2, theta2_p2_2)
Est.par_2=optim(par=theta0_2,fn = fn)$par
b1_p1_2<- Est.par_2[1:(p1+a+1)]
b2_p2_2<- Est.par_2[(p1+a+2):(p1+p2+2+2*a)]
e_1_hat<- X1_p1_2[,(p1+1):(p1+a)]%*% b1_p1_2[(p1+1):(p1+a)]
e_2_hat<- X2_p2_2[,(p2+1):(p2+a)]%*% b2_p2_2[(p2+1):(p2+a)]
yhat_p1_2<-as.matrix(X1)%*%as.vector(b1)+e_1_hat
yhat_p2_2<-as.matrix(X2)%*%as.vector(theta2)+e_2_hat
delta_1<-((y-yhat_p1_2)*ifelse((y-yhat_p1_2)>0,alpha^2,(1-alpha)^2))/exp(2*yhat_p2_2)
delta_2<--1+((y-yhat_p1_2)^2*ifelse((y-yhat_p1_2)>0,alpha^2,(1-alpha)^2))/exp(2*yhat_p2_2)
v11_x0<-sum(((y-X1_p1_2%*% b1_p1_2)*ifelse((y-X1_p1_2%*% b1_p1_2)>0,alpha^2,(1-alpha)^2))^2*K_h/exp(2*X2_p2_2%*% b2_p2_2))/sum(K_h)
v22_x0<-sum((-1+(y-X1_p1_2%*% b1_p1_2)^2*ifelse((y-X1_p1_2%*% b1_p1_2)>0,alpha^2,(1-alpha)^2)/exp(2*X2_p2_2%*% b2_p2_2))^2*K_h)/sum(K_h)
W<-diag(c(K_h))
S_11<-t(X1)%*%W%*%X1
S_22<-t(X2)%*%W%*%X2
W_K_2<-diag(c(K_h^2))
S_11_bar_n<-t(X1)%*%W_K_2%*%X1
S_22_bar_n<-t(X2)%*%W_K_2%*%X2
Bias_1_x0<-(solve(S_11))%*%(t(X1)%*%W%*%delta_1)/v11_x0
Bias_2_x0<-(solve(S_22))%*%(t(X2)%*%W%*%delta_2)/v22_x0
Var_1_x0<-solve(S_11)%*%S_11_bar_n%*%solve(S_11)/v11_x0
Var_2_x0<-solve(S_22)%*%S_22_bar_n%*%solve(S_22)/v22_x0
list(theta1_x0=b1,theta2_x0=theta2,Bias_1_x0=Bias_1_x0,Bias_2_x0=Bias_2_x0,Var_1_x0=Var_1_x0,Var_2_x0=Var_2_x0)
}
locpolAND<-function(x, y,p1,p2, h, alpha,m = 101)
{
xx <- seq(min(x)+.01*h, max(x)-.01*h, length = m)
theta_10<-matrix(NA,length(xx),1)
theta_20<-matrix(NA,length(xx),1)
Bias_10<-matrix(NA,length(xx),1)
Bias_20<-matrix(NA,length(xx),1)
Var_10<-matrix(NA,length(xx),1)
Var_20<-matrix(NA,length(xx),1)
for (ii in 1:length(xx)) {
fit_x0<-locpolAND_x0(x,y,p1,p2,h,alpha,x0=xx[ii])
theta_10[ii] <- fit_x0$ theta1_x0[[1]]
theta_20[ii] <-fit_x0$theta2_x0[[1]]
Bias_10[ii]<- fit_x0$Bias_1_x0[1,1]
Bias_20[ii]<- fit_x0$Bias_2_x0[1,1]
Var_10[ii]<- fit_x0$Var_1_x0[1,1]
Var_20[ii]<- fit_x0$Var_2_x0[1,1]
}
list(x0 = xx, theta_10= theta_10, theta_20= theta_20,Bias_10=Bias_10,Bias_20=Bias_20,Var_10=Var_10,Var_20=Var_20)
}
SemiQRegAND<-function(beta,x, y, p1=1,p2=1,h,alpha=NULL, m = 101){
if (is.null(alpha)){
alpha_fn<-function(x,y){
Newdata<-data.frame(x,y)
fit_mean<-locpol::locpol(y~x, data=Newdata,weig=rep(1,nrow(Newdata)) ,kernel=gaussK,deg=1,xeval=NULL,xevalLen=101)
MeanRegResidual<-fit_mean$residuals
MeanRegResidual<-sort(MeanRegResidual)
alpha<-mleAND(MeanRegResidual)$alpha
list(alpha=alpha)
}
alpha<-alpha_fn(x,y)$alpha}
fit_theta <-locpolAND(x, y,p1,p2, h, alpha,m)
mu=fit_theta$theta_10
phi=exp(fit_theta$theta_20)
quanty<-matrix(NA,length(mu),1);
for (i in 1:length(mu))
{
if (beta <alpha)
{
quanty[i]<-mu[i]-sqrt((2*phi[i]^2/(1-alpha)^2)*Igamma.inv(0.5, beta*sqrt(pi)/alpha,lower=FALSE));
}
else
{
quanty[i]<-mu[i]+sqrt((2*phi[i]^2/alpha^2)*Igamma.inv(0.5, sqrt(pi)*(beta-alpha)/(1-alpha)));
}
}
C_alpha_beta<-qAND(beta,mu=0,phi=1,alpha)
Bias_q_x0<-fit_theta$Bias_10+C_alpha_beta*fit_theta$Bias_20*exp(fit_theta$theta_20)
Var_q_x0<-fit_theta$Var_10+(C_alpha_beta)^2*fit_theta$Var_20*exp(2*fit_theta$theta_20)*exp(fit_theta$Bias_20)
list(x0=fit_theta$x0,fit_beta_AND=quanty,Bias_q_x0=Bias_q_x0,Var_q_x0=Var_q_x0,fit_alpha_AND=mu,alpha=alpha,beta=beta)
}
|
plotPriorPost <- function(fittedModel, probitInverse = "mean", M=2e5, ci=.95, nCPU=3,...){
mfrow <- par()$mfrow
S <- length(fittedModel$mptInfo$thetaUnique)
samples <- sampleHyperprior(fittedModel$mptInfo$hyperprior, M=M, S=S,
probitInverse=probitInverse, nCPU=nCPU)
for(s in 1:S){
label <- ifelse( S== 1, "", paste0("[",s,"]"))
mean.post <- unlist(fittedModel$runjags$mcmc[,paste0("mean", label)])
d.mean <- density(mean.post, from=0, to=1, na.rm = TRUE)
prior.mean <- density(samples$mean[,s], from=0,to=1, na.rm = TRUE)
ci.mean <- quantile(mean.post, c((1-ci)/2,1-(1-ci)/2))
if(fittedModel$mptInfo$model == "betaMPT"){
sd.post <- unlist(fittedModel$runjags$mcmc[,paste0("sd", label)])
ci.sd <- quantile(sd.post, c((1-ci)/2,1-(1-ci)/2))
d.sd <- density(sd.post, from=0, to=.5, na.rm = TRUE)
prior.sd <- density(samples$sd[,s], from=0, to=.5, na.rm = TRUE)
xlab.sd = "Group SD (probability)"
}else{
sig.post <- unlist(fittedModel$runjags$mcmc[,paste0("sigma", label)])
if(probitInverse == "mean_sd"){
mean_sd <- probitInverse(qnorm(mean.post), sig.post)
d.mean <- density(mean_sd[,"mean"], from=0, to=1, na.rm = TRUE)
d.sd <- density(mean_sd[,"sd"], from = 0, to = .5, na.rm = TRUE)
ci.sd <- quantile(mean_sd[,"sd"], c((1-ci)/2,1-(1-ci)/2))
ci.mean <- quantile(mean_sd[,"mean"], c((1-ci)/2,1-(1-ci)/2))
prior.sd <- density(samples$sd[,s], from=0, to=.5 ,na.rm = TRUE)
}else{
prior.sd <- density(samples$sd[,s], from = 0, na.rm = TRUE)
d.sd <- density(sig.post, from = 0, na.rm = TRUE)
ci.sd <- quantile(sig.post, c((1-ci)/2,1-(1-ci)/2))
if(probitInverse == "none"){
d.mean <- density(qnorm(mean.post), na.rm = TRUE)
ci.mean <- quantile(qnorm(mean.post), c((1-ci)/2,1-(1-ci)/2))
prior.mean <- density(samples$mean[,s], na.rm = TRUE)
}
}
xlab.sd = ifelse(probitInverse=="mean_sd",
"Group SD (probability scale)",
"Group SD (probit scale)")
}
par(mfrow=1:2)
tmp <- readline(prompt = "Press <Enter> to show the next plot.")
plot(d.mean, main=paste0( "Group mean of ", fittedModel$mptInfo$thetaUnique[s]),
xlab="Group mean", las=1, ...)
lines(prior.mean, col="blue", lty="dashed")
abline(v= ci.mean, col="red")
plot(d.sd, main=paste0("Group SD of ", fittedModel$mptInfo$thetaUnique[s]),
xlab=xlab.sd, las=1, ...)
lines(prior.sd, col="blue", lty="dashed")
abline(v=ci.sd,col="red")
}
if(fittedModel$mptInfo$model == "traitMPT" & S>1){
cnt <- 0
for(s1 in 1:(S-1)){
for(s2 in (s1+1):S){
d.cor <- density(unlist(fittedModel$runjags$mcmc[,paste0("rho[",s1,",",s2,"]")]),
from=-1, to=1)
prior.cor <- density(samples$rho[s1,s2,], from=-1, to=1)
if(cnt/2 == round(cnt/2))
tmp <- readline(prompt = "Press <Enter> to show the next plot.")
cnt <- cnt+1
plot(d.cor, main=paste0( "Correlation between ",
fittedModel$mptInfo$thetaUnique[s1], " and ",
fittedModel$mptInfo$thetaUnique[s2]),
xlab="Correlation (on latent probit scale)", las=1, ...)
lines(prior.cor, col="blue", lty="dashed")
abline(v= quantile(unlist(fittedModel$runjags$mcmc[,paste0("rho[",s1,",",s2,"]")]),
c((1-ci)/2,1-(1-ci)/2)), col="red")
}
}
}
par(mfrow=mfrow)
}
|
DfReadCrossedModalities <- function(fileName, sequentialNames = FALSE) {
UNINITIALIZED <- RJafrocEnv$UNINITIALIZED
wb <- excel_sheets(fileName)
sheetNames <- toupper(wb)
truthFileIndex <- which(!is.na(match(sheetNames, "TRUTH")))
if (truthFileIndex == 0)
stop("TRUTH table cannot be found in the dataset.")
truthTable <- data.frame(read_xlsx(fileName, truthFileIndex, range = cell_cols(1:3) ) )
for (i in 1:3){
truthTable[grep("^\\s*$", truthTable[ , i]), i] <- NA
}
naRows <- colSums(is.na(truthTable))
if (max(naRows) > 0) {
if (max(naRows) == min(naRows)) {
truthTable <- truthTable[1:(nrow(truthTable) - max(naRows)), ]
}
}
for (i in 1:2) {
if (any((as.numeric(as.character(truthTable[, i]))) %% 1 != 0 )) {
naLines <- which(!is.integer(as.numeric(as.character(truthTable[, i])))) + 1
errorMsg <- paste0("There are non-integer values(s) for CaseID or LesionID at the line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table.")
stop(errorMsg)
}
}
if (any(is.na(as.numeric(as.character(truthTable[, 3]))))) {
naLines <- which(is.na(as.numeric(as.character(truthTable[, 3])))) + 1
errorMsg <- paste0("There are non-numeric values(s) for weights at the line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table.")
stop(errorMsg)
}
caseID <- as.integer(truthTable[[1]])
lesionID <- as.integer(truthTable[[2]])
weights <- truthTable[[3]]
normalCases <- sort(unique(caseID[lesionID == 0]))
abnormalCases <- sort(unique(caseID[lesionID > 0]))
allCases <- c(normalCases, abnormalCases)
K1 <- length(normalCases)
K2 <- length(abnormalCases)
K <- (K1 + K2)
if (anyDuplicated(cbind(caseID, lesionID))) {
naLines <- which(duplicated(cbind(caseID, lesionID))) + 1
errorMsg <- paste0("Line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table are duplicated with previous line(s) .")
stop(errorMsg)
}
nlFileIndex <- which(!is.na(match(sheetNames, c("FP", "NL"))))
if (nlFileIndex == 0)
stop("FP/NL table cannot be found in the dataset.")
NLTable <- data.frame( read_xlsx(fileName, nlFileIndex, range = cell_cols(1:5) ) )
for (i in 1:5){
NLTable[grep("^\\s*$", NLTable[ , i]), i] <- NA
}
naRows <- colSums(is.na(NLTable))
if (max(naRows) > 0) {
if (max(naRows) == min(naRows)) {
NLTable <- NLTable[1:(nrow(NLTable) - max(naRows)), ]
}
}
for (i in 4:5) {
if (any(is.na(as.numeric(as.character(NLTable[, i]))))) {
naLines <- which(is.na(as.numeric(as.character(NLTable[, i])))) + 1
errorMsg <- paste0("There are missing cell(s) at line(s) ", paste(naLines, collapse = ", "), " in the FP table.")
stop(errorMsg)
}
}
NLReaderID <- as.character(NLTable[[1]])
NLModalityID1 <- as.character(NLTable[[2]])
NLModalityID2 <- as.character(NLTable[[3]])
NLCaseID <- NLTable[[4]]
if (any(!(NLCaseID %in% caseID))) {
naCases <- NLCaseID[which(!(NLCaseID %in% caseID))]
errorMsg <- paste0("Case(s) ", paste(unique(naCases), collapse = ", "), " in the FP table cannot be found in TRUTH table.")
stop(errorMsg)
}
NLRating <- NLTable[[5]]
llFileIndex <- which(!is.na(match(sheetNames, c("TP", "LL"))))
if (llFileIndex == 0)
stop("TP/LL table cannot be found in the dataset.")
LLTable <- data.frame(read_xlsx(fileName, llFileIndex, range = cell_cols(1:6) ) )
for (i in 1:6){
LLTable[grep("^\\s*$", LLTable[ , i]), i] <- NA
}
naRows <- colSums(is.na(LLTable))
if (max(naRows) > 0) {
if (max(naRows) == min(naRows)) {
LLTable <- LLTable[1:(nrow(LLTable) - max(naRows)), ]
}
}
for (i in 4:6) {
if (any(is.na(as.numeric(as.character(LLTable[, i]))))) {
naLines <- which(is.na(as.numeric(as.character(LLTable[, i])))) + 1
errorMsg <- paste0("There are missing cell(s) at line(s) ", paste(naLines, collapse = ", "), " in the TP table.")
stop(errorMsg)
}
}
LLReaderID <- as.character(LLTable[[1]])
LLModalityID1 <- as.character(LLTable[[2]])
LLModalityID2 <- as.character(LLTable[[3]])
LLCaseID <- LLTable[[4]]
LLLesionID <- LLTable[[5]]
for (i in 1:nrow(LLTable)) {
lineNum <- which((caseID == LLCaseID[i]) & (lesionID == LLLesionID[i]))
if (!length(lineNum)) {
errorMsg <- paste0("Modality ", LLTable[i, 1], "and ", LLTable[i, 2], " Reader(s) ", LLTable[i, 1], " Case(s) ", LLTable[i, 4], " Lesion(s) ", LLTable[i, 5], " cannot be found in TRUTH table .")
stop(errorMsg)
}
}
LLRating <- LLTable[[6]]
if (anyDuplicated(LLTable[, 1:5])) {
naLines <- which(duplicated(LLTable[, 1:5]))
errorMsg <- paste0("Modality1 ", paste(LLTable[naLines, 2], collapse = ", "), "Modality2 ", paste(LLTable[naLines, 3], collapse = ", "),
" Reader(s) ", paste(LLTable[naLines, 1], collapse = ", "), " Case(s) ", paste(LLTable[naLines, 4], collapse = ", "),
" Lesion(s) ", paste(LLTable[naLines, 5], collapse = ", "), " have multiple ratings in TP table .")
stop(errorMsg)
}
perCase <- as.vector(table(caseID[caseID %in% abnormalCases]))
lesionWeight <- array(dim = c(length(abnormalCases), max(perCase)))
lesionIDTable <- array(dim = c(length(abnormalCases), max(perCase)))
for (k2 in 1:length(abnormalCases)) {
k <- which(caseID == abnormalCases[k2])
lesionIDTable[k2, ] <- c(sort(lesionID[k]), rep(UNINITIALIZED, max(perCase) - length(k)))
if (all(weights[k] == 0)) {
lesionWeight[k2, 1:length(k)] <- 1/perCase[k2]
} else {
lesionWeight[k2, ] <- c(weights[k][order(lesionID[k])], rep(UNINITIALIZED, max(perCase) - length(k)))
sumWeight <- sum(lesionWeight[k2, lesionWeight[k2, ] != UNINITIALIZED])
if (sumWeight != 1){
if (sumWeight <= 1.01 && sumWeight >= 0.99){
lesionWeight[k2, ] <- lesionWeight[k2, ] / sumWeight
}else{
errorMsg <- paste0("The sum of the weights of Case ", k2, " is not 1.")
stop(errorMsg)
}
}
}
}
modalityID1 <- as.character(sort(unique(c(NLModalityID1, LLModalityID1))))
I1 <- length(modalityID1)
modalityID2 <- as.character(sort(unique(c(NLModalityID2, LLModalityID2))))
I2 <- length(modalityID2)
readerID <- as.character(sort(unique(c(NLReaderID, LLReaderID))))
J <- length(readerID)
maxNL <- 0
for (i1 in modalityID1) {
for (i2 in modalityID2) {
for (j in readerID) {
k <- (NLModalityID1 == i1) & (NLModalityID2 == i2) & (NLReaderID == j)
if ((sum(k) == 0))
next
maxNL <- max(maxNL, max(table(NLCaseID[k])))
}
}
}
NL <- array(dim = c(I1, I2, J, K, maxNL))
for (i1 in 1:I1) {
for (i2 in 1:I2) {
for (j in 1:J) {
k <- (NLModalityID1 == modalityID1[i1]) & (NLModalityID2 == modalityID2[i2]) & (NLReaderID == readerID[j])
if ((sum(k) == 0))
next
caseNLTable <- table(NLCaseID[k])
IDs <- as.numeric(unlist(attr(caseNLTable, "dimnames")))
for (k1 in 1:length(IDs)) {
for (el in 1:caseNLTable[k1]) {
NL[i1, i2, j, which(IDs[k1] == allCases), el] <- NLRating[k][which(NLCaseID[k] == IDs[k1])][el]
}
}
}
}
}
LL <- array(dim = c(I1, I2, J, K2, max(perCase)))
for (i1 in 1:I1) {
for (i2 in 1:I2) {
for (j in 1:J) {
k <- (LLModalityID1 == modalityID1[i1]) & (LLModalityID2 == modalityID2[i2]) & (LLReaderID == readerID[j])
if ((sum(k) == 0))
next
caseLLTable <- table(LLCaseID[k])
IDs <- as.numeric(unlist(attr(caseLLTable, "dimnames")))
for (k1 in 1:length(IDs)) {
for (el in 1:caseLLTable[k1]) {
LL[i1, i2, j, which(IDs[k1] == abnormalCases), which(LLLesionID[k][which(LLCaseID[k] == IDs[k1])][el] == lesionIDTable[which(IDs[k1] == abnormalCases), ])] <- LLRating[k][which(LLCaseID[k] == IDs[k1])][el]
}
}
}
}
}
lesionWeight[is.na(lesionWeight)] <- UNINITIALIZED
lesionIDTable[is.na(lesionIDTable)] <- UNINITIALIZED
NL[is.na(NL)] <- UNINITIALIZED
LL[is.na(LL)] <- UNINITIALIZED
isROI <- TRUE
for (i1 in 1:I1) {
for (i2 in 1:I2) {
for (j in 1:J) {
if (any(NL[i1, i2, j, 1:K1, ] == UNINITIALIZED)) {
isROI <- FALSE
break
}
temp <- LL[i1, i2, j, , ] != UNINITIALIZED
dim(temp) <- c(K2, max(perCase))
if (!all(perCase == rowSums(temp))) {
isROI <- FALSE
break
}
temp <- NL[i1, i2, j, (K1 + 1):K, ] == UNINITIALIZED
dim(temp) <- c(K2, maxNL)
if (!all(perCase == rowSums(temp))) {
isROI <- FALSE
break
}
}
}
}
if ((max(table(caseID)) == 1) && (maxNL == 1) && (all((NL[, , , (K1 + 1):K, ] == UNINITIALIZED))) && (all((NL[, , , 1:K1, ] != UNINITIALIZED)))) {
type <- "ROC"
} else {
if (isROI) {
type <- "ROI"
} else {
type <- "FROC"
}
}
modality1Names <- modalityID1
modality2Names <- modalityID2
readerNames <- readerID
if (sequentialNames){
modalityID1 <- 1:I1
modalityID2 <- 1:I2
readerID <- 1:J
}
names(modalityID1) <- modality1Names
names(modalityID2) <- modality2Names
names(readerID) <- readerNames
fileName <- paste0("DfReadCrossedModalities(", tools::file_path_sans_ext(basename(fileName)), ")")
name <- "THOMPSON-X-MOD"
design <- "FCTRL-X-MOD"
truthTableStr <- NA
IDs <- lesionIDTable
weights <- lesionWeight
return(convert2Xdataset(NL, LL, LL_IL = NA,
perCase, IDs, weights,
fileName, type, name, truthTableStr, design,
modalityID1, modalityID2, readerID))
}
|
post.column.switch <- function(mcmc)
{
assertClass(mcmc, classes = "befa")
if (attr(mcmc, "post.column.switch")) {
warning("column switching already performed, nothing done.")
return(mcmc)
}
if (mean(mcmc$MHacc) < 0.2) {
warning(paste("M-H acceptance rate of sampler is low (< 0.20).",
"Check convergence and mixing!"))
}
Kmax <- attr(mcmc, "Kmax")
nvar <- ncol(mcmc$dedic)
iter <- nrow(mcmc$dedic)
R.npar <- Kmax * (Kmax - 1)/2
R.mat <- diag(Kmax) * (R.npar + 1)
R.mat[lower.tri(R.mat)] <- 1:R.npar
R.mat[upper.tri(R.mat)] <- t(R.mat)[upper.tri(R.mat)]
v <- 1:Kmax
for (i in 1:iter) {
d <- mcmc$dedic[i, ]
mcmc$dedic[i, ] <- relabel.dedic(d)
u <- unique(d[d != 0])
r <- c(u, v[!v %in% u])
R <- c(mcmc$R[i, ], 1)
R <- matrix(R[R.mat], nrow = Kmax)
R <- R[r, r]
mcmc$R[i, ] <- R[lower.tri(R)]
}
attr(mcmc, "post.column.switch") <- TRUE
return(mcmc)
}
|
compute.rmse<-function(Y,X){
if(length(Y)!=length(X)){stop("Input vectors are of different length !!!")}
lengthNAX <- sum(is.na(X))
if(lengthNAX > 0){warning(paste("Vector of true values contains ", lengthNAX, " NA !!! NA excluded", sep = ""))}
lengthNAY <- sum(is.na(Y))
if(lengthNAY > 0){warning(paste("Vector of imputed values contains ", lengthNAY, " NA !!! NA excluded", sep = ""))}
n <- length(X)-max(lengthNAX, lengthNAY)
out=sqrt(sum((Y-X)^2, na.rm = T)/n)
return(out)
}
|
data_dir <- file.path("..", "testdata")
tempfile_nc <- function() {
tempfile_helper("cmsaf.cat_")
}
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
temp2, temp2, temp2[1:3])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "cmsaf_info")$value
expect_equal(actual, "cmsafops::cmsaf.cat for variable SIS")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out, nc34 = 4)
file <- nc_open(file_out)
test_that("data is correct in version 4", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
temp2, temp2, temp2[1:3])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct in version 4", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct in version 4", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
file_out <- tempfile_nc()
test_that("error is thrown if ncdf version is wrong", {
expect_error(
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out, nc34 = 7),
"nc version must be in c(3, 4), but was 7", fixed = TRUE
)
})
file_out <- tempfile_nc()
test_that("ncdf version NULL throws an error", {
expect_error(
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out, nc34 = NULL),
"nc_version must not be NULL"
)
})
file_out <- tempfile_nc()
test_that("no error is thrown if var does not exist", {
expect_warning(cmsaf.cat("lat",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out),
"Variable 'lat' not found. Variable 'SIS' will be used instead.")
})
file <- nc_open(file_out)
test_that("data is correct if non-existing variable is given", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
temp2, temp2, temp2[1:3])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct if non-existing variable is given", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct if non-existing variable is given", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
file_out <- tempfile_nc()
test_that("error is thrown if variable is NULL", {
expect_error(
cmsaf.cat(NULL,
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out),
"variable must not be NULL"
)
})
test_that("no error is thrown if var does not exist", {
file_out <- tempfile_nc()
expect_warning(cmsaf.cat("",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out),
"Variable '' not found. Variable 'SIS' will be used instead.")
})
file_out <- tempfile_nc()
test_that("error is thrown if input file does not exist", {
expect_error(cmsaf.cat("SIS",
c(file.path(data_dir, "xemaple1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out),
"Input file ../testdata/xemaple1.nc does not exist")
})
file_out <- tempfile_nc()
test_that("error is thrown if input filename is empty", {
expect_error(cmsaf.cat("SIS", c("",
file.path(data_dir, "ex_normal2.nc")),
file_out),
"Input file does not exist")
})
file_out <- tempfile_nc()
test_that("no error is thrown if input filename is NULL", {
expect_error(cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
NULL),
file_out),
NA)
})
file_out <- tempfile_nc()
cat("test\n", file = file_out)
test_that("no error is thrown if output file already exists", {
expect_error(cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out),
paste0("File '",
file_out,
"' already exists. Specify 'overwrite = TRUE' if you want to overwrite it."),
fixed = TRUE)
})
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_time_dim1.nc"),
file.path(data_dir, "ex_time_dim2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(rep(temp, 4), temp[1:6],
rep(temp2, 4), temp2[1:6])
expected <- array(expected_data, dim = c(7, 7, 4))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544, 167976, 177480)))
})
nc_close(file)
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_normal1.nc"),
file.path(data_dir, "ex_time_dim2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
rep(temp2, 5))
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 167976, 177480)))
})
nc_close(file)
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_time_dim1.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp1 <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp2, temp2, temp2[1:3],
rep(temp1, 7))
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(158544, 149016, 158544)))
})
nc_close(file)
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_time_dim3.nc"),
file.path(data_dir, "ex_time_dim2.nc")),
file_out)
test_that("output file is created because dimensions match", {
expect_true(file.exists(file_out))
})
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_additional_attr.nc"),
file.path(data_dir, "ex_normal2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
temp2, temp2, temp2[1:3])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 2)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
actual <- names(global_attr[2])
expect_equal(actual, "institution")
actual <- global_attr[[2]]
expect_equal(actual, "This is a test attribute.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
file_out <- tempfile_nc()
cmsaf.cat("SIS",
c(file.path(data_dir, "ex_v4_1.nc"),
file.path(data_dir, "ex_v4_2.nc")),
file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
temp <- seq(250, 272)
temp2 <- seq(230, 252)
expected_data <- c(temp, temp, temp[1:3],
temp2, temp2, temp2[1:3])
expected <- array(expected_data, dim = c(7, 7, 2))
expect_equivalent(actual, expected)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149016, 158544)))
})
nc_close(file)
|
library(gridGraphics)
require(grDevices)
plot.factor1 <- function() {
plot(weight ~ group, data = PlantGrowth)
}
plot.factor2 <- function() {
plot(cut(weight, 2) ~ group, data = PlantGrowth)
}
plot.factor3 <- function() {
plot(cut(weight, 3) ~ group, data = PlantGrowth,
col = hcl(c(0, 120, 240), 50, 70))
}
plot.factor4 <- function() {
plot(PlantGrowth$group, axes = FALSE, main = "no axes")
}
plotdiff(expression(plot.factor1()), "plot.factor-1")
plotdiff(expression(plot.factor2()), "plot.factor-2")
plotdiff(expression(plot.factor3()), "plot.factor-3")
plotdiff(expression(plot.factor4()), "plot.factor-4")
plotdiffResult()
|
seqadd.confint=function(L, alpha, presample, addsample){
n0=length(presample)
s0=sd(presample)
z=(L/2)^2/qt(1-alpha/2,n0-1)^2
n=max(n0+1,ceiling(s0^2/z))
a=z*(s0^2)
if (n<1/a) n=ceiling(1/a)
g=function(x){((n/n0)/(n-n0))*x^2-(2/(n-n0))*x+1/(n-n0)-z*s0^2}
b=seq(-1,1,0.05)
lb=length(b)
k=max(which(g(b)*g(1)<0))
a0=uniroot(g,c(b[k],1))$root
a1=(1-a0)/(n-n0)
ln=a0*mean(presample)+a1*sum(addsample)
list("Significance level"=alpha,
"Length of confidence interval"=L,
"Length of presample"=n0,
"Number of additional observations"=n-n0,
"Total number of observations"=n,
"confidence interval"=c(ln-L/2,ln+L/2))
}
|
index.G1d<-function(d,cl)
{
d<-as.matrix(d)
wgss<-0
bgss<-0
for(i in 1:(nrow(d)-1))
for(j in (i+1):nrow(d)){
if(cl[i]==cl[j]){
wgss<-wgss+d[i,j]^2
}
else{
bgss<-bgss+d[i,j]^2
}
}
(bgss/(max(cl)-1))/((sum(d^2)/2-bgss)/(length(cl)-max(cl)))
}
|
ind.plots.cwres.hist <-
function(object,
wres="cwres",
...) {
obj <- ind.plots.wres.hist(object,wres=wres,...)
return(obj)
}
|
library(gpuR)
context("CPU vclMatrix qr decomposition")
current_context <- set_device_context("cpu")
set.seed(123)
ORDER <- 10
X <- matrix(rnorm(ORDER^2), nrow=ORDER, ncol=ORDER)
nsqA <- matrix(rnorm(20), nrow = 4)
qrX <- qr(X)
Q <- qr.Q(qrX)
R <- qr.R(qrX)
test_that("CPU vclMatrix Single Precision Matrix QR Decomposition",
{
has_cpu_skip()
fgpuX <- vclMatrix(X, type="float")
fgpuA <- vclMatrix(nsqA, type = "float")
E <- qr(fgpuX)
gpuQ <- qr.Q(E)
gpuR <- qr.R(E)
expect_is(E, "gpuQR")
expect_equal(abs(gpuQ[]), abs(Q), tolerance=1e-05,
info="Q matrices not equivalent")
expect_equal(abs(gpuR[]), abs(R), tolerance=1e-05,
info="R matrices not equivalent")
expect_error(qr(fgpuA), "non-square matrix not currently supported for 'qr'",
info = "qr shouldn't accept non-square matrices")
})
test_that("CPU vclMatrix Double Precision Matrix QR Decomposition",
{
has_cpu_skip()
fgpuX <- vclMatrix(X, type="double")
fgpuA <- vclMatrix(nsqA, type = "double")
E <- qr(fgpuX)
gpuQ <- qr.Q(E)
gpuR <- qr.R(E)
expect_is(E, "gpuQR")
expect_equal(abs(gpuQ[]), abs(Q), tolerance=.Machine$double.eps ^ 0.5,
info="Q matrices not equivalent")
expect_equal(abs(gpuR[]), abs(R), tolerance=.Machine$double.eps ^ 0.5,
info="R matrices not equivalent")
expect_error(qr(fgpuA), "non-square matrix not currently supported for 'qr'",
info = "qr shouldn't accept non-square matrices")
})
setContext(current_context)
|
asl.optim <- function(x){
init <- asl.optim.init(x)
if(init[4] == 0){
warning("Initial values are on the boundary.")
}
ui <- rbind(c(1, 0, 0),
c(-1, 0, 0),
c(0, 0, 1))
ci <- c(min(x), -max(x), 0)
theta <- init[-3]
tmp <- constrOptim(theta, asl.logL, grad = NULL, ui, ci,
method = "Nelder-Mead",
x = x)
theta <- tmp$par[1]
mu <- tmp$par[2]
sigma <- tmp$par[3]
kappa <- (sqrt(2 * sigma^2 + mu^2) - mu) / sqrt(2 * sigma)
ret <- c(theta, mu, kappa, sigma)
names(ret) <- c("theta", "mu", "kappa", "sigma")
ret
}
asl.logL <- function(theta, x){
-sum(dasl(x, theta = theta[1], mu = theta[2], sigma = theta[3], log = TRUE))
}
asl.optim.init <- function(x){
theta <- x
all.h <- do.call("c", lapply(theta, h.theta, x))
r <- which.min(all.h)
if(r == 1){
ret <- c(x[r], x[r] - mean(x), 0, 0)
} else if(r == length(x)){
ret <- c(x[r], mean(x) - x[r], 0, 0)
} else{
theta.hat <- x[r]
alpha.beta <- asl.alpha.beta(theta.hat, x)
sqrt.alpha.beta <- sqrt(alpha.beta)
forth.root.alpha.beta <- alpha.beta^{0.25}
kappa.hat <- forth.root.alpha.beta[2] / forth.root.alpha.beta[1]
sigma.hat <- sqrt(2) * forth.root.alpha.beta[1] * forth.root.alpha.beta[2] *
(sqrt.alpha.beta[1] + sqrt.alpha.beta[2])
mu.hat <- sigma.hat / sqrt(2) * (1 / kappa.hat - kappa.hat)
ret <- c(theta.hat, mu.hat, kappa.hat, sigma.hat)
}
names(ret) <- c("theta", "mu", "kappa", "sigma")
ret
}
h.theta <- function(theta, x){
alpha.beta <- asl.alpha.beta(theta, x)
sqrt.alpha.beta <- sqrt(alpha.beta)
ret <- 2 * log(sqrt.alpha.beta[1] + sqrt.alpha.beta[2]) +
sqrt.alpha.beta[1] * sqrt.alpha.beta[2]
ret
}
asl.alpha.beta <- function(theta, x){
tmp <- (x - theta)
alpha <- sum(tmp[tmp >= 0])
beta <- -sum(tmp[tmp <= 0])
ret <- c(alpha, beta) / length(tmp)
ret
}
|
epmc_search <- function(query = NULL,
output = 'parsed',
synonym = TRUE,
verbose = TRUE,
limit = 100,
sort = NULL) {
stopifnot(is.logical(c(verbose, synonym)))
stopifnot(is.numeric(limit))
if (!is.null(sort)) {
match.arg(sort, c("date", "cited"))
query <- switch(
sort,
date = paste(query, "sort_date:y"),
cited = paste(query, "sort_cited:y")
)
} else {
query <- query
}
query <- transform_query(paste0(query, "&synonym=", synonym))
page_token <- "*"
if (!output == "raw")
results <- tibble::tibble()
else
results <- NULL
out <-
epmc_search_(
query = query,
limit = limit,
output = output,
verbose = verbose,
page_token = page_token,
sort = sort
)
res_chunks <- chunks(limit = limit)
hits <- epmc_hits(query, synonym = synonym)
if (hits == 0) {
message("There are no results matching your query")
md <- NULL
} else {
limit <- as.integer(limit)
limit <- ifelse(hits <= limit, hits, limit)
message(paste(hits, "records found, returning", limit))
if (!is.null(out$next_cursor)) {
i <- 0
pb <- pb(limit = limit)
while (i < res_chunks$page_max) {
out <-
epmc_search_(
query = query,
limit = limit,
output = output,
verbose = verbose,
page_token = page_token,
sort = sort
)
if (is.null(out$next_cursor))
break
i <- i + 1
if (verbose == TRUE && hits > 100)
pb$tick()
page_token <- out$next_cursor
if (output == "raw") {
results <- c(results, out$results)
} else {
results <- dplyr::bind_rows(results, out$results)
}
}
if (output == "raw") {
md <- results[1:limit]
} else {
md <- results[1:limit, ]
}
attr(md, "hit_count") <- hits
} else {
md <- out$results
attr(md, "hit_count") <- hits
}
}
return(md)
}
epmc_search_ <-
function(query = NULL,
limit = 100,
output = "parsed",
page_token = NULL,
...) {
limit <- as.integer(limit)
page_size <- ifelse(batch_size() <= limit, batch_size(), limit)
if (!output %in% c("id_list", "parsed", "raw"))
stop("'output' must be one of 'parsed', 'id_list', or 'raw'",
call. = FALSE)
result_types <- c("id_list" = "idlist",
"parsed" = "lite",
"raw" = "core")
resulttype <- result_types[[output]]
args <-
list(
query = query,
format = "json",
resulttype = resulttype,
pageSize = page_size,
cursorMark = page_token
)
out <-
rebi_GET(path = paste0(rest_path(), "/search"), query = args)
if (!resulttype == "core") {
md <- out$resultList$result
if (length(md) == 0) {
md <- tibble::tibble()
} else {
md <- md %>%
dplyr::select_if(Negate(is.list)) %>%
tibble::as_tibble()
}
} else {
out <- jsonlite::fromJSON(out, simplifyDataFrame = FALSE)
md <- out$resultList$result
}
list(next_cursor = out$nextCursorMark, results = md)
}
|
tuneLasso <- function
(Y,
X,
normalize=TRUE,
method=c("lasso","Glasso"),
dmax=NULL,
Vfold=TRUE,
V=10,
LINselect=TRUE,
a=0.5,
K=1.1,
verbose=TRUE,
max.steps=NULL
)
{
calc.proj <- FALSE
calc.pen <- FALSE
res <- NULL
n=nrow(X)
p=ncol(X)
Xmean <- apply(X,2,mean)
mu=mean(Y)
if (is.null(max.steps)) max.steps=2*min(p,n)
if (p>=n) dmax <- floor(min(c(3*p/4,n-5,dmax)))
if (p<n) dmax <- floor(min(c(p,n-5,dmax)))
res.lasso <- try(enet(X,Y,lambda=0, intercept=TRUE, normalize=normalize,
max.steps=max.steps))
if (inherits(res.lasso, "try-error")) {
print("error when calling enet")
res <- res.lasso[1]
}
if (!inherits(res.lasso, "try-error")) {
lesBeta <- array(0,c(dim(res.lasso$beta.pure)[1],p))
lesBeta[,res.lasso$allset] <- res.lasso$beta.pure
lesDim <- apply(lesBeta!=0,1,sum)
if (max(lesDim) <= dmax) Nmod.lasso <- length(lesDim)
if (max(lesDim)>dmax) Nmod.lasso<-(1:dim(lesBeta)[1])[(lesDim>=dmax)][1]
f.lasso <- matrix(0,nrow=n,ncol=Nmod.lasso)
Intercept <- mu-lesBeta[1:Nmod.lasso,]%*%Xmean
for (l in 1:Nmod.lasso) {
f.lasso[,l] <- rep(Intercept[l],n)+X%*%lesBeta[l,]
}
if (is.element("lasso",method)) {
res<- list(lasso=NULL)
if (Vfold) {
if (verbose) {
print(paste("Tuning Lasso with Vfold CV: V=",V,", dmax=",dmax))
}
s <- 1:(Nmod.lasso+1)
res.cv.enet=0
while (!is.list(res.cv.enet)) {
s <- s[-length(s)]
res.cv.enet <- try(cv.enet(X, Y, K = V, lambda=0,
s=s, mode="step", normalize=normalize,
intercept=TRUE,
plot.it=FALSE,se=FALSE),silent=TRUE)
}
l.lasso <- which.min(res.cv.enet$cv)
f.pred <- f.lasso[,l.lasso]
coeff <- c(Intercept[l.lasso],lesBeta[l.lasso,][lesBeta[l.lasso,]!=0])
names(coeff) <- c("Intercept",which(lesBeta[l.lasso,]!=0))
res$lasso$CV <- list(support=which(lesBeta[l.lasso,]!=0),
coeff=coeff, fitted=f.pred, crit=res.cv.enet$cv,
crit.error=res.cv.enet$cv.error,
lambda=res.lasso$penalty[s])
}
if (LINselect) {
calc.proj <- TRUE
if (verbose) print(paste("Tuning Lasso with LINselect: K=",K,", a=",a,", dmax=",dmax))
D <- 0:dmax
dm <- pmin(D,rep(p/2,dmax+1))
Delta <- lgamma(p+1)-lgamma(dm+1)-lgamma(p-dm+1)+2*log(D+1)
pen <- penalty(Delta, n, p, K)
calc.pen <- TRUE
I.lasso <- list(NULL)
ProjMod <- array(0,c(n,n,Nmod.lasso))
A <- array(Inf,c(Nmod.lasso,Nmod.lasso))
B=A
SCR <- rep(0,Nmod.lasso)
penSCR <- rep(0,Nmod.lasso)
sumY2 <- sum((Y-mu)**2)
un <- rep(1,n)
for (l in 1:Nmod.lasso) {
I.lasso[[l]] <- (1:p)[lesBeta[l,]!=0]
if (length(I.lasso[[l]])>0) {
ProjM <- Proj(cbind(un,X[,I.lasso[[l]]]),length(I.lasso[[l]])+1)
ProjMod[,,l] <- ProjM$Proj
SCR[l] <- sum((Y-ProjMod[,,l]%*%Y)**2)
penSCR[l] <- SCR[l]*pen[ProjM$rg+1]/(n-ProjM$rg)
}
if (length(I.lasso[[l]])==0) {
ProjMod[,,l] <- un%*%t(un)/n
ProjM <- list(Proj=ProjMod[,,l],rg=1)
SCR[l] <- sumY2
penSCR[l] <- sumY2*pen[ProjM$rg+1]/(n-ProjM$rg)
}
}
Ind <- rep(1:Nmod.lasso,rep(Nmod.lasso,Nmod.lasso))
YY<-Y%*%t(rep(1,Nmod.lasso))
for (m in 1:Nmod.lasso) {
Proj.f<-ProjMod[,,m]%*%f.lasso
B[m,] <- apply((YY-Proj.f)**2,2,sum)+a*apply((f.lasso-Proj.f)**2,2,sum)
A[m,] <- B[m,]+penSCR[m]
}
l.lasso <- Ind[which.min(A)]
f.pred <- f.lasso[, l.lasso]
coeff <- c(Intercept[l.lasso],lesBeta[l.lasso,][lesBeta[l.lasso,]!=0])
names(coeff) <- c("Intercept",which(lesBeta[l.lasso,]!=0))
crit <- apply(A,2,min)
res$lasso$Ls <- list(support=which(lesBeta[l.lasso,]!=0),
coeff=coeff, fitted=f.pred, crit=crit,
lambda=res.lasso$penalty[1:Nmod.lasso])
}
}
if (is.element("Glasso",method)) {
if (!is.list(res)) res <- list(Glasso=NULL)
if (!calc.pen) {
D <- 0:dmax
dm <- pmin(D,rep(p/2,dmax+1))
Delta <- lgamma(p+1)-lgamma(dm+1)-lgamma(p-dm+1)+2*log(D+1)
pen <- penalty(Delta, n, p, K)
}
if (!calc.proj) {
I.lasso <- list(NULL)
SCR <- rep(0,Nmod.lasso)
penSCR <- rep(0,Nmod.lasso)
sumY2 <- sum((Y-mu)**2)
un <- rep(1,n)
for (l in 1:Nmod.lasso) {
I.lasso[[l]] <- (1:p)[lesBeta[l,]!=0]
if (length(I.lasso[[l]])>0) {
ProjM <- Proj(cbind(un,X[,I.lasso[[l]]]),length(I.lasso[[l]])+1)
SCR[l] <- sum((Y-ProjM$Proj%*%Y)**2)
penSCR[l] <- SCR[l]*pen[ProjM$rg+1]/(n-ProjM$rg)
}
if (length(I.lasso[[l]])==0) {
SCR[l] <- sumY2
penSCR[l] <- SCR[l]*pen[2]/(n-1)
}
}
}
if (Vfold) {
if (verbose) {
print(paste("Tuning Gauss Lasso with Vfold CV: V=",V,", dmax=",dmax))
}
I.CV <- list(NULL)
IM.CV <- list(NULL)
for (iv in 1:V) {
I.CV[[iv]] <- (floor((iv-1)*n/V)+1):(iv*n/V)
IM.CV[[iv]] <- (1:n)[-I.CV[[iv]]]
}
active_set<-list(NULL)
all_lambda<-c(-1)
lambda <- list(NULL)
for (i in 1:V) {
in_s<-enleve_var_0(X,IM.CV[[i]])
res.i<-enet(X[IM.CV[[i]],in_s],Y[IM.CV[[i]]],lambda=0,
intercept=TRUE,normalize=normalize,max.steps=max.steps)
lesBeta.i <- array(0,c(dim(res.i$beta.pure)[1],length(in_s)))
lesBeta.i[,res.i$allset] <- res.i$beta.pure
lesDim.i <- apply(lesBeta.i!=0,1,sum)
if (max(lesDim.i) <= dmax) Nmod.lasso.i <- length(lesDim.i)
if (max(lesDim.i)>dmax) Nmod.lasso.i<-(1:dim(lesBeta.i)[1])[(lesDim.i>=dmax)][1]
lambda[[i]]<-res.i$penalty[1:Nmod.lasso.i]
active_set[[i]]<-active(res.i,in_s)[1:Nmod.lasso.i]
all_lambda<-c(all_lambda,lambda[[i]])
}
all_lambda<-all_lambda[2:(length(all_lambda))]
L1 <- length(all_lambda)
all_lambda<-c(all_lambda,res.lasso$penalty[1:Nmod.lasso])
L<-length(all_lambda)
rank.all_lambda<-L-rank(all_lambda)+1
sort.all_lambda<-sort(all_lambda,decreasing=TRUE)
erreur<-matrix(0,V,L)
for (i in 1:V) {
est<-estime2(Y,X,I.CV[[i]],IM.CV[[i]],active_set[[i]])
ind<-1
for (l in 1:L) {
if (lambda[[i]][ind]>sort.all_lambda[l]) {
if (ind < length(lambda[[i]])) {
ind<-ind+1
}
}
erreur[i,l]<-est[[ind]]
}
}
resultat<-apply(erreur,2,mean)
err.resultat<-sqrt(apply(erreur,2,var))/sqrt(V)
resultat[resultat<10**(-10)] <- 0
lambda_cv<-sort.all_lambda[which.min(resultat)]
ind<-indice(lambda_cv,res.lasso$penalty[1:Nmod.lasso])
rlm <- lm(Y~X[,I.lasso[[ind]]])
beta <- rlm$coef
names(beta) <- c("Intercept",I.lasso[[ind]])
resultatF <- c(min(resultat),
resultat[rank.all_lambda][(L1+1):L])
err.resultatF <- c(err.resultat[which.min(resultat)],
err.resultat[rank.all_lambda][(L1+1):L])
les.lambda <- c(lambda_cv,res.lasso$penalty[1:Nmod.lasso])
crit <- resultatF[order(les.lambda,decreasing=TRUE)]
crit.error <- err.resultatF[order(les.lambda,decreasing=TRUE)]
res$Glasso$CV <- list(support=I.lasso[[ind]],
coeff=beta, fitted=rlm$fitted,
crit=crit,
crit.error=crit.error,
lambda=sort(les.lambda,decreasing=TRUE))
}
if (LINselect) {
if (verbose) print(paste("Tuning Gauss Lasso with LinSelect: K=",K))
if (!calc.pen) {
D <- 0:dmax
dm <- pmin(D,rep(p/2,dmax+1))
Delta <- lgamma(p+1)-lgamma(dm+1)-lgamma(p-dm+1)+2*log(D+1)
pen <- penalty(Delta, n, p, K)
}
crit <- SCR + penSCR
ind <- which.min(crit)
rlm <- lm(Y~X[,I.lasso[[ind]]])
beta <- rlm$coef
names(beta) <- c("Intercept",I.lasso[[ind]])
res$Glasso$Ls <- list(support=I.lasso[[ind]],
coeff=beta, fitted=rlm$fitted+mu,
crit=crit,
lambda=res.lasso$penalty[1:Nmod.lasso] )
}
}
}
result <- res
return(result)
}
|
header.rest <- function(caption = NULL, caption.level = NULL) {
niv <- c("=", "-", "~", "^", "+")
ncharcap <- nchar(caption)
if (is.null(caption.level))
caption.level <- ""
res <- ""
if (!is.null(caption)) {
if (is.numeric(caption.level) & caption.level > 0) {
res <- paste(caption, paste(paste(rep(niv[caption.level], ncharcap), collapse = ""), "\n", sep = ""), sep = "\n")
} else if (is.character(caption.level) & caption.level %in% c("s", "e", "m")) {
if (caption.level == "s")
res <- paste(beauty.rest(caption, "s"), "\n\n", sep = "")
else if (caption.level == "e")
res <- paste(beauty.rest(caption, "e"), "\n\n", sep = "")
else if (caption.level == "m")
res <- paste(beauty.rest(caption, "m"), "\n\n", sep = "")
} else if (is.character(caption.level) & caption.level != "" & caption.level != "none") {
res <- paste(caption, paste(paste(rep(caption.level, ncharcap), collapse = ""), "\n", sep = ""), sep = "\n")
} else if (caption.level == "" | caption.level == "none") {
res <- paste(caption, "\n\n", sep = "")
}
}
return(res)
}
beauty.rest <- function(x, beauti = c("e", "m", "s")) {
x[is.na(x)] <- "NA"
if (beauti == "s") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("\\*\\*.*\\*\\*", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <- sub("(^ *)([:alpha]*)", "\\1\\*\\*\\2", sub("([:alpha:]*)( *$)", "\\1\\*\\*\\2", x[!y]))
if (length(x[y]) != 0) x[y] <- sub("(^ *$)", "\\1 ", x[y])
}
if (beauti == "e") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("\\*.*\\*", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <-sub("(^ *)([:alpha]*)", "\\1\\*\\2", sub("([:alpha:]*)( *$)", "\\1\\*\\2", x[!y]))
if (length(x[y]) != 0) x[y] <- sub("(^ *$)", "\\1 ", x[y])
}
if (beauti == "m") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("``.*``", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <-sub("(^ *)([:alpha]*)", "\\1``\\2", sub("([:alpha:]*)( *$)", "\\1``\\2", x[!y]))
if (length(x[y]) != 0) x[y] <- sub("(^ *$)", "\\1 ", x[y])
}
return(x)
}
escape.rest <- function(x) {
xx <- gsub("\\|", "\\\\|", x)
xx
}
show.rest.table <- function(x, include.rownames = FALSE, include.colnames = FALSE, rownames = NULL, colnames = NULL, format = "f", digits = 2, decimal.mark = ".", na.print = "", caption = NULL, caption.level = NULL, width = 0, frame = NULL, grid = NULL, valign = NULL, header = FALSE, footer = FALSE, align = NULL, col.width = 1, style = NULL, lgroup = NULL, n.lgroup = NULL, lalign = "c", lvalign = "middle", lstyle = "h", rgroup = NULL, n.rgroup = NULL, ralign = "c", rvalign = "middle", rstyle = "h", tgroup = NULL, n.tgroup = NULL, talign = "c", tvalign = "middle", tstyle = "h", bgroup = NULL, n.bgroup = NULL, balign = "c", bvalign = "middle", bstyle = "h", ...) {
x <- escape.rest(tocharac(x, include.rownames, include.colnames, rownames, colnames, format, digits, decimal.mark, na.print))
nrowx <- nrow(x)
ncolx <- ncol(x)
if (!is.null(style)) {
style <- expand(style, nrowx, ncolx)
style[!(style %in% c("s", "e", "m"))] <- ""
style[style == "s"] <- "**"
style[style == "e"] <- "*"
style[style == "m"] <- "``"
} else {
style <- ""
style <- expand(style, nrowx, ncolx)
}
if (include.rownames & include.colnames) {
style[1, 1] <- ""
}
x <- paste.matrix(style, x, style, sep = "", transpose.vector = TRUE)
if (tstyle == "h")
tstyle <- "s"
if (bstyle == "h")
bstyle <- "s"
if (rstyle == "h")
rstyle <- "s"
if (lstyle == "h")
lstyle <- "s"
if (!is.null(lgroup)) {
if (!is.list(lgroup))
lgroup <- list(lgroup)
n.lgroup <- groups(lgroup, n.lgroup, nrowx-include.colnames)[[2]]
lgroup <- lapply(lgroup, function(x) beauty.rest(x, lstyle))
}
if (!is.null(rgroup)) {
if (!is.list(rgroup))
rgroup <- list(rgroup)
n.rgroup <- groups(rgroup, n.rgroup, nrowx-include.colnames)[[2]]
rgroup <- lapply(rgroup, function(x) beauty.rest(x, rstyle))
}
if (!is.null(tgroup)) {
if (!is.list(tgroup))
tgroup <- list(tgroup)
n.tgroup <- groups(tgroup, n.tgroup, ncolx-include.rownames)[[2]]
tgroup <- lapply(tgroup, function(x) beauty.rest(x, tstyle))
}
if (!is.null(bgroup)) {
if (!is.list(bgroup))
bgroup <- list(bgroup)
n.bgroup <- groups(bgroup, n.bgroup, ncolx-include.rownames)[[2]]
bgroup <- lapply(bgroup, function(x) beauty.rest(x, bstyle))
}
if (!is.null(tgroup)) {
tgroup.vsep <- NULL
for (i in 1:length(tgroup)) {
line.tgroup <- unlist(interleave(as.list(tgroup[[i]]), lapply(n.tgroup[[i]], function(x) rep("", x-1))))
if (include.rownames) {
line.tgroup <- c("", line.tgroup)
}
x <- rbind(line.tgroup, x)
tvsep <- c(unlist(interleave(as.list(rep("|", length(tgroup[[i]]))), lapply(n.tgroup[[i]], function(x) rep(" ", x-1)))), "|")
tgroup.vsep <- rbind(tvsep, tgroup.vsep)
}
}
if (!is.null(bgroup)) {
bgroup.vsep <- NULL
for (i in 1:length(bgroup)) {
line.bgroup <- unlist(interleave(as.list(bgroup[[i]]), lapply(n.bgroup[[i]], function(x) rep("", x-1))))
if (include.rownames) {
line.bgroup <- c("", line.bgroup)
}
x <- rbind(x, line.bgroup)
bvsep <- c(unlist(interleave(as.list(rep("|", length(bgroup[[i]]))), lapply(n.bgroup[[i]], function(x) rep(" ", x-1)))), "|")
bgroup.vsep <- rbind(bgroup.vsep, bvsep)
}
}
if (!is.null(lgroup)) {
lgroup.hsep <- NULL
for (i in 1:length(lgroup)) {
line.lgroup <- unlist(interleave(as.list(lgroup[[i]]), lapply(n.lgroup[[i]], function(x) rep("", x-1))))
line.lgroup <- c(rep("", include.colnames + length(tgroup)), line.lgroup)
line.lgroup <- c(line.lgroup, rep("", length(bgroup)))
x <- cbind(line.lgroup, x)
lhsep <- c(unlist(interleave(as.list(rep("-", length(lgroup[[i]]))), lapply(n.lgroup[[i]], function(x) rep(" ", x-1)))), "-")
lgroup.hsep <- cbind(lhsep, lgroup.hsep)
}
}
if (!is.null(rgroup)) {
rgroup.hsep <- NULL
for (i in 1:length(rgroup)) {
line.rgroup <- unlist(interleave(as.list(rgroup[[i]]), lapply(n.rgroup[[i]], function(x) rep("", x-1))))
line.rgroup <- c(rep("", include.colnames + length(tgroup)), line.rgroup)
line.rgroup <- c(line.rgroup, rep("", length(bgroup)))
x <- cbind(x, line.rgroup)
rhsep <- c(unlist(interleave(as.list(rep("-", length(rgroup[[i]]))), lapply(n.rgroup[[i]], function(x) rep(" ", x-1)))), "-")
rgroup.hsep <- cbind(rgroup.hsep, rhsep)
}
}
vsep <- expand("|", nrowx+length(tgroup)+length(bgroup), ncolx+1+length(lgroup) + length(rgroup))
if (!is.null(tgroup)) {
vsep[1:length(tgroup), (length(lgroup)+include.rownames+1):(ncol(vsep)-length(rgroup))] <- tgroup.vsep
}
if (!is.null(bgroup)) {
vsep[(length(tgroup)+nrowx+1):(length(tgroup)+nrowx+length(bgroup)), (length(lgroup)+include.rownames+1):(ncol(vsep)-length(rgroup))] <- bgroup.vsep
}
if ((length(lgroup)+include.rownames >= 1) & (length(tgroup)+include.colnames >= 1)) {
topleft <- matrix(" ", length(tgroup)+include.colnames, length(lgroup)+include.rownames)
topleft[, 1] <- "|"
vsep[1:nrow(topleft), 1:ncol(topleft)] <- topleft
}
if ((length(lgroup)+include.rownames >=1) & (length(bgroup) >= 1)) {
bottomleft <- matrix(" ", length(bgroup), length(lgroup)+include.rownames)
bottomleft[, 1] <- "|"
vsep[(nrow(vsep)-length(bgroup)+1):(nrow(vsep)), 1:ncol(bottomleft)] <- bottomleft
}
if ((length(rgroup) >= 1) & (include.colnames+length(tgroup) >= 1)) {
topright <- matrix(" ", length(tgroup)+include.colnames, length(rgroup))
topright[, ncol(topright)] <- "|"
vsep[1:nrow(topright), (ncol(vsep)-length(rgroup)+1):ncol(vsep)] <- topright
}
if ((length(rgroup) >=1 ) & (length(bgroup) >= 1)) {
bottomright <- matrix(" ", length(bgroup), length(rgroup))
bottomright[, ncol(bottomright)] <- "|"
vsep[(nrow(vsep)-nrow(bottomright)+1):nrow(vsep), (ncol(vsep)-length(rgroup)+1):ncol(vsep)] <- bottomright
}
hsep <- expand("-", nrowx+1+length(tgroup)+length(bgroup), ncolx+length(lgroup)+length(rgroup))
if (!is.null(lgroup)) {
hsep[(length(tgroup)+include.colnames+1):(nrow(hsep)-length(bgroup)), 1:length(lgroup)] <- lgroup.hsep
}
if (!is.null(rgroup)) {
hsep[(length(tgroup)+include.colnames+1):(nrow(hsep)-length(bgroup)), (ncol(hsep)-length(rgroup)+1):(ncol(hsep))] <- rgroup.hsep
}
if ((length(lgroup)+include.rownames >= 1) & (length(tgroup)+include.colnames >= 1)) {
topleft <- matrix(" ", length(tgroup)+include.colnames, length(lgroup)+include.rownames)
topleft[1, ] <- "-"
hsep[1:nrow(topleft), 1:ncol(topleft)] <- topleft
}
if ((length(lgroup)+include.rownames >= 1)&(length(bgroup) >= 1)) {
bottomleft <- matrix(" ", length(bgroup), length(lgroup)+include.rownames)
bottomleft[nrow(bottomleft), ] <- "-"
hsep[(nrow(hsep)-length(bgroup)+1):(nrow(hsep)), 1:ncol(bottomleft)] <- bottomleft
}
if ((length(rgroup) >= 1) & (include.colnames+length(tgroup) >= 1)) {
topright <- matrix(" ", length(tgroup)+include.colnames, length(rgroup))
topright[1, ] <- "-"
hsep[1:nrow(topright), (ncol(hsep)-length(rgroup)+1):ncol(hsep)] <- topright
}
if ((length(rgroup) >= 1) & (length(bgroup) >= 1)) {
bottomright <- matrix(" ", length(bgroup), length(rgroup))
bottomright[nrow(bottomright), ] <- "-"
hsep[(nrow(hsep)-nrow(bottomright)+1):nrow(hsep), (ncol(hsep)-length(rgroup)+1):ncol(hsep)] <- bottomright
}
csep <- matrix("+", nrowx+1+length(tgroup)+length(bgroup), ncolx+length(lgroup)+length(rgroup)+1)
if ((length(lgroup)+include.rownames >= 1) & (length(tgroup)+include.colnames >= 1)) {
topleft <- matrix(" ", length(tgroup)+include.colnames, length(lgroup)+include.rownames)
topleft[1, ] <- "+"
topleft[, 1] <- "+"
csep[1:nrow(topleft), 1:ncol(topleft)] <- topleft
}
if ((length(lgroup)+include.rownames >=1) & (length(bgroup) >= 1)) {
bottomleft <- matrix(" ", length(bgroup), length(lgroup)+include.rownames)
bottomleft[nrow(bottomleft), ] <- "+"
bottomleft[, 1] <- "+"
csep[(nrow(csep)-length(bgroup)+1):(nrow(csep)), 1:ncol(bottomleft)] <- bottomleft
}
if ((length(rgroup) >= 1) & (include.colnames+length(tgroup) >= 1)) {
topright <- matrix(" ", length(tgroup)+include.colnames, length(rgroup))
topright[1, ] <- "+"
topright[, ncol(topright)] <- "+"
csep[1:nrow(topright), (ncol(csep)-length(rgroup)+1):ncol(csep)] <- topright
}
if ((length(rgroup) >= 1) & (length(bgroup) >= 1)) {
bottomright <- matrix(" ", length(bgroup), length(rgroup))
bottomright[nrow(bottomright), ] <- "+"
bottomright[, ncol(bottomright)] <- "+"
csep[(nrow(hsep)-nrow(bottomright)+1):nrow(csep), (ncol(csep)-length(rgroup)+1):ncol(csep)] <- bottomright
}
if (header) {
header <- min(c(header+length(tgroup), nrowx+length(tgroup)))+1
hsep[header,] <- gsub("-", "=", hsep[header,])
}
results <- print.character.matrix(x, vsep = vsep, csep = csep, hsep = hsep, print = FALSE)
cat(header.rest(caption = caption, caption.level = caption.level), sep = "\n")
cat(results, sep = "\n")
}
show.rest.list <- function(x, caption = NULL, caption.level = NULL, list.type = "bullet", ...) {
if (list.type == "bullet") mark <- rep("*", length(x))
if (list.type == "number") mark <- rep("
if (list.type == "none") mark <- rep("", length(x))
if (list.type == "label") {
if (is.null(names(x))) {
namesx <- paste("[[", 1:length(x), "]]", sep = "")
} else {
namesx <- names(x)
}
mark <- paste(namesx, "\n ", sep = "")
}
y <- gsub("(^\t*)(.*)", "\\1", x)
z <- NULL
for (i in 2:length(y))
z <- c(z, ifelse(y[i] != y[i-1], i-1, NA))
cat(header.rest(caption = caption, caption.level = caption.level), sep = "\n")
for (i in 1:length(x)) {
tmp <- x[[i]]
if (list.type == "label") tmp <- sub("^\t*", "", tmp)
tmp <- gsub('\t|(*COMMIT)(*FAIL)', " ", tmp, perl = TRUE)
tmp <- sub("(^ *)", paste("\\1", mark[i], " ", sep = ""), tmp)
cat(tmp, "\n")
if (i %in% z)
cat("\n")
}
}
|
print.summary.spbp.mle <-
function(x, digits = max(getOption('digits')-4, 3),
signif.stars = getOption("show.signif.stars"), ...) {
if (!is.null(x$call)) {
cat("Call:\n")
dput(x$call)
cat("\n")
}
savedig <- options(digits = digits)
on.exit(options(savedig))
cat(" n=", x$n)
if (!is.null(x$nevent)) cat(", number of events=", x$nevent, "\n")
else cat("\n")
if (nrow(x$coef)==0) {
cat ("Null model\n")
return()
}
if(!is.null(x$coefficients)) {
cat("\n")
printCoefmat(x$coefficients, digits = digits,
signif.stars = signif.stars, ...)
}
if(!is.null(x$conf.int)) {
cat("\n")
print(x$conf.int)
}
cat("\n")
pdig <- max(1, getOption("digits")-4)
cat("Likelihood ratio test= ", format(round(x$logtest["test"], 2)), " on ",
x$logtest["df"], " df,", " p=",
format.pval(x$logtest["pvalue"], digits=pdig),
"\n", sep = "")
cat("Wald test = ", format(round(x$waldtest["test"], 2)), " on ",
x$waldtest["df"], " df,", " p=",
format.pval(x$waldtest["pvalue"], digits=pdig),
"\n", sep = "")
invisible()
}
|
"lichen"
|
regplot.rma <- function(x, mod, pred=TRUE, ci=TRUE, pi=FALSE, shade=TRUE,
xlim, ylim, predlim, olim, xlab, ylab, at, digits=2L,
transf, atransf, targs, level=x$level,
pch=21, psize, plim=c(0.5,3), col="black", bg="darkgray",
grid=FALSE, refline, label=FALSE, offset=c(1,1), labsize=1,
lcol, lwd, lty, legend=FALSE, xvals, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
.chkclass(class(x), must="rma", notav=c("rma.mh","rma.peto"))
if (x$int.only)
stop(mstyle$stop("Plot not applicable to intercept-only models."))
na.act <- getOption("na.action")
on.exit(options(na.action=na.act), add=TRUE)
if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass")))
stop(mstyle$stop("Unknown 'na.action' specified under options()."))
if (missing(transf))
transf <- FALSE
if (missing(atransf))
atransf <- FALSE
transf.char <- deparse(transf)
atransf.char <- deparse(atransf)
if (is.function(transf) && is.function(atransf))
stop(mstyle$stop("Use either 'transf' or 'atransf' to specify a transformation (not both)."))
if (missing(targs))
targs <- NULL
if (missing(ylab))
ylab <- .setlab(x$measure, transf.char, atransf.char, gentype=1, short=FALSE)
if (missing(at))
at <- NULL
if (missing(psize))
psize <- NULL
if (missing(label))
label <- NULL
if (is.logical(grid))
gridcol <- "gray"
if (is.character(grid)) {
gridcol <- grid
grid <- TRUE
}
if (is.logical(shade))
shadecol <- c("gray85", "gray95")
if (is.character(shade)) {
if (length(shade) == 1L)
shade <- c(shade, shade)
shadecol <- shade
shade <- TRUE
}
if (inherits(pred, "list.rma")) {
addpred <- TRUE
if (missing(xvals))
stop(mstyle$stop("Need to specify the 'xvals' argument."))
if (length(xvals) != length(pred$pred))
stop(mstyle$stop(paste0("Length of the 'xvals' argument (", length(xvals), ") does not correspond to the number of predicted values (", length(pred$pred), ").")))
} else {
addpred <- pred
}
if (missing(refline))
refline <- NA
if (missing(lcol)) {
lcol <- c("black", "black", "black", "gray40")
} else {
if (length(lcol) == 1L)
lcol <- rep(lcol, 4L)
if (length(lcol) == 2L)
lcol <- c(lcol[c(1,2,2)], "gray40")
if (length(lcol) == 3L)
lcol <- c(lcol, "gray40")
}
if (missing(lty)) {
lty <- c("solid", "dashed", "dotted", "solid")
} else {
if (length(lty) == 1L)
lty <- rep(lty, 4L)
if (length(lty) == 2L)
lty <- c(lty[c(1,2,2)], "solid")
if (length(lty) == 3L)
lty <- c(lty, "solid")
}
if (missing(lwd)) {
lwd <- c(3,1,1,2)
} else {
if (length(lwd) == 1L)
lwd <- rep(lwd, 4L)
if (length(lwd) == 2L)
lwd <- c(lwd[c(1,2,2)], 2)
if (length(lwd) == 3L)
lwd <- c(lwd, 2)
}
level <- .level(level)
if (missing(mod)) {
if (x$p == 2L && x$int.incl) {
mod <- 2
} else {
stop(mstyle$stop("Need to specify the 'mod' argument."))
}
}
if (length(mod) != 1L)
stop(mstyle$stop("Can only specify a single variable via argument 'mod'."))
if (!(is.character(mod) || is.numeric(mod)))
stop(mstyle$stop("Argument 'mod' must either be a character string or a scalar."))
if (is.character(mod)) {
mod.pos <- charmatch(mod, colnames(x$X))
if (is.na(mod.pos))
stop(mstyle$stop("Argument 'mod' must be the name of a moderator variable in the model."))
if (mod.pos == 0L)
stop(mstyle$stop("No ambiguous match found for variable name specified via 'mod' argument."))
} else {
mod.pos <- round(mod)
if (mod.pos < 1 | mod.pos > x$p)
stop(mstyle$stop("Specified position of 'mod' variable does not exist in the model."))
}
yi <- c(x$yi.f)
vi <- x$vi.f
X <- x$X.f
slab <- x$slab
ids <- x$ids
options(na.action = "na.pass")
weights <- try(weights(x), silent=TRUE)
if (inherits(weights, "try-error"))
weights <- rep(1, x$k.f)
options(na.action = na.act)
if (length(pch) == 1L)
pch <- rep(pch, x$k.all)
if (length(pch) != x$k.all)
stop(mstyle$stop(paste0("Length of the 'pch' argument (", length(pch), ") does not correspond to the size of the original dataset (", x$k.all, ").")))
if (!is.null(x$subset))
pch <- pch[x$subset]
psize.char <- FALSE
if (!is.null(psize)) {
if (is.character(psize)) {
psize <- match.arg(psize, c("seinv", "vinv"))
if (psize == "seinv") {
psize <- 1 / sqrt(vi)
} else {
psize <- 1 / vi
}
psize.char <- TRUE
} else {
if (length(psize) == 1L)
psize <- rep(psize, x$k.all)
if (length(psize) != x$k.all)
stop(mstyle$stop(paste0("Length of the 'psize' argument (", length(psize), ") does not correspond to the size of the original dataset (", x$k.all, ").")))
if (!is.null(x$subset))
psize <- psize[x$subset]
}
}
if (length(col) == 1L)
col <- rep(col, x$k.all)
if (length(col) != x$k.all)
stop(mstyle$stop(paste0("Length of the 'col' argument (", length(col), ") does not correspond to the size of the original dataset (", x$k.all, ").")))
if (!is.null(x$subset))
col <- col[x$subset]
if (length(bg) == 1L)
bg <- rep(bg, x$k.all)
if (length(bg) != x$k.all)
stop(mstyle$stop(paste0("Length of the 'bg' argument (", length(bg), ") does not correspond to the size of the original dataset (", x$k.all, ").")))
if (!is.null(x$subset))
bg <- bg[x$subset]
if (!is.null(label)) {
if (is.character(label)) {
label <- match.arg(label, c("all", "ciout", "piout"))
if (label == "all") {
label <- rep(TRUE, x$k.all)
if (!is.null(x$subset))
label <- label[x$subset]
}
} else if (is.logical(label)) {
if (!is.logical(label))
stop(mstyle$stop("Argument 'label' must be a logical vector (or a single character string)."))
if (length(label) == 1L)
label <- rep(label, x$k.all)
if (length(label) != x$k.all)
stop(mstyle$stop(paste0("Length of the 'label' argument (", length(label), ") does not correspond to the size of the original dataset (", x$k.all, ").")))
if (!is.null(x$subset))
label <- label[x$subset]
} else if (is.numeric(label)) {
label <- round(label)
label <- seq(x$k.all) %in% label
}
}
has.na <- is.na(yi) | is.na(vi) | apply(is.na(X), 1, any)
not.na <- !has.na
if (any(has.na)) {
yi <- yi[not.na]
vi <- vi[not.na]
X <- X[not.na,,drop=FALSE]
slab <- slab[not.na]
ids <- ids[not.na]
weights <- weights[not.na]
pch <- pch[not.na]
psize <- psize[not.na]
col <- col[not.na]
bg <- bg[not.na]
if (!is.character(label))
label <- label[not.na]
}
k <- length(yi)
xi <- X[,mod.pos]
if (inherits(pred, "list.rma")) {
xs <- xvals
ci.lb <- pred$ci.lb
ci.ub <- pred$ci.ub
if (is.null(pred$pi.lb) || anyNA(pred$pi.lb)) {
pi.lb <- pred$ci.lb
pi.ub <- pred$ci.ub
if (pi)
warning(mstyle$warning("Object passed to 'pred' argument does not contain prediction interval information."), call.=FALSE)
pi <- FALSE
} else {
pi.lb <- pred$pi.lb
pi.ub <- pred$pi.ub
}
pred <- pred$pred
if (!is.null(label) && is.character(label) && label %in% c("ciout", "piout")) {
warning(mstyle$stop("Cannot label points based on the confidence/prediction interval when passing an object to 'pred'."))
label <- NULL
}
yi.pred <- NULL
yi.ci.lb <- NULL
yi.ci.ub <- NULL
yi.pi.lb <- NULL
yi.pi.ub <- NULL
} else {
if (!missing(xvals)) {
xs <- xvals
len <- length(xs)
predlim <- range(xs)
} else {
len <- 1000
if (missing(predlim)) {
range.xi <- max(xi) - min(xi)
predlim <- c(min(xi) - .04*range.xi, max(xi) + .04*range.xi)
xs <- seq(predlim[1], predlim[2], length=len)
} else {
if (length(predlim) != 2L)
stop(mstyle$stop("Argument 'predlim' must be of length 2."))
xs <- seq(predlim[1], predlim[2], length=len)
}
}
Xnew <- rbind(colMeans(X))[rep(1,len),,drop=FALSE]
Xnew[,mod.pos] <- xs
if (x$int.incl)
Xnew <- Xnew[,-1,drop=FALSE]
tmp <- predict(x, newmods=Xnew, level=level)
pred <- tmp$pred
ci.lb <- tmp$ci.lb
ci.ub <- tmp$ci.ub
if (is.null(tmp$pi.lb) || anyNA(tmp$pi.lb)) {
pi.lb <- ci.lb
pi.ub <- ci.ub
if (pi)
warning(mstyle$warning("Cannot draw prediction interval for the given model."), call.=FALSE)
pi <- FALSE
} else {
pi.lb <- tmp$pi.lb
pi.ub <- tmp$pi.ub
}
Xnew <- rbind(colMeans(X))[rep(1,k),,drop=FALSE]
Xnew[,mod.pos] <- xi
if (x$int.incl)
Xnew <- Xnew[,-1,drop=FALSE]
tmp <- predict(x, newmods=Xnew, level=level)
yi.pred <- tmp$pred
yi.ci.lb <- tmp$ci.lb
yi.ci.ub <- tmp$ci.ub
if (is.null(tmp$pi.lb) || anyNA(tmp$pi.lb)) {
yi.pi.lb <- yi.ci.lb
yi.pi.ub <- yi.ci.ub
if (!is.null(label) && is.character(label) && label == "piout") {
warning(mstyle$warning("Cannot label points based on the prediction interval for the given model."), call.=FALSE)
label <- NULL
}
} else {
yi.pi.lb <- tmp$pi.lb
yi.pi.ub <- tmp$pi.ub
}
}
if (is.function(transf)) {
if (is.null(targs)) {
yi <- sapply(yi, transf)
pred <- sapply(pred, transf)
ci.lb <- sapply(ci.lb, transf)
ci.ub <- sapply(ci.ub, transf)
pi.lb <- sapply(pi.lb, transf)
pi.ub <- sapply(pi.ub, transf)
yi.pred <- sapply(yi.pred, transf)
yi.ci.lb <- sapply(yi.ci.lb, transf)
yi.ci.ub <- sapply(yi.ci.ub, transf)
yi.pi.lb <- sapply(yi.pi.lb, transf)
yi.pi.ub <- sapply(yi.pi.ub, transf)
} else {
yi <- sapply(yi, transf, targs)
pred <- sapply(pred, transf, targs)
ci.lb <- sapply(ci.lb, transf, targs)
ci.ub <- sapply(ci.ub, transf, targs)
pi.lb <- sapply(pi.lb, transf, targs)
pi.ub <- sapply(pi.ub, transf, targs)
yi.pred <- sapply(yi.pred, transf, targs)
yi.ci.lb <- sapply(yi.ci.lb, transf, targs)
yi.ci.ub <- sapply(yi.ci.ub, transf, targs)
yi.pi.lb <- sapply(yi.pi.lb, transf, targs)
yi.pi.ub <- sapply(yi.pi.ub, transf, targs)
}
}
tmp <- .psort(ci.lb, ci.ub)
ci.lb <- tmp[,1]
ci.ub <- tmp[,2]
tmp <- .psort(pi.lb, pi.ub)
pi.lb <- tmp[,1]
pi.ub <- tmp[,2]
if (!missing(olim)) {
if (length(olim) != 2L)
stop(mstyle$stop("Argument 'olim' must be of length 2."))
olim <- sort(olim)
yi[yi < olim[1]] <- olim[1]
yi[yi > olim[2]] <- olim[2]
pred[pred < olim[1]] <- olim[1]
pred[pred > olim[2]] <- olim[2]
ci.lb[ci.lb < olim[1]] <- olim[1]
ci.ub[ci.ub > olim[2]] <- olim[2]
pi.lb[pi.lb < olim[1]] <- olim[1]
pi.ub[pi.ub > olim[2]] <- olim[2]
}
if (is.null(psize) || psize.char) {
if (length(plim) < 2L)
stop(mstyle$stop("Argument 'plim' must be of length 2 or 3."))
if (psize.char) {
wi <- psize
} else {
wi <- sqrt(weights)
}
if (!is.na(plim[1]) && !is.na(plim[2])) {
rng <- max(wi, na.rm=TRUE) - min(wi, na.rm=TRUE)
if (rng <= .Machine$double.eps^0.5) {
psize <- rep(1, k)
} else {
psize <- (wi - min(wi, na.rm=TRUE)) / rng
psize <- (psize * (plim[2] - plim[1])) + plim[1]
}
}
if (is.na(plim[1]) && !is.na(plim[2])) {
psize <- wi / max(wi, na.rm=TRUE) * plim[2]
if (length(plim) == 3L)
psize[psize <= plim[3]] <- plim[3]
}
if (!is.na(plim[1]) && is.na(plim[2])) {
psize <- wi / min(wi, na.rm=TRUE) * plim[1]
if (length(plim) == 3L)
psize[psize >= plim[3]] <- plim[3]
}
if (all(is.na(psize)))
psize <- rep(1, k)
}
if (missing(xlab))
xlab <- colnames(X)[mod.pos]
if (!is.expression(xlab) && xlab == "")
xlab <- "Moderator"
if (missing(xlim)) {
xlim <- range(xi)
} else {
if (length(xlim) != 2L)
stop(mstyle$stop("Argument 'xlim' must be of length 2."))
}
if (missing(ylim)) {
if (pi) {
ylim <- range(c(yi, pi.lb, pi.ub))
} else if (ci) {
ylim <- range(c(yi, ci.lb, ci.ub))
} else {
ylim <- range(yi)
}
} else {
if (length(ylim) != 2L)
stop(mstyle$stop("Argument 'ylim' must be of length 2."))
}
if (!is.null(at)) {
ylim[1] <- min(c(ylim[1], at), na.rm=TRUE)
ylim[2] <- max(c(ylim[2], at), na.rm=TRUE)
}
plot(NA, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, yaxt="n", ...)
if (is.null(at)) {
at <- axTicks(side=2)
} else {
at <- at[at > par("usr")[3]]
at <- at[at < par("usr")[4]]
}
at.lab <- at
if (is.function(atransf)) {
if (is.null(targs)) {
at.lab <- formatC(sapply(at.lab, atransf), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
} else {
at.lab <- formatC(sapply(at.lab, atransf, targs), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
}
} else {
at.lab <- formatC(at.lab, digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
}
axis(side=2, at=at, labels=at.lab, ...)
if (shade) {
if (pi)
polygon(c(xs, rev(xs)), c(pi.lb, rev(pi.ub)), border=NA, col=shadecol[2], ...)
if (ci)
polygon(c(xs, rev(xs)), c(ci.lb, rev(ci.ub)), border=NA, col=shadecol[1], ...)
}
if (ci) {
lines(xs, ci.lb, col=lcol[2], lty=lty[2], lwd=lwd[2], ...)
lines(xs, ci.ub, col=lcol[2], lty=lty[2], lwd=lwd[2], ...)
}
if (pi) {
lines(xs, pi.lb, col=lcol[3], lty=lty[3], lwd=lwd[3], ...)
lines(xs, pi.ub, col=lcol[3], lty=lty[3], lwd=lwd[3], ...)
}
if (.isTRUE(grid))
grid(col=gridcol)
abline(h=refline, col=lcol[4], lty=lty[4], lwd=lwd[4], ...)
if (addpred)
lines(xs, pred, col=lcol[1], lty=lty[1], lwd=lwd[1], ...)
box(...)
order.vec <- order(psize, decreasing=TRUE)
xi.o <- xi[order.vec]
yi.o <- yi[order.vec]
pch.o <- pch[order.vec]
psize.o <- psize[order.vec]
col.o <- col[order.vec]
bg.o <- bg[order.vec]
points(x=xi.o, y=yi.o, pch=pch.o, col=col.o, bg=bg.o, cex=psize.o, ...)
if (!is.null(label)) {
if (!is.null(label) && is.character(label) && label %in% c("ciout", "piout")) {
if (label == "ciout") {
label <- yi < yi.ci.lb | yi > yi.ci.ub
label[xi < predlim[1] | xi > predlim[2]] <- FALSE
} else {
label <- yi < yi.pi.lb | yi > yi.pi.ub
label[xi < predlim[1] | xi > predlim[2]] <- FALSE
}
}
yrange <- ylim[2] - ylim[1]
if (length(offset) == 2L)
offset <- c(offset[1]/100 * yrange, offset[2]/100 * yrange, 1)
if (length(offset) == 1L)
offset <- c(0, offset/100 * yrange, 1)
for (i in which(label)) {
if (isTRUE(yi[i] > yi.pred[i])) {
text(xi[i], yi[i] + offset[1] + offset[2]*psize[i]^offset[3], slab[i], cex=labsize, ...)
} else {
text(xi[i], yi[i] - offset[1] - offset[2]*psize[i]^offset[3], slab[i], cex=labsize, ...)
}
}
} else {
label <- rep(FALSE, k)
}
if (is.logical(legend) && isTRUE(legend))
lpos <- "topright"
if (is.character(legend)) {
lpos <- legend
legend <- TRUE
}
if (legend) {
pch.l <- NULL
col.l <- NULL
bg.l <- NULL
lty.l <- NULL
lwd.l <- NULL
tcol.l <- NULL
ltxt <- NULL
if (length(unique(pch)) == 1L && length(unique(col)) == 1L && length(unique(bg)) == 1L) {
pch.l <- NA
col.l <- NA
bg.l <- NA
lty.l <- "blank"
lwd.l <- NA
tcol.l <- "white"
ltxt <- "Studies"
}
if (addpred) {
pch.l <- c(pch.l, NA)
col.l <- c(col.l, NA)
bg.l <- c(bg.l, NA)
lty.l <- c(lty.l, NA)
lwd.l <- c(lwd.l, NA)
tcol.l <- c(tcol.l, "white")
ltxt <- c(ltxt, "Regression Line")
}
if (ci) {
pch.l <- c(pch.l, 22)
col.l <- c(col.l, lcol[2])
bg.l <- c(bg.l, shadecol[1])
lty.l <- c(lty.l, NA)
lwd.l <- c(lwd.l, 1)
tcol.l <- c(tcol.l, "white")
ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Confidence Interval"))
}
if (pi) {
pch.l <- c(pch.l, 22)
col.l <- c(col.l, lcol[3])
bg.l <- c(bg.l, shadecol[2])
lty.l <- c(lty.l, NA)
lwd.l <- c(lwd.l, 1)
tcol.l <- c(tcol.l, "white")
ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Prediction Interval"))
}
if (length(ltxt) >= 1L)
legend(lpos, inset=.01, bg="white", pch=pch.l, col=col.l, pt.bg=bg.l, lty=lty.l, lwd=lwd.l, text.col=tcol.l, pt.cex=1.5, seg.len=3, legend=ltxt)
pch.l <- NULL
col.l <- NULL
bg.l <- NULL
lty.l <- NULL
lwd.l <- NULL
tcol.l <- NULL
ltxt <- NULL
if (length(unique(pch)) == 1L && length(unique(col)) == 1L && length(unique(bg)) == 1L) {
pch.l <- pch[1]
col.l <- col[1]
bg.l <- bg[1]
lty.l <- "blank"
lwd.l <- 1
tcol.l <- "black"
ltxt <- "Studies"
}
if (addpred) {
pch.l <- c(pch.l, NA)
col.l <- c(col.l, lcol[1])
bg.l <- c(bg.l, NA)
lty.l <- c(lty.l, lty[1])
lwd.l <- c(lwd.l, lwd[1])
tcol.l <- c(tcol.l, "black")
ltxt <- c(ltxt, "Regression Line")
}
if (ci) {
pch.l <- c(pch.l, NA)
col.l <- c(col.l, lcol[2])
bg.l <- c(bg.l, NA)
lty.l <- c(lty.l, lty[2])
lwd.l <- c(lwd.l, lwd[2])
tcol.l <- c(tcol.l, "black")
ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Confidence Interval"))
}
if (pi) {
pch.l <- c(pch.l, NA)
col.l <- c(col.l, lcol[3])
bg.l <- c(bg.l, NA)
lty.l <- c(lty.l, lty[3])
lwd.l <- c(lwd.l, lwd[3])
tcol.l <- c(tcol.l, "black")
ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Prediction Interval"))
}
if (length(ltxt) >= 1L)
legend(lpos, inset=.01, bg=NA, pch=pch.l, col=col.l, pt.bg=bg.l, lty=lty.l, lwd=lwd.l, text.col=tcol.l, pt.cex=1.5, seg.len=3, legend=ltxt)
}
sav <- data.frame(slab, ids, xi, yi, pch, psize, col, bg, label, order=order.vec)
if (length(yi.pred) != 0L)
sav$pred <- yi.pred
attr(sav, "offset") <- offset
attr(sav, "labsize") <- labsize
class(sav) <- "regplot"
invisible(sav)
}
|
call.spread = function(k1, k2, c1, c2, llimit = 20, ulimit = 20){
if(k1<k2){
print('This is a Bull Call Spread because excercise price of long call (k1) is less than excercise price of short call (k2)')
}else{'This is a Bear Call Spread because excercise price of long call (k1) is greater than excercise price of short call (k2)'}
stock_price_at_expiration = round((k1 - llimit)):round((ulimit + k1))
long_call = (map_dbl(round((k1 - llimit)):round((ulimit + k1)), .f = ~max(.x - k1,0))) - c1
short_call = (-1* map_dbl(round((k1 - llimit)):round((ulimit + k1)), .f = ~max(.x - k2,0))) + c2
profit_loss = long_call + short_call
df = data.frame(stock_price_at_expiration, long_call, short_call, profit_loss)
p1 = ggplot(data = df) +
geom_line(aes(x = stock_price_at_expiration, y = long_call, colour = 'long_call')) +
geom_line(aes(x = stock_price_at_expiration, y = short_call, colour = 'short_call')) +
geom_line(aes(x = stock_price_at_expiration, y = profit_loss, colour = 'profit_loss')) +
labs(x = 'stock price at expiration', y = 'profit/loss', title = 'Bull/Bear Call Spread Plot', color = 'Option contract') +
scale_colour_manual('', breaks = c('long_call', 'short_call', 'profit_loss'), values = c('blue', 'red', 'black'))
print(df)
print(ggplotly(p1))
}
|
X <- c(1L, 3L, 5L, 7L, 9L, 15.3)
mean_X <- mean(X)
|
write_output_yml <- function(path) {
output_yml <- ymlthis::yml_output(
.yml = ymlthis::yml_empty(),
bookdown::gitbook(
lib_dir = "assets",
split_by = "chapter",
config = list(download = "pdf")
),
bookdown::pdf_book(
keep_tex = TRUE,
includes = ymlthis::includes2(in_header = "preamble.tex")
)
)
options(ymlthis.remove_blank_line = TRUE)
ymlthis::use_output_yml(.yml = output_yml, path = path, quiet = TRUE)
options(ymlthis.remove_blank_line = FALSE)
}
|
get_trinoploid_1n_est <- function(.filt_peak_sizes){
trinploids <- .filt_peak_sizes$minor_variant_cov_rounded == 0.33
if(any(trinploids)){
triplod_1n_guess <- min(.filt_peak_sizes$pair_cov[trinploids]) / 3
genome_counts_by_trip_1n_est <- round(.filt_peak_sizes$pair_cov / triplod_1n_guess)
if(sum(genome_counts_by_trip_1n_est == 3) == 1){
return(triplod_1n_guess)
}
}
return(NA)
}
|
XZ_BSPLINE.f <- function(x, knt, ord, ...){
BS <- BSplines(knots = knt, ord = ord, der = 0, x = x)
BS <- BS[, -ncol(BS), drop=F]
return(BS)
}
|
plot_histograms <- function(.minor_variant_rel_cov, .total_pair_cov, .ymax, .smudge_summary,
.nbins, .fig_title = NA, .cex = 1.4, .col = NA){
to_filter <- .total_pair_cov < .ymax - (.ymax / .nbins)
.total_pair_cov <- .total_pair_cov[to_filter]
.minor_variant_rel_cov <- .minor_variant_rel_cov[to_filter]
h1 <- hist(.minor_variant_rel_cov, breaks = 100, plot = F)
h2 <- hist(.total_pair_cov, breaks = 100, plot = F)
top <- max(h1$counts, h2$counts)
if( is.na(.col) ){
.col <- rgb(0.8352, 0.2431, 0.3098)
}
par(mar=c(0,3.8,1,0))
barplot(h1$counts, axes=F, ylim=c(0, top), space=0, col = .col)
if(!(is.na(.fig_title))){
mtext(bquote(italic(.(.fig_title))), side=3, adj=0, line=-3, cex = .cex + 0.2)
}
if ( .smudge_summary$genome_ploidy < 9){
ploidytext <- switch(.smudge_summary$genome_ploidy - 1,
p2 = 'diploid',
p3 = 'triploid',
p4 = 'tetraploid',
p5 = 'pentaploid',
p6 = 'hexaploid',
p7 = 'heptaploid',
p8 = 'octoploid')
} else {
ploidytext <- paste0(.smudge_summary$genome_ploidy, '-ploid')
}
if(!(is.na(.smudge_summary$genome_ploidy))){
mtext(paste('proposed', ploidytext), side=3, adj=0.05, line=-5, cex = .cex - 0.2)
}
par(mar=c(3.8,0,0.5,1))
barplot(h2$counts, axes=F, xlim=c(0, top), space=0, col = .col, horiz = T)
legend('bottomright', bty = 'n', paste('1n = ', round(.smudge_summary$n)), cex = .cex - 0.1)
.peak_sizes <- .smudge_summary$peak_sizes[,c(11,3)]
colnames(.peak_sizes) <- c('peak', 'size')
to_remove <- sapply(.peak_sizes[,1], nchar) > 6
.peak_sizes <- .peak_sizes[!to_remove, ]
if( any(to_remove) ){
.peak_sizes <- rbind(.peak_sizes, data.frame(peak = 'others', 'size' = 1 - sum(.peak_sizes[,2])) )
}
if(! any(is.na(.peak_sizes))){
legend('topleft', bty = 'n', .peak_sizes[,1], cex = .cex - 0.2)
legend('topright', bty = 'n', legend = round(.peak_sizes[,2], 2), cex = .cex - 0.2)
}
}
|
highlight_html_cells <- function(input, output, tags, update_css = TRUE,
browse = TRUE, print = FALSE) {
CSSid <- gsub("\\{.+", "", tags)
CSSid <- gsub("^[\\s+]|\\s+$", "", CSSid)
CSSidPaste <- gsub("
CSSid2 <- paste(" ", CSSid, sep = "")
ids <- paste("<td id='", CSSidPaste, "'", sep = "")
for(i in seq_along(CSSid)){
locations <- grep(CSSid[i], input)
input[locations] <- gsub("<td", ids[i], input[locations])
input[locations] <- gsub(CSSid2[i], "", input[locations], fixed = TRUE)
}
if(update_css){
input <- update_css(input, tags)
}
if(print) {
input
} else {
write(input, file = output)
if(browse) {
browseURL(output)
}
}
}
highlight_html_text <- function(input, output, tags, update_css = TRUE,
browse = TRUE, print = FALSE){
CSSid <- gsub("\\{.+", "", tags)
CSSid <- gsub("^[\\s+]|\\s+$", "", CSSid)
CSSidPaste <- gsub("
CSSid2 <- paste(" ", CSSid, sep = "")
ids <- paste("<span id='", CSSidPaste, "'>", sep = "")
for(i in seq_along(CSSid)){
locations <- grep(CSSid[i], input)
input[locations] <- gsub(paste("\\{", CSSid[i], sep = ''), ids[i], input[locations])
input[locations] <- gsub("\\}", "</span>", input[locations])
}
if(update_css){
input <- update_css(input, tags)
}
if(print) {
input
} else {
write(input, file = output)
if(browse) {
browseURL(output)
}
}
}
|
context("cf_query")
test_that("cf_query", {
skip_on_cran()
tt = cf_query(cf_user("public"), cf_datatype(5, 2, 1), cf_station(),
"2012-01-01 00", "2012-01-02 00")
expect_is(tt, "cfSunshine")
expect_is(tt$Station, "factor")
expect_is(tt$`Date(local)`, "POSIXct")
expect_is(tt$`Amount(MJ/m2)`, "numeric")
expect_is(tt$`Period(Hrs)`, "integer")
expect_is(tt$Type, "character")
expect_is(tt$Freq, "character")
})
|
library(testthat)
library(cellassign)
test_check("cellassign")
|
context("upload sheets")
activate_test_token()
test_that("Nonexistent or wrong-extension files throw error", {
expect_error(gs_upload("I dont exist.csv"), "does not exist")
expect_error(gs_upload("test-gs-upload.R"),
"Cannot convert file with this extension")
})
test_that("Different file formats can be uploaded", {
files_to_upload <-
paste("mini-gap", c("xlsx", "tsv", "csv", "txt", "ods"), sep = ".")
upload_titles <- p_(files_to_upload)
tmp <- mapply(gs_upload,
file = system.file("mini-gap",
files_to_upload, package = "googlesheets"),
sheet_title = upload_titles, SIMPLIFY = FALSE)
Sys.sleep(1)
expect_true(all(vapply(tmp, class, character(2))[1, ] == "googlesheet"))
expect_equivalent(vapply(tmp, function(x) x$n_ws,integer(1)),
c(5, 1, 1, 1, 5))
Sys.sleep(1)
ss_df <- gs_ls()
expect_true(all(upload_titles %in% ss_df$sheet_title))
})
test_that("Overwrite actually overwrites an existing file", {
before <- dplyr::data_frame(x = "before")
after <- dplyr::data_frame(x = "after")
on.exit(file.remove(c("before.csv", "after.csv")))
readr::write_csv(before, "before.csv")
readr::write_csv(after, "after.csv")
target_sheet <- p_("overwrite_test_sheet")
ss <- gs_upload("before.csv", target_sheet)
Sys.sleep(1)
res <- gs_read(ss)
expect_identical(res$x[1], "before")
ss <- gs_upload("after.csv", target_sheet, overwrite = TRUE)
Sys.sleep(1)
res <- gs_read(ss)
expect_identical(res$x[1], "after")
})
gs_grepdel(TEST, verbose = FALSE)
gs_deauth(verbose = FALSE)
|
context("test-leafgl-popup")
library(leaflet)
library(jsonify)
library(sf)
test_that("popup-points-character", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = "state",
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), breweries91$state)
rm(m)
sfpoints <- sf::st_as_sf(breweries91)
m <- leaflet() %>%
addGlPoints(data = st_sfc(st_geometry(sfpoints)),
popup = sfpoints$state,
group = "grp")
expect_is(m, "leaflet")
expect_is(m$x$calls[[1]]$args[[2]], "json")
expect_true(validate_json(m$x$calls[[1]]$args[[2]]))
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = breweries91$state,
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), breweries91$state)
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = c("state", "address"),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = "Text 1",
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(breweries91)))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = c("Text 1", "Text 2"),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]),
rep(c("Text 1","Text 2"), nrow(breweries91))[1:nrow(breweries91)])
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = rep("Text 1", nrow(breweries91)),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(breweries91)))
})
test_that("popup-points-table", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.data.frame(breweries91),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.data.frame(breweries91),
group = "grp",
src = TRUE)
expect_is(m, "leaflet")
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.data.frame(breweries91)[1:4,],
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.matrix(as.data.frame(breweries91)),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-points-spatial", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = breweries91,
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = breweries91,
group = "grp",
src = TRUE)
expect_is(m, "leaflet")
library(sf)
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = st_as_sf(breweries91),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-points-formula", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = ~sprintf("<b>State</b>: %s<br>
<b>Address</b>: %s<br>
<b>Brauerei</b>: %s,",
state, address, brewery),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = ~sprintf("<b>State</b>: %s<br>
<b>Address</b>: %s<br>
<b>Brauerei</b>: %s,",
state, address, brewery),
group = "grp",
src = TRUE)
expect_is(m, "leaflet")
})
test_that("popup-points-list", {
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.list(data.frame(city="Berlin",
district=5029, stringsAsFactors = F)),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup=as.list(data.frame(city=c("Vienna","Berlin"),
district=c(1010,40302),
stringsAsFactors = F)),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = as.list(as.data.frame(breweries91)),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-points-json", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = jsonify::to_json(as.list(as.data.frame(breweries91[,1]))),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = jsonify::to_json(as.data.frame(breweries91[,1])),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = jsonify::to_json(as.list(as.data.frame(breweries91[,1:5]))),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = jsonify::to_json(as.data.frame(breweries91[1,])),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = jsonify::to_json(as.list(as.data.frame(breweries91))),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-points-logical", {
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = TRUE,
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = TRUE,
group = "grp",
src = TRUE)
expect_is(m, "leaflet")
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = FALSE,
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_true(m$x$calls[[2]]$args[[3]] == "{}")
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = NULL,
group = "grp")
expect_is(m, "leaflet")
expect_true(is.null(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-points-shiny.tag", {
library(shiny)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = shiny::icon("car"),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = shiny::icon("car"),
group = "grp", src = TRUE))
expect_is(m, "leaflet")
})
test_that("popup-points-default", {
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = Sys.time(),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = seq.POSIXt(Sys.time(), Sys.time()+1000,
length.out = nrow(breweries91)),
group = "grp")
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPoints(data = breweries91,
popup = Sys.Date(),
group = "grp"))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
storms = suppressWarnings(st_cast(st_as_sf(atlStorms2005), "LINESTRING"))
storms = st_transform(storms, 4326)
test_that("popup-lines-character", {
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = "Name",
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), as.character(storms$Name))
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = storms$Name,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), as.character(storms$Name))
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = c("Name", "MaxWind"),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = "Text 1",
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(storms)))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = c("Text 1", "Text 2"),
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]),
rep(c("Text 1","Text 2"), nrow(storms))[1:nrow(storms)])
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = rep("Text 1", nrow(storms)),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(storms)))
})
test_that("popup-lines-table", {
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = as.data.frame(storms),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = as.data.frame(storms)[1:4,],
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = as.matrix(as.data.frame(storms)),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-lines-spatial", {
popups <- suppressWarnings(sf::as_Spatial(storms))
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = popups,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
library(sf)
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = storms,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-lines-formula", {
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = ~sprintf("<b>State</b>: %s<br>
<b>Address</b>: %s<br>
<b>Brauerei</b>: %s,",
MinPress, MaxWind, Name),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-lines-logical", {
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = TRUE,
opacity = 1)
expect_is(m, "leaflet")
expect_true(m$x$calls[[2]]$args[[3]])
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = FALSE,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_true(m$x$calls[[2]]$args[[3]] == "{}")
m <- leaflet() %>% addTiles() %>%
addGlPolylines(data = storms,
popup = NULL,
opacity = 1)
expect_is(m, "leaflet")
expect_true(is.null(m$x$calls[[2]]$args[[3]]))
})
gadm = suppressWarnings(st_cast(st_as_sf(gadmCHE), "POLYGON"))
test_that("popup-polygon-character", {
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = "HASC_1",
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), gadm$HASC_1)
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = gadm$HASC_1,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), gadm$HASC_1)
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = c("HASC_1", "NAME_0"),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = "Text 1",
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(gadm)))
rm(m)
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = c("Text 1", "Text 2"),
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]),
rep(c("Text 1","Text 2"), nrow(gadm))[1:nrow(gadm)])
rm(m)
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = rep("Text 1", nrow(gadm)),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_identical(from_json(m$x$calls[[2]]$args[[3]]), rep("Text 1", nrow(gadm)))
})
test_that("popup-polygon-table", {
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = as.data.frame(gadm),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- expect_warning(leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = as.data.frame(gadm)[1:4,],
opacity = 1))
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = as.matrix(as.data.frame(gadm)),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-polygon-spatial", {
popups <- suppressWarnings(sf::as_Spatial(gadm))
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = popups,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
library(sf)
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = gadm,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-polygon-formula", {
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = ~sprintf("<b>State</b>: %s<br>
<b>Address</b>: %s<br>
<b>Brauerei</b>: %s,",
NAME_0, NAME_1, HASC_1),
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
})
test_that("popup-polygon-logical", {
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = TRUE,
opacity = 1)
expect_is(m, "leaflet")
expect_true(m$x$calls[[2]]$args[[3]])
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = FALSE,
opacity = 1)
expect_is(m, "leaflet")
expect_true(jsonify::validate_json(m$x$calls[[2]]$args[[3]]))
expect_true(m$x$calls[[2]]$args[[3]] == "{}")
m <- leaflet() %>% addTiles() %>%
addGlPolygons(data = gadm,
popup = NULL,
opacity = 1)
expect_is(m, "leaflet")
expect_true(is.null(m$x$calls[[2]]$args[[3]]))
})
|
register_class("data.frame")
ts_data.frame_dts <- function(x) {
as.data.frame(ts_data.table(x))
}
ts_dts.data.frame <- function(x) {
ts_dts(as.data.table(x))
}
ts_data.frame <- function(x) {
stopifnot(ts_boxable(x))
if (relevant_class(x) == "data.frame") {
return(x)
}
ts_data.frame_dts(ts_dts(x))
}
ts_df <- function(x) {
ts_data.frame(x)
}
|
fptpdf <- function(z,x0max,chi,v,sdv) {
if (x0max==0) return( (chi/z^2)*dnorm(chi/z,mean=v,sd=sdv))
zs=z*sdv ; zu=z*v ; chiminuszu=chi-zu
chizu=chiminuszu/zs ; chizumax=(chiminuszu-x0max)/zs
(v*(pnorm(chizu)-pnorm(chizumax)) +
sdv*(dnorm(chizumax)-dnorm(chizu)))/x0max
}
fptcdf <- function(z,x0max,chi,v,sdv) {
if (x0max==0) return(pnorm(chi/z,mean=v,sd=sdv,lower.tail=F))
zs=z*sdv ; zu=z*v ; chiminuszu=chi-zu ; xx=chiminuszu-x0max
chizu=chiminuszu/zs ; chizumax=xx/zs
tmp1=zs*(dnorm(chizumax)-dnorm(chizu))
tmp2=xx*pnorm(chizumax)-chiminuszu*pnorm(chizu)
1+(tmp1+tmp2)/x0max
}
mean_v <- 2.4
A <- 1.2
b <- 2.7
t0 <- .2
sd_v <- 1
st0 <- 0
posdrift <- TRUE
pnorm(mean_v/sd_v)
res0 <- ggdmc252:::fptpdf(.3, A, b, mean_v, sd_v, t0, posdrift)
res1 <- ggdmc:::fptpdf(.3, A, b, mean_v, sd_v, t0, posdrift)
res2 <- rtdists:::dlba_norm_core(.3, A, b, t0, mean_v, sd_v)
res3 <- fun(.3, A, b, t0, mean_v, sd_v)
res0
res1
res2
res3
res0[,1]==res1[,1]
A <- .02
b <- .01
mean_v <- c(2.4, 2.2, 1.5)
sd_v <- c(1, 1, 1.5)
t0 <- .01
res0 <- ggdmc252:::fptpdf(0, A, b, mean_v[1], sd_v[1], t0, posdrift)
res1 <- ggdmc:::fptpdf(0, A, b, mean_v[1], sd_v[1], t0, posdrift)
res2 <- fptpdf(0-t0, x0max=A, chi=b, v=mean_v[1], sdv=sd_v[1])
res3 <- rtdists:::dlba_norm_core(0, A, b, t0, mean_v[1], sd_v[1])
res0[,1]
res1[,1]
res2
res3
res0 <- ggdmc252:::fptcdf(0, A, b, mean_v[1], sd_v[1], t0, posdrift)
res1 <- ggdmc:::fptcdf(0, A, b, mean_v[1], sd_v[1], t0, posdrift)
res2 <- fptcdf(0-t0, x0max=A, chi=b, v=mean_v[1], sdv=sd_v[1])
res3 <- rtdists:::plba_norm_core(0, A, b, t0, mean_v[1], sd_v[1])
res0[,1]
res1[,1]
res2
res3
rt <- seq(0, 10, .01)
res0 <- ggdmc252:::fptpdf(rt, A, b, mean_v[1], sd_v[1], t0, posdrift)
res1 <- ggdmc:::fptpdf(rt, A, b, mean_v[1], sd_v[1], t0, posdrift)
res2 <- fptpdf(rt-t0, x0max=A, chi=b, v=mean_v[1], sdv=sd_v[1])
all(res0[,1]==res1[,1])
all(res1[,1]==res2)
all.equal(res0[,1], res1[,1])
all.equal(res1[,1], res2)
head(cbind(res0, res1, res2, rt))
tail(cbind(res0, res1, res2, rt))
rt <- seq(.1, 5, .01)
mean_v <- seq(0, 5, .1)
A <- seq(0, 5, .1)
b <- 2.7
t0 <- .1
sd_v <- 1
for(i in 1:length(mean_v))
{
for(j in 1:length(A))
{
res0 <- ggdmc252:::fptpdf(rt, A[j], b, mean_v[i], sd_v, t0, posdrift)
res1 <- ggdmc:::fptpdf(rt, A[j], b, mean_v[i], sd_v, t0, posdrift)
test <- all(res0[,1]==res1[,1])
if(!test) cat("[", mean_v[i], " ", A[j], " ", b, " ", t0, " ", sd_v,
"]", " results in a different likelihood\n")
}
}
mean_v <- 2.4
A <- 1.2
b <- 2.7
t0 <- .2
sd_v <- 1
st0 <- 0
posdrift <- FALSE
res0 <- ggdmc252:::fptcdf(.6, A, b, mean_v, sd_v, t0, posdrift)
res1 <- ggdmc:::fptcdf(.6, A, b, mean_v, sd_v, t0, posdrift)
res2 <- fptcdf(z=.6-t0, x0max=A, chi=b, v=mean_v, sdv=sd_v)
res0[,1]==res1[,1]
all.equal(res1[,1], res2)
cbind(res1[,1], res2)
rt <- seq(0, 10, .01)
res0 <- ggdmc252:::fptcdf(rt, A, b, mean_v, sd_v, t0, posdrift)
res1 <- ggdmc:::fptcdf(rt, A, b, mean_v, sd_v, t0, posdrift)
res2 <- fptcdf(rt-t0, x0max=A, chi=b, v=mean_v, sdv=sd_v)
all(res0[,1]==res1[,1])
all(res1[,1]==res2)
all.equal(res1[,1], res2)
head(cbind(res0, res1, res2, rt), 22)
tail(cbind(res0, res1, res2, rt))
head(cbind(res0, res1, res2, rt))
tail(cbind(res0, res1, res2, rt))
all.equal(res0[,1], res1[,1])
all.equal(res0[,1], res2)
rt <- seq(.2, .6, .01)
mean_v <- seq(1.2, 5, .01)
for(j in 1:length(mean_v))
{
res0 <- ggdmc252:::fptcdf(rt, A, b, mean_v[j], sd_v, t0, posdrift)
res1 <- ggdmc:::fptcdf(rt, A, b, mean_v[j], sd_v, t0, posdrift)
if( !all.equal(res0[,1], res1[,1]) )
{
cat("Not the same \n")
}
}
|
context("PCC.elimination")
test_that("yields correct output on simple object", {
x = list(
edgelist = structure(c("VL1", "VL1", "VL2", "VL4"),
.Dim = c(2L, 2L)),
conflictsTotal = structure(c(2, 1, 0, 1, 2, 1, 0, 1),
.Dim = c(4L, 2L),
.Dimnames = list(c("VL1", "VL2","VL3", "VL4"),
c("Number of conflicts", "Centrality index"))),
database = matrix(
data = c(
1,1,1,1,
1,2,0,2,
2,1,1,1,
2,2,0,2,
2,3,0,NA
),
ncol = 5,
nrow = 4,
dimnames = list(
c("VL1","VL2","VL3","VL4"),
c("A","B","C","D","E")
)
),
vertexAttributes = structure(
c("overconflicting", "sober", "sober", "red", "green", "green"),
.Dim = c(3L, 2L), .Dimnames = list(c("VL1", "VL2","VL4"), c("label", "color")))
)
class(x) = "pccOverconflicting"
results = matrix(
data = c(
1,1,1,
2,0,2,
1,1,1,
2,0,2,
3,0,NA
),
ncol = 5,
nrow = 3,
dimnames = list(
c("VL2","VL3","VL4"),
c("A","B","C","D","E")
))
expect_equal(PCC.elimination(x), results)
})
|
"ciliarybeat"
|
is_converged <- function(fitted_model,
threshold = 1.05,
parameters = c("sigma", "x", "Z")) {
Rhats <-
fitted_model$monitor[which(grepl(
paste(parameters, collapse = "|"),
rownames(fitted_model$monitor)
) == TRUE), "Rhat"]
max(Rhats, na.rm = TRUE) < threshold
}
|
library(sp)
library(gstat)
data(meuse)
coordinates(meuse) = ~x+y
data(meuse.grid)
gridded(meuse.grid) = ~x+y
mg = meuse.grid
gridded(mg) = FALSE
mg= mg[1500,]
krige(log(zinc)~1,meuse,mg,vgm(1, "Exp", 300, anis=c(0,0.01)),
vdist=FALSE, maxdist=1000,nmax=10)
krige(log(zinc)~1,meuse,mg,vgm(1, "Exp", 300, anis=c(0,0.01)),
vdist=TRUE, maxdist=1000,nmax=10)
|
GuFit <- function (ts, uncert=FALSE, nrep=100, ncores='all', sf=quantile(ts, probs=c(0.05, 0.95), na.rm=TRUE)) {
if (class(index(ts))[1]=='POSIXct') {
doy.vector <- as.numeric(format(index(ts), '%j'))
index(ts) <- doy.vector
}
fit <- FitDoubleLogGu(ts, sf=sf)
residuals <- ts - as.vector(fit$predicted)
sd.res <- sd(residuals, na.rm=TRUE)
res2 <- abs(residuals)
res3 <- res2/max(res2)
sign.res <- sign(residuals)
if (uncert) {
if (ncores=='all') cores <- detectCores() else cores <- ncores
cl <- makeCluster(cores)
registerDoParallel(cl)
coefs <- c(5.246, 0.00441, -0.731)
.pred.fun <- function(coefs, cores, nrep) {
expected.time <- coefs[1] + coefs[2]*nrep + coefs[3]*log(cores)
names(expected.time) <- NULL
return(round(exp(expected.time)/60))
}
min.exp.time <- .pred.fun(coefs, cores, nrep)
print(paste0('estimated computation time (',cores,' cores): ', min.exp.time, ' mins'))
output <- foreach(a=1:nrep, .packages=c('phenopix'), .combine=c) %dopar% {
noise <- runif(length(ts), -sd.res, sd.res)
sign.noise <- sign(noise)
pos.no <- which(sign.res!=sign.noise)
if (length(pos.no)!=0) noise[pos.no] <- -noise[pos.no]
noised <- ts + noise
fit.tmp <- try(FitDoubleLogGu(noised, sf=sf))
if (class(fit.tmp)=='try-error') out.single <- list(predicted=rep(NA, length(ts)), params=rep(NA,9)) else {
out.single <- list(predicted=fit.tmp$predicted, params=fit.tmp$params)
}
}
stopCluster(cl)
pred.pos <- which(names(output)=='predicted')
par.pos <- which(names(output)=='params')
predicted.df <- as.data.frame(output[pred.pos])
names(predicted.df) <- paste0('X',1:length(predicted.df))
predicted.df <- zoo(predicted.df, order.by=index(ts))
params.df <- as.data.frame(output[par.pos])
names(params.df) <- names(predicted.df)
uncertainty.list <- list(predicted=predicted.df, params=params.df)
returned <- list(fit=fit, uncertainty=uncertainty.list)
return(returned)
} else {
returned <- list(fit=fit, uncertainty=NULL)
(return(returned))
}
}
|
ggvis <- function(data = NULL, ..., env = parent.frame()) {
vis <- structure(
list(
marks = list(),
data = list(),
props = list(),
reactives = list(),
scales = list(),
axes = list(),
legends = list(),
controls = list(),
connectors = list(),
handlers = list(),
options = list(),
cur_data = NULL,
cur_props = NULL,
cur_vis = NULL
),
class = "ggvis"
)
vis <- add_data(vis, data, deparse2(substitute(data)))
vis <- add_props(vis, ..., env = env)
vis
}
add_props <- function(vis, ..., .props = NULL, inherit = NULL,
env = parent.frame()) {
if (!is.null(.props)) inherit <- attr(.props, "inherit", TRUE)
inherit <- inherit %||% TRUE
new_props <- props(..., .props = .props, inherit = inherit, env = env)
both_props <- merge_props(cur_props(vis), new_props)
vis$props[[length(vis$props) + 1]] <- both_props
vis$cur_props <- both_props
vis <- register_reactives(vis, extract_reactives(both_props))
vis
}
add_data <- function(vis, data, name = deparse2(substitute(data)),
add_suffix = TRUE) {
if (is.null(data)) return(vis)
if (!shiny::is.reactive(data)) {
static_data <- data
data <- function() static_data
}
if (add_suffix) name <- paste0(name, length(vis$data))
data_id(data) <- name
vis$data[[name]] <- data
vis$cur_data <- data
vis
}
is.ggvis <- function(x) inherits(x, "ggvis")
add_mark <- function(vis, type = NULL, props = NULL, data = NULL,
data_name = "unnamed_data") {
old_data <- vis$cur_data
old_props <- vis$cur_props
if (!is.null(vis$cur_vis)) {
suffix <- paste0(vis$cur_vis, collapse = "-")
props <- lapply(props, function(x) {
if (identical(x$scale, FALSE)) return(x)
x$scale <- paste0(x$scale, suffix)
x
})
}
vis <- add_data(vis, data, data_name)
vis <- add_props(vis, .props = props)
vis <- register_scales_from_props(vis, cur_props(vis))
new_mark <- mark(type, props = cur_props(vis), data = vis$cur_data)
vis <- append_ggvis(vis, "marks", new_mark)
vis$cur_data <- old_data
vis$cur_props <- old_props
vis
}
add_scale <- function(vis, scale, data_domain = TRUE) {
if (data_domain && shiny::is.reactive(scale$domain)) {
vis <- register_reactive(vis, scale$domain)
}
vis <- append_ggvis(vis, "scales", scale)
vis
}
add_options <- function(vis, options, replace = TRUE) {
if (replace) {
vis$options <- merge_vectors(vis$options, options)
} else {
vis$options <- merge_vectors(options, vis$options)
}
vis
}
register_computation <- function(vis, args, name, transform = NULL) {
vis <- register_reactives(vis, args)
if (is.null(transform)) return(vis)
parent_data <- vis$cur_data
id <- paste0(data_id(parent_data), "/", name, length(vis$data))
if (shiny::is.reactive(parent_data) || any_apply(args, shiny::is.reactive)) {
empty <- NULL
new_data <- reactive({
if (is.null(empty)) {
out <- transform(parent_data(), values(args))
empty <<- out[0, , drop = FALSE]
out
} else {
tryCatch(
transform(parent_data(), values(args)),
error = function(e) {
message("Error: ", e$message)
data.frame
}
)
}
})
} else {
cache <- transform(parent_data(), args)
new_data <- function() cache
}
data_id(new_data) <- id
vis$data[[id]] <- new_data
vis$cur_data <- new_data
vis
}
register_reactives <- function(vis, reactives = NULL) {
reactives <- reactives[vapply(reactives, shiny::is.reactive, logical(1))]
for (reactive in reactives) {
vis <- register_reactive(vis, reactive)
}
vis
}
register_reactive <- function(vis, reactive) {
if (identical(attr(reactive, "register"), FALSE)) return(vis)
if (is.null(reactive_id(reactive))) {
reactive_id(reactive) <- rand_id("reactive_")
}
label <- reactive_id(reactive)
if (label %in% names(vis$reactives)) return(vis)
vis$reactives[[label]] <- reactive
if (is.broker(reactive)) {
broker <- attr(reactive, "broker", TRUE)
vis <- register_controls(vis, broker$controls)
vis <- register_connector(vis, broker$connect)
vis <- register_handler(vis, broker$spec)
}
vis
}
register_scales_from_props <- function(vis, props) {
names(props) <- trim_prop_event(names(props))
data <- vis$cur_data
add_scale_from_prop <- function(vis, prop) {
label <- prop_label(prop)
if (label == "" || grepl("_$", label)) {
label <- NULL
}
if (is.prop_band(prop)) {
vis <- add_scale(
vis,
ggvis_scale(property = propname_to_scale(prop$property),
name = prop$scale, points = FALSE, label = label)
)
return(vis)
}
if (is.null(prop$value) || !prop_is_scaled(prop) || is.null(data)) {
return(vis)
}
type <- vector_type(shiny::isolate(prop_value(prop, data())))
domain <- reactive({
data_range(prop_value(prop, data()))
})
attr(domain, "register") <- FALSE
scale_fun <- match.fun(paste0("scale_", type))
vis <- scale_fun(vis, property = prop$property, name = prop$scale,
label = label, domain = domain, override = FALSE)
vis
}
for (i in seq_along(props)) {
vis <- add_scale_from_prop(vis, props[[i]])
}
vis
}
register_controls <- function(vis, controls) {
if (empty(controls)) return(vis)
if (inherits(controls, "shiny.tag")) {
controls <- list(controls)
}
vis$controls <- c(vis$controls, controls)
vis
}
register_connector <- function(vis, connector) {
vis$connectors <- c(vis$connectors, connector)
vis
}
register_handler <- function(vis, handler) {
if(empty(handler)) return(vis)
vis$handlers <- c(vis$handlers, list(handler))
vis
}
show_spec <- function(vis, pieces = NULL) {
out <- as.vega(vis, dynamic = FALSE)
if (!is.null(pieces)) {
out <- out[pieces]
}
json <- jsonlite::toJSON(out, pretty = TRUE, auto_unbox = TRUE, force = TRUE,
null = "null")
cat(gsub("\t", " ", json), "\n", sep = "")
invisible(vis)
}
save_spec <- function(x, path, ...) {
assert_that(is.ggvis(x), is.string(path))
json <- jsonlite::toJSON(as.vega(x, ...), pretty = TRUE, auto_unbox = TRUE,
force = TRUE, null = "null")
writeLines(json, path)
}
view_spec <- function(path, ...) {
contents <- paste0(readLines(path), collapse = "\n")
spec <- jsonlite::fromJSON(contents)
view_static(spec)
}
append_ggvis <- function(vis, field, x) {
i <- vis$cur_vis
if (length(i) == 0) {
vis[[field]] <- c(vis[[field]], list(x))
} else if (length(i) == 1) {
vis$marks[[i]][[field]] <- c(vis$marks[[i]][[field]], list(x))
} else if (length(i) == 2) {
vis$marks[[i[1]]]$marks[[i[2]]][[field]] <-
c(vis$marks[[i[1]]]$marks[[i[2]]][[field]], list(x))
} else {
stop(">3 levels deep? You must be crazy!", call. = FALSE)
}
vis
}
|
library(copula)
library(mev)
d. <- c(2, 3)
d <- sum(d.)
stopifnot(d >= 3)
n <- 1000
rV012 <- function(n, family, tau)
{
stopifnot(n >= 1, is.character(family), length(tau) == 3, tau > 0)
cop <- getAcop(family)
th <- iTau(cop, tau = tau)
V0 <- cop@V0(n, theta = th[1])
V01 <- cop@V01(V0, theta0 = th[1], theta1 = th[2])
V02 <- cop@V01(V0, theta0 = th[1], theta1 = th[3])
cbind(V0 = V0, V01 = V01, V02 = V02)
}
mypairs <- function(x, pch = ".", file = NULL, width = 6, height = 6, ...)
{
opar <- par(pty = "s")
on.exit(par(opar))
doPDF <- !is.null(file)
if(doPDF) {
pdf(file = file, width = width, height = height)
stopifnot(require(crop))
}
pairs2(x, pch = pch, ...)
if(doPDF) dev.off.crop(file)
}
tau <- 0.4
family <- "Clayton"
cop <- getAcop(family)
th <- iTau(cop, tau = tau)
set.seed(271)
V <- cop@V0(n, theta = th)
E <- matrix(rexp(n * d), ncol = d)
U.AC <- cop@psi(E/V, theta = th)
mypairs(U.AC)
tau.EVC <- 0.5
family.EVC <- "Gumbel"
th.EVC <- iTau(getAcop(family.EVC), tau = tau.EVC)
cop.EVC <- onacopulaL(family.EVC, list(th.EVC, 1:d))
set.seed(271)
U.EVC <- rCopula(n, copula = cop.EVC)
E.EVC <- -log(U.EVC)
U.AXC <- cop@psi(E.EVC/V, theta = th)
mypairs(U.AXC)
tau.N <- c(0.2, 0.4, 0.6)
family.N <- "Clayton"
cop.N <- getAcop(family.N)
th.N <- iTau(cop.N, tau = tau.N)
set.seed(271)
V.N <- rV012(n, family = family.N, tau = tau.N)
V0 <- V.N[,"V0"]
V01 <- V.N[,"V01"]
V02 <- V.N[,"V02"]
U.NAC <- cbind(cop.N@psi(E[,1:d.[1]]/V01, theta = th.N[2]),
cop.N@psi(E[,(d.[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.NAC)
U.HAXC <- cbind(cop.N@psi(E.EVC[,1:d.[1]]/V01, theta = th.N[2]),
cop.N@psi(E.EVC[,(d.[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC)
tau.HEVC <- c(0.2, 0.5, 0.7)
family.HEVC <- "Gumbel"
cop.HEVC <- getAcop(family.HEVC)
th.HEVC <- iTau(cop.HEVC, tau = tau.HEVC)
cop.HEVC <- onacopulaL(family.HEVC, list(th.HEVC[1], NULL,
list(list(th.HEVC[2], 1:d.[1]),
list(th.HEVC[3], (d.[1]+1):d))))
set.seed(271)
U.HEVC <- rCopula(n, copula = cop.HEVC)
E.HEVC <- -log(U.HEVC)
U.HAXC.HEVC.same <- cbind(cop.N@psi(E.HEVC[,1:d.[1]]/V01, theta = th.N[2]),
cop.N@psi(E.HEVC[,(d.[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC.HEVC.same)
d.. <- rev(d.)
U.HAXC.HEVC.dffr <- cbind(cop.N@psi(E.HEVC[,1:d..[1]]/V01, theta = th.N[2]),
cop.N@psi(E.HEVC[,(d..[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC.HEVC.dffr)
P <- matrix(0.7, ncol = d, nrow = d)
diag(P) <- 1
nu <- 3.5
set.seed(271)
U.EVC <- exp(-1/rmev(n, d = d, param = nu, sigma = P, model = "xstud"))
mypairs(U.EVC)
P.h <- matrix(0.2, ncol = d, nrow = d)
P.h[1:d.[1], 1:d.[1]] <- 0.5
P.h[(d-d.[2]+1):d, (d-d.[2]+1):d] <- 0.7
diag(P.h) <- 1
X.et <- rmev(n, d = d, param = nu, sigma = P.h, model = "xstud")
U.HEVC <- exp(-1/X.et)
mypairs(U.HEVC)
E.HEVC <- -log(U.HEVC)
U.AXC.HEVC <- cop@psi(E.HEVC/V, theta = th)
mypairs(U.AXC.HEVC)
E.EVC <- -log(U.EVC)
U.HAXC.EVC <- cbind(cop.N@psi(E.EVC[,1:d.[1]]/V01, theta = th.N[2]),
cop.N@psi(E.EVC[,(d.[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC.EVC)
U.NAXC.HEVC.same <- cbind(cop.N@psi(E.HEVC[,1:d.[1]]/V01, theta = th.N[2]),
cop.N@psi(E.HEVC[,(d.[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC.HEVC.same)
U.NAXC.HEVC.dffr <- cbind(cop.N@psi(E.HEVC[,1:d..[1]]/V01, theta = th.N[2]),
cop.N@psi(E.HEVC[,(d..[1]+1):d]/V02, theta = th.N[3]))
mypairs(U.HAXC.HEVC.dffr)
|
knitr::opts_chunk$set(echo = TRUE)
library(Ryacas)
library(Matrix)
N <- 3
L1chr <- diag("1", 1 + N)
L1chr[cbind(1+(1:N), 1:N)] <- "-a"
L1s <- ysym(L1chr)
L1s
K1s <- L1s %*% t(L1s)
V1s <- solve(K1s)
cat(
"\\begin{align} K_1 &= ", tex(K1s), " \\\\
V_1 &= ", tex(V1s), " \\end{align}", sep = "")
N <- 3
L2chr <- diag("1", 1 + 2*N)
L2chr[cbind(1+(1:N), 1:N)] <- "-a"
L2chr[cbind(1 + N + (1:N), 1 + 1:N)] <- "-b"
L2s <- ysym(L2chr)
L2s
K2s <- L2s %*% t(L2s)
V2s <- solve(K2s)
try(V2s <- simplify(V2s), silent = TRUE)
cat(
"\\begin{align} K_2 &= ", tex(K2s), " \\\\
V_2 &= ", tex(V2s), " \\end{align}", sep = "")
sparsify <- function(x) {
if (requireNamespace("Matrix", quietly = TRUE)) {
library(Matrix)
return(Matrix::Matrix(x, sparse = TRUE))
}
return(x)
}
alpha <- 0.5
beta <- -0.3
N <- 3
L1 <- diag(1, 1 + N)
L1[cbind(1+(1:N), 1:N)] <- -alpha
K1 <- L1 %*% t(L1)
V1 <- solve(K1)
sparsify(K1)
sparsify(V1)
N <- 3
L2 <- diag(1, 1 + 2*N)
L2[cbind(1+(1:N), 1:N)] <- -alpha
L2[cbind(1 + N + (1:N), 1 + 1:N)] <- -beta
K2 <- L2 %*% t(L2)
V2 <- solve(K2)
sparsify(K2)
sparsify(V2)
V1s_eval <- eval(yac_expr(V1s), list(a = alpha))
V2s_eval <- eval(yac_expr(V2s), list(a = alpha, b = beta))
all.equal(V1, V1s_eval)
all.equal(V2, V2s_eval)
|
test_that("unquote", {
f <- lintr:::unquote
expect_equal(f(character()), character())
expect_equal(f("foo"), "foo")
expect_equal(
f(c("'f", "\"f'", "\"f\""), q = "\""),
c("'f", "\"f'", "f"))
expect_equal(
f(c("\"f\"", "'f'", "`f`", "`'f'`"), q = "'"),
c("\"f\"", "f", "`f`", "`'f'`"))
expect_equal(f("`a\\`b`", q = c("`")), "a`b")
x <- c("\"x\"", "\"\\n\"", "\"\\\\\"", "\"\\\\y\"", "\"\\ny\"", "\"\\\\ny\"", "\"\\\\\\ny\"",
"\"\\\\\\\\ny\"", "\"'\"", "\"\\\"\"", "\"`\"")
y <- c("x", "\n", "\\", "\\y", "\ny", "\\ny", "\\\ny", "\\\\ny", "'", "\"", "`")
expect_equal(f(x, q = "\""), y)
})
test_that("unescape", {
f <- lintr:::unescape
expect_equal(f(character()), character())
expect_equal(f("n"), "n")
x <- c("x", "x\\n", "x\\\\", "x\\\\y", "x\\ny", "x\\\\ny", "x\\\\\\ny", "x\\\\\\\\ny")
y <- c("x", "x\n", "x\\", "x\\y", "x\ny", "x\\ny", "x\\\ny", "x\\\\ny")
expect_equal(f(x), y)
})
test_that("is_root_path", {
f <- lintr:::is_root_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("", "foo", "http://rseek.org/", "./", " /", "/foo", "'/'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("/", "//")
y <- c(TRUE, FALSE)
expect_equal(f(x), y)
x <- c("~", "~/", "~//", "~bob2", "~foo_bar/")
y <- c(TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("c:", "C:\\", "D:/", "C:\\\\", "D://")
y <- c(TRUE, TRUE, TRUE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("\\\\", "\\\\localhost", "\\\\localhost\\")
y <- c(TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_absolute_path", {
f <- lintr:::is_absolute_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("/", "//", "/foo", "/foo/")
y <- c(TRUE, FALSE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("~", "~/foo", "~/foo/", "~'")
y <- c(TRUE, TRUE, TRUE, FALSE)
expect_equal(f(x), y)
x <- c("c:", "C:\\foo\\", "C:/foo/")
y <- c(TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("\\\\", "\\\\localhost", "\\\\localhost\\c$", "\\\\localhost\\c$\\foo")
y <- c(TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_relative_path", {
f <- lintr:::is_relative_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("/", "c:\\", "~/", "foo", "http://rseek.org/", "'./'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("/foo", "foo/", "foo/bar", "foo//bar", "./foo", "../foo")
y <- c(FALSE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("\\\\", "\\foo", "foo\\", "foo\\bar", ".\\foo", "..\\foo", ".", "..", "../")
y <- c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_path", {
f <- lintr:::is_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("", "foo", "http://rseek.org/", "foo\nbar", "'foo/bar'", "'/'")
y <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("c:", "..", "foo/bar", "foo\\bar", "~", "\\\\localhost")
y <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("is_valid_path", {
f <- lintr:::is_valid_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("C:/asdf", "C:/asd*f", "a\\s:df", "a\\\nsdf")
y <- c(TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x), y)
x <- c("C:/asdf", "C:/asd*f", "a\\s:df", "a\\\nsdf")
y <- c(TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x, lax = TRUE), y)
x <- c("/asdf", "/asd*f", "/as:df", "/a\nsdf")
y <- c(TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
x <- c("/asdf", "/asd*f", "/as:df", "/a\nsdf")
y <- c(TRUE, FALSE, FALSE, FALSE)
expect_equal(f(x, lax = TRUE), y)
})
test_that("is_long_path", {
f <- lintr:::is_long_path
x <- character()
y <- logical()
expect_equal(f(x), y)
x <- c("foo/", "/foo", "n/a", "Z:\\foo", "foo/bar", "~/foo", "../foo")
y <- c(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
expect_equal(f(x), y)
})
test_that("returns the correct linting", {
msg <- rex::escape("Do not use absolute paths.")
linter <- absolute_path_linter(lax = FALSE)
non_absolute_path_strings <- c(
"..",
"./blah",
encodeString("blah\\file.txt")
)
for (path in non_absolute_path_strings) {
expect_lint(single_quote(path), NULL, linter)
expect_lint(double_quote(path), NULL, linter)
}
expect_lint("\"'/'\"", NULL, linter)
absolute_path_strings <- c(
"/",
"/blah/file.txt",
encodeString("d:\\"),
"E:/blah/file.txt",
encodeString("\\\\"),
encodeString("\\\\server\\path"),
"~",
"~james.hester/blah/file.txt",
encodeString("/a\nsdf"),
"/as:df"
)
for (path in absolute_path_strings) {
expect_lint(single_quote(path), msg, linter)
expect_lint(double_quote(path), msg, linter)
}
linter <- absolute_path_linter(lax = TRUE)
unlikely_path_strings <- c(
"/",
encodeString("/a\nsdf/bar"),
"/as:df/bar"
)
for (path in unlikely_path_strings) {
expect_lint(single_quote(path), NULL, linter)
expect_lint(double_quote(path), NULL, linter)
}
})
|
context("fundamental cycles")
testthat::skip_on_cran ()
test_that("dodgr_fundamental_cycles", {
net <- weight_streetnet (hampi)
graph <- dodgr_contract_graph (net)
expect_error (x <- dodgr_fundamental_cycles (),
"graph must be provided")
expect_error (x <- dodgr_fundamental_cycles (graph = "a"),
"graph must be a data.frame object")
expect_silent (x <- dodgr_fundamental_cycles (graph))
expect_is (x, "list")
expect_true (length (x) > 1)
})
test_that("cycles_with_max_graph_size", {
net <- weight_streetnet (hampi)
expect_message (
x <- dodgr_fundamental_cycles (graph = net,
graph_max_size = 1000),
"Now computing fundamental cycles")
expect_is (x, "list")
expect_length (x, 62)
expect_silent (
xf <- dodgr_full_cycles (graph = net,
graph_max_size = 1000))
expect_true (length (x) > 1)
})
test_that("sflines_to_poly", {
expect_error (p <- dodgr_sflines_to_poly (list (hampi)),
"lines must be an object of class 'sf' or 'sfc'")
h <- hampi
class (h$geometry) <- "list"
expect_error (p <- dodgr_sflines_to_poly (h),
"lines must be an 'sfc_LINESTRING' object")
expect_silent (p <- dodgr_sflines_to_poly (hampi))
expect_is (hampi$geometry, "sfc_LINESTRING")
expect_is (p, "sfc_POLYGON")
expect_equal (length (p), 62)
net <- weight_streetnet (hampi, wt_profile = 1)
net1 <- net [net$component == 1, ]
net1$edge_id <- seq (nrow (net1))
p1 <- dodgr_full_cycles (net1)
net2 <- net [net$component == 2, ]
net2$edge_id <- seq (nrow (net2))
p2 <- dodgr_full_cycles (net2)
expect_equal (length (p1) + length (p2), length (p))
})
|
get_statistic <- function(x, ...) {
UseMethod("get_statistic")
}
get_statistic.default <- function(x, column_index = 3, verbose = TRUE, ...) {
cs <- stats::coef(summary(x))
if (column_index > ncol(cs)) {
if (isTRUE(verbose)) {
warning("Could not access test statistic of model parameters.", call. = FALSE)
}
return(NULL)
}
params <- rownames(cs)
if (is.null(params)) {
params <- paste(1:nrow(cs))
}
out <- data.frame(
Parameter = params,
Statistic = as.vector(cs[, column_index]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.summary.lm <- function(x, ...) {
cs <- stats::coef(x)
out <- data.frame(
Parameter = rownames(cs),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mlm <- function(x, ...) {
cs <- stats::coef(summary(x))
out <- lapply(names(cs), function(i) {
params <- cs[[i]]
data.frame(
Parameter = rownames(params),
Statistic = as.vector(params[, 3]),
Response = gsub("^Response (.*)", "\\1", i),
stringsAsFactors = FALSE,
row.names = NULL
)
})
out <- .remove_backticks_from_parameter_names(do.call(rbind, out))
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.lme <- function(x, ...) {
get_statistic.default(x, column_index = 4)
}
get_statistic.lmerModLmerTest <- get_statistic.lme
get_statistic.merModList <- function(x, ...) {
s <- suppressWarnings(summary(x))
out <- data.frame(
Parameter = s$fe$term,
Statistic = s$fe$statistic,
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.afex_aov <- function(x, ...) {
out <- data.frame(
Parameter = rownames(x$anova_table),
Statistic = x$anova_table$"F",
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.plm <- get_statistic.default
get_statistic.maxLik <- get_statistic.default
get_statistic.glmmadmb <- get_statistic.default
get_statistic.lm_robust <- get_statistic.default
get_statistic.geeglm <- get_statistic.default
get_statistic.truncreg <- get_statistic.default
get_statistic.tobit <- get_statistic.default
get_statistic.censReg <- get_statistic.default
get_statistic.negbin <- get_statistic.default
get_statistic.feis <- get_statistic.default
get_statistic.mhurdle <- function(x,
component = c("all", "conditional", "zi", "zero_inflated", "infrequent_purchase", "ip", "auxiliary"),
...) {
component <- match.arg(component)
s <- summary(x)
params <- get_parameters(x, component = "all")
stats <- data.frame(
Parameter = rownames(s$coefficients),
Statistic = as.vector(s$coefficients[, 3]),
Component = NA,
stringsAsFactors = FALSE
)
cond_pars <- which(grepl("^h2\\.", rownames(s$coefficients)))
zi_pars <- which(grepl("^h1\\.", rownames(s$coefficients)))
ip_pars <- which(grepl("^h3\\.", rownames(s$coefficients)))
aux_pars <- (1:length(rownames(s$coefficients)))[-c(cond_pars, zi_pars, ip_pars)]
stats$Component[cond_pars] <- "conditional"
stats$Component[zi_pars] <- "zero_inflated"
stats$Component[ip_pars] <- "infrequent_purchase"
stats$Component[aux_pars] <- "auxiliary"
params <- merge(params, stats, sort = FALSE)
params <- .filter_component(params, component)[intersect(c("Parameter", "Statistic", "Component"), colnames(params))]
params <- .remove_backticks_from_parameter_names(params)
attr(params, "statistic") <- find_statistic(x)
params
}
get_statistic.glmmTMB <- function(x,
component = c("all", "conditional", "zi", "zero_inflated", "dispersion"),
...) {
component <- match.arg(component)
cs <- .compact_list(stats::coef(summary(x)))
out <- lapply(names(cs), function(i) {
data.frame(
Parameter = find_parameters(x, effects = "fixed", component = i, flatten = TRUE),
Statistic = as.vector(cs[[i]][, 3]),
Component = i,
stringsAsFactors = FALSE,
row.names = NULL
)
})
stat <- do.call(rbind, out)
stat$Component <- .rename_values(stat$Component, "cond", "conditional")
stat$Component <- .rename_values(stat$Component, "zi", "zero_inflated")
stat$Component <- .rename_values(stat$Component, "disp", "dispersion")
stat <- .filter_component(stat, component)
stat <- .remove_backticks_from_parameter_names(stat)
attr(stat, "statistic") <- find_statistic(x)
stat
}
get_statistic.zeroinfl <- function(x,
component = c("all", "conditional", "zi", "zero_inflated"),
...) {
component <- match.arg(component)
cs <- .compact_list(stats::coef(summary(x)))
out <- lapply(names(cs), function(i) {
comp <- ifelse(i == "count", "conditional", "zi")
stats <- cs[[i]]
theta <- grepl("Log(theta)", rownames(stats), fixed = TRUE)
if (any(theta)) {
stats <- stats[!theta, ]
}
data.frame(
Parameter = find_parameters(x,
effects = "fixed",
component = comp,
flatten = TRUE
),
Statistic = as.vector(stats[, 3]),
Component = comp,
stringsAsFactors = FALSE,
row.names = NULL
)
})
stat <- do.call(rbind, out)
stat$Component <- .rename_values(stat$Component, "cond", "conditional")
stat$Component <- .rename_values(stat$Component, "zi", "zero_inflated")
stat <- .filter_component(stat, component)
stat <- .remove_backticks_from_parameter_names(stat)
attr(stat, "statistic") <- find_statistic(x)
stat
}
get_statistic.hurdle <- get_statistic.zeroinfl
get_statistic.zerocount <- get_statistic.zeroinfl
get_statistic.MixMod <- function(x,
component = c("all", "conditional", "zi", "zero_inflated"),
...) {
component <- match.arg(component)
s <- summary(x)
cs <- list(s$coef_table, s$coef_table_zi)
names(cs) <- c("conditional", "zero_inflated")
cs <- .compact_list(cs)
out <- lapply(names(cs), function(i) {
data.frame(
Parameter = find_parameters(x,
effects = "fixed",
component = i,
flatten = TRUE
),
Statistic = as.vector(cs[[i]][, 3]),
Component = i,
stringsAsFactors = FALSE,
row.names = NULL
)
})
stat <- .filter_component(do.call(rbind, out), component)
stat <- .remove_backticks_from_parameter_names(stat)
attr(stat, "statistic") <- find_statistic(x)
stat
}
get_statistic.Gam <- function(x, ...) {
p.aov <- stats::na.omit(summary(x)$parametric.anova)
out <- data.frame(
Parameter = rownames(p.aov),
Statistic = as.vector(p.aov[, 4]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.gam <- function(x, ...) {
cs <- summary(x)$p.table
cs.smooth <- summary(x)$s.table
out <- data.frame(
Parameter = c(rownames(cs), rownames(cs.smooth)),
Statistic = c(as.vector(cs[, 3]), as.vector(cs.smooth[, 3])),
Component = c(rep("conditional", nrow(cs)), rep("smooth_terms", nrow(cs.smooth))),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.scam <- get_statistic.gam
get_statistic.SemiParBIV <- function(x, ...) {
s <- summary(x)
s <- .compact_list(s[grepl("^tableP", names(s))])
params <- do.call(rbind, lapply(1:length(s), function(i) {
out <- as.data.frame(s[[i]])
out$Parameter <- rownames(out)
out$Component <- paste0("Equation", i)
out
}))
colnames(params)[3] <- "Statistic"
rownames(params) <- NULL
out <- .remove_backticks_from_parameter_names(params[c("Parameter", "Statistic", "Component")])
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.gamm <- function(x, ...) {
x <- x$gam
class(x) <- c("gam", "lm", "glm")
get_statistic.gam(x, ...)
}
get_statistic.list <- function(x, ...) {
if ("gam" %in% names(x)) {
x <- x$gam
class(x) <- c("gam", "lm", "glm")
get_statistic.gam(x, ...)
}
}
get_statistic.gamlss <- function(x, ...) {
parms <- get_parameters(x)
utils::capture.output(cs <- summary(x))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(cs[, 3]),
Component = parms$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.vglm <- function(x, ...) {
if (!requireNamespace("VGAM", quietly = TRUE)) {
stop("Package 'VGAM' needed for this function to work. Please install it.")
}
cs <- VGAM::coef(VGAM::summary(x))
out <- data.frame(
Parameter = rownames(cs),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.vgam <- function(x, ...) {
params <- get_parameters(x)
out <- data.frame(
Parameter = names([email protected]),
Statistic = [email protected],
stringsAsFactors = FALSE,
row.names = NULL
)
out <- merge(params, out, all.x = TRUE)
out <- out[order(out$Parameter, params$Parameter), ]
out <- .remove_backticks_from_parameter_names(out[c("Parameter", "Statistic", "Component")])
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.cgam <- function(x,
component = c("all", "conditional", "smooth_terms"),
...) {
component <- match.arg(component)
sc <- summary(x)
stat <- as.vector(sc$coefficients[, 3])
if (!is.null(sc$coefficients2)) stat <- c(stat, rep(NA, nrow(sc$coefficients2)))
params <- get_parameters(x, component = "all")
out <- data.frame(
Parameter = params$Parameter,
Statistic = stat,
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.coxph <- function(x, ...) {
get_statistic.default(x, column_index = 4)
}
get_statistic.svy_vglm <- function(x, verbose = TRUE, ...) {
cs <- summary(x)$coeftable
out <- data.frame(
Parameter = find_parameters(x, flatten = TRUE),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.coxr <- function(x, ...) {
parms <- get_parameters(x)
vc <- get_varcov(x)
se <- sqrt(diag(vc))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.crr <- get_statistic.coxr
get_statistic.coxme <- function(x, ...) {
beta <- x$coefficients
out <- NULL
if (length(beta) > 0) {
out <- data.frame(
Parameter = names(beta),
Statistic = as.vector(beta / sqrt(diag(stats::vcov(x)))),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
}
out
}
get_statistic.riskRegression <- function(x, ...) {
junk <- utils::capture.output(cs <- stats::coef(x))
out <- data.frame(
Parameter = as.vector(cs[, 1]),
Statistic = as.numeric(cs[, "z"]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.survreg <- function(x, ...) {
parms <- get_parameters(x)
s <- summary(x)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = s$table[, 3],
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.BBmm <- function(x, ...) {
parms <- get_parameters(x)
s <- summary(x)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = s$fixed.coefficients[, 3],
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.flexsurvreg <- function(x, ...) {
parms <- get_parameters(x)
se <- x$res[, "se"]
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.aareg <- function(x, ...) {
sc <- summary(x)
parms <- get_parameters(x)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = unname(sc$test.statistic),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.clm2 <- function(x,
component = c("all", "conditional", "scale"),
...) {
component <- match.arg(component)
stats <- stats::coef(summary(x))
n_intercepts <- length(x$xi)
n_location <- length(x$beta)
n_scale <- length(x$zeta)
out <- data.frame(
Parameter = rownames(stats),
Statistic = unname(stats[, "z value"]),
Component = c(rep("conditional", times = n_intercepts + n_location), rep("scale", times = n_scale)),
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.clmm2 <- get_statistic.clm2
get_statistic.mvord <- function(x,
component = c("all", "conditional", "thresholds", "correlation"),
...) {
component <- match.arg(component)
junk <- utils::capture.output(s <- summary(x))
thresholds <- as.data.frame(s$thresholds)
thresholds$Parameter <- rownames(thresholds)
thresholds$Response <- gsub("(.*)\\s(.*)", "\\1", thresholds$Parameter)
coefficients <- as.data.frame(s$coefficients)
coefficients$Parameter <- rownames(coefficients)
coefficients$Response <- gsub("(.*)\\s(.*)", "\\2", coefficients$Parameter)
if (!all(coefficients$Response %in% thresholds$Response)) {
resp <- unique(thresholds$Response)
for (i in coefficients$Response) {
coefficients$Response[coefficients$Response == i] <- resp[grepl(paste0(i, "$"), resp)]
}
}
params <- data.frame(
Parameter = c(thresholds$Parameter, coefficients$Parameter),
Statistic = c(unname(thresholds[, "z value"]), unname(coefficients[, "z value"])),
Component = c(rep("thresholds", nrow(thresholds)), rep("conditional", nrow(coefficients))),
Response = c(thresholds$Response, coefficients$Response),
stringsAsFactors = FALSE,
row.names = NULL
)
params_error <- data.frame(
Parameter = rownames(s$error.structure),
Statistic = unname(s$error.structure[, "z value"]),
Component = "correlation",
Response = NA,
stringsAsFactors = FALSE,
row.names = NULL
)
params <- rbind(params, params_error)
if (.n_unique(params$Response) == 1) {
params$Response <- NULL
}
if (component != "all") {
params <- params[params$Component == component, , drop = FALSE]
}
attr(params, "statistic") <- find_statistic(x)
.remove_backticks_from_parameter_names(params)
}
get_statistic.glmm <- function(x,
effects = c("all", "fixed", "random"),
...) {
effects <- match.arg(effects)
s <- summary(x)
out <- get_parameters(x, effects = "all")
out$Statistic <- c(s$coefmat[, 3], s$nucoefmat[, 3])
out <- out[, c("Parameter", "Statistic", "Effects")]
if (effects != "all") {
out <- out[out$Effects == effects, , drop = FALSE]
out$Effects <- NULL
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mixor <- function(x,
effects = c("all", "fixed", "random"),
...) {
stats <- x$Model[, "z value"]
effects <- match.arg(effects)
parms <- get_parameters(x, effects = effects)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = stats[parms$Parameter],
Effects = parms$Effects,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.multinom <- function(x, ...) {
parms <- get_parameters(x)
stderr <- summary(x)$standard.errors
if (is.matrix(stderr)) {
se <- c()
for (i in 1:nrow(stderr)) {
se <- c(se, as.vector(stderr[i, ]))
}
} else {
se <- as.vector(stderr)
}
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
if ("Response" %in% colnames(parms)) {
out$Response <- parms$Response
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.brmultinom <- get_statistic.multinom
get_statistic.bracl <- function(x, ...) {
parms <- get_parameters(x)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = stats::coef(summary(x))[, "z value"],
Response = parms$Response,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mlogit <- function(x, ...) {
if (requireNamespace("mlogit", quietly = TRUE)) {
cs <- stats::coef(summary(x))
out <- data.frame(
Parameter = rownames(cs),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
} else {
NULL
}
}
get_statistic.betamfx <- function(x,
component = c("all", "conditional", "precision", "marginal"),
...) {
component <- match.arg(component)
parms <- get_parameters(x, component = "all", ...)
cs <- do.call(rbind, stats::coef(summary(x$fit)))
stat <- c(as.vector(x$mfxest[, 3]), as.vector(cs[, 3]))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = stat,
Component = parms$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.betaor <- function(x,
component = c("all", "conditional", "precision"),
...) {
component <- match.arg(component)
parms <- get_parameters(x, component = "all", ...)
cs <- do.call(rbind, stats::coef(summary(x$fit)))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(cs[, 3]),
Component = parms$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.logitmfx <- function(x,
component = c("all", "conditional", "marginal"),
...) {
parms <- get_parameters(x, component = "all", ...)
cs <- stats::coef(summary(x$fit))
stat <- c(as.vector(x$mfxest[, 3]), as.vector(cs[, 3]))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = stat,
Component = parms$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.poissonmfx <- get_statistic.logitmfx
get_statistic.negbinmfx <- get_statistic.logitmfx
get_statistic.probitmfx <- get_statistic.logitmfx
get_statistic.logitor <- function(x, ...) {
get_statistic.default(x$fit)
}
get_statistic.poissonirr <- get_statistic.logitor
get_statistic.negbinirr <- get_statistic.logitor
get_statistic.pgmm <- function(x,
component = c("conditional", "all"),
verbose = TRUE,
...) {
component <- match.arg(component)
cs <- stats::coef(summary(x, time.dummies = TRUE, robust = FALSE))
out <- data.frame(
Parameter = row.names(cs),
Statistic = as.vector(cs[, 3]),
Component = "conditional",
stringsAsFactors = FALSE,
row.names = NULL
)
out$Component[out$Parameter %in% x$args$namest] <- "time_dummies"
if (component == "conditional") {
out <- out[out$Component == "conditional", ]
out <- .remove_column(out, "Component")
}
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.selection <- function(x,
component = c("all", "selection", "outcome", "auxiliary"),
...) {
component <- match.arg(component)
s <- summary(x)
rn <- row.names(s$estimate)
estimates <- as.data.frame(s$estimate, row.names = FALSE)
params <- data.frame(
Parameter = rn,
Statistic = estimates[[3]],
Component = "auxiliary",
stringsAsFactors = FALSE,
row.names = NULL
)
params$Component[s$param$index$betaS] <- "selection"
params$Component[s$param$index$betaO] <- "outcome"
if (component != "all") {
params <- params[params$Component == component, , drop = FALSE]
}
params <- .remove_backticks_from_parameter_names(params)
attr(params, "statistic") <- find_statistic(x)
params
}
get_statistic.lavaan <- function(x, ...) {
check_if_installed("lavaan")
params <- lavaan::parameterEstimates(x)
params$parameter <- paste0(params$lhs, params$op, params$rhs)
params$comp <- NA
params$comp[params$op == "~"] <- "regression"
params$comp[params$op == "=~"] <- "latent"
params$comp[params$op == "~~"] <- "residual"
params$comp[params$op == "~1"] <- "intercept"
params <- data.frame(
Parameter = params$parameter,
Statistic = params$z,
Component = params$comp,
stringsAsFactors = FALSE
)
params <- .remove_backticks_from_parameter_names(params)
attr(params, "statistic") <- find_statistic(x)
params
}
get_statistic.model_fit <- function(x, ...) {
get_statistic(x$fit, ...)
}
get_statistic.Sarlm <- function(x, ...) {
s <- summary(x)
if (!is.null(s$rho)) {
rho <- as.numeric(s$rho) / as.numeric(s$rho.se)
} else {
rho <- NULL
}
stat <- data.frame(
Parameter = find_parameters(x, flatten = TRUE),
Statistic = c(rho, as.vector(s$Coef[, 3])),
stringsAsFactors = FALSE,
row.names = NULL
)
stat <- .remove_backticks_from_parameter_names(stat)
attr(stat, "statistic") <- find_statistic(x)
stat
}
get_statistic.mjoint <- function(x,
component = c("all", "conditional", "survival"),
...) {
component <- match.arg(component)
s <- summary(x)
params <- rbind(
data.frame(
Parameter = rownames(s$coefs.long),
Statistic = unname(s$coefs.long[, 3]),
Component = "conditional",
stringsAsFactors = FALSE,
row.names = NULL
),
data.frame(
Parameter = rownames(s$coefs.surv),
Statistic = unname(s$coefs.surv[, 3]),
Component = "survival",
stringsAsFactors = FALSE,
row.names = NULL
)
)
if (component != "all") {
params <- params[params$Component == component, , drop = FALSE]
}
attr(params, "statistic") <- find_statistic(x)
params
}
get_statistic.Rchoice <- function(x, verbose = TRUE, ...) {
cs <- summary(x)$CoefTable
out <- data.frame(
Parameter = find_parameters(x, flatten = TRUE),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.garch <- function(x, verbose = TRUE, ...) {
cs <- summary(x)$coef
out <- data.frame(
Parameter = find_parameters(x, flatten = TRUE),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.ergm <- function(x, verbose = TRUE, ...) {
get_statistic.default(x = x, column_index = 4, verbose = verbose, ...)
}
get_statistic.btergm <- function(x, verbose = TRUE, ...) {
params <- x@coef
bootstraps <- x@boot$t
sdev <- sapply(1:ncol(bootstraps), function(i) {
cur <- (bootstraps[, i] - params[i])^2
sqrt(sum(cur) / length(cur))
})
stat <- (0 - colMeans(bootstraps)) / sdev
out <- data.frame(
Parameter = names(stat),
Statistic = stat,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.ridgelm <- function(x, ...) {
NULL
}
get_statistic.lmodel2 <- function(x, ...) {
NULL
}
get_statistic.ivFixed <- get_statistic.coxr
get_statistic.ivprobit <- function(x, ...) {
out <- data.frame(
Parameter = x$names,
Statistic = as.vector(x$tval),
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.HLfit <- function(x, ...) {
utils::capture.output(s <- summary(x))
out <- data.frame(
Parameter = rownames(s$beta_table),
Statistic = as.vector(s$beta_table[, "t-value"]),
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.margins <- function(x, ...) {
out <- data.frame(
Parameter = get_parameters(x)$Parameter,
Statistic = as.vector(summary(x)$z),
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.lqmm <- function(x, ...) {
cs <- summary(x, ...)
params <- get_parameters(x)
if (is.list(cs$tTable)) {
stats <- do.call(rbind, cs$tTable)
params$Statistic <- params$Estimate / stats[, 2]
params <- params[c("Parameter", "Statistic", "Component")]
} else {
params$Statistic <- params$Estimate / cs$tTable[, 2]
params <- params[c("Parameter", "Statistic")]
}
out <- .remove_backticks_from_parameter_names(params)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.lqm <- get_statistic.lqmm
get_statistic.mipo <- function(x, ...) {
params <- data.frame(
Parameter = as.vector(summary(x)$term),
Statistic = as.vector(summary(x)$statistic),
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(params)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mira <- function(x, ...) {
get_statistic(x$analyses[[1]], ...)
}
get_statistic.mle2 <- function(x, ...) {
if (!requireNamespace("bbmle", quietly = TRUE)) {
stop("Package `bbmle` needs to be installed to extract test statistic.", call. = FALSE)
}
s <- bbmle::summary(x)
params <- data.frame(
Parameter = names(s@coef[, 3]),
Statistic = unname(s@coef[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(params)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mle <- get_statistic.mle2
get_statistic.glht <- function(x, ...) {
s <- summary(x)
alt <- switch(x$alternative,
two.sided = "==",
less = ">=",
greater = "<="
)
out <- data.frame(
Parameter = paste(names(s$test$coefficients), alt, x$rhs),
Statistic = unname(s$test$tstat),
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.emmGrid <- function(x, ci = .95, adjust = "none", merge_parameters = FALSE, ...) {
s <- summary(x, level = ci, adjust = adjust, infer = TRUE)
stat <- s[["t.ratio"]]
if (.is_empty_object(stat)) {
stat <- s[["z.ratio"]]
}
if (.is_empty_object(stat)) {
return(NULL)
}
estimate_pos <- which(colnames(s) == attr(s, "estName"))
if (isTRUE(merge_parameters)) {
params <- get_parameters(x, merge_parameters = TRUE)["Parameter"]
} else {
params <- s[, seq_len(estimate_pos - 1), drop = FALSE]
}
out <- data.frame(
params,
Statistic = as.vector(stat),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.emm_list <- function(x, ci = .95, adjust = "none", ...) {
params <- get_parameters(x)
s <- summary(x, level = ci, adjust = adjust, infer = TRUE)
stat <- lapply(s, "[[", "t.ratio")
if (.is_empty_object(stat)) {
stat <- lapply(s, "[[", "z.ratio")
}
if (.is_empty_object(stat)) {
return(NULL)
}
stat <- unlist(stat)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(stat),
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.robmixglm <- function(x, ...) {
cs <- stats::coef(summary(x))
out <- data.frame(
Parameter = rownames(cs),
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- out[!is.na(out$Statistic), ]
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.averaging <- function(x, component = c("conditional", "full"), ...) {
component <- match.arg(component)
params <- get_parameters(x, component = component)
if (component == "full") {
s <- summary(x)$coefmat.full
} else {
s <- summary(x)$coefmat.subset
}
out <- data.frame(
Parameter = params$Parameter,
Statistic = s[, 4],
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.bayesx <- function(x, ...) {
out <- data.frame(
Parameter = find_parameters(x, component = "conditional", flatten = TRUE),
Statistic = x$fixed.effects[, 3],
stringsAsFactors = FALSE
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.Arima <- function(x, ...) {
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(params$Estimate / sqrt(diag(get_varcov(x)))),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.wbm <- function(x, ...) {
s <- summary(x)
statistic_column <- if ("t val." %in% c(
colnames(s$within_table),
colnames(s$between_table),
colnames(s$ints_table)
)) {
"t val."
} else {
"z val."
}
stat <- c(
s$within_table[, statistic_column],
s$between_table[, statistic_column],
s$ints_table[, statistic_column]
)
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(stat),
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.wbgee <- get_statistic.wbm
get_statistic.cpglmm <- function(x, ...) {
check_if_installed("cplm")
stats <- cplm::summary(x)$coefs
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(stats[, "t value"]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.sem <- function(x, ...) {
if (!.is_semLme(x)) {
return(NULL)
}
params <- get_parameters(x, effects = "fixed")
if (is.null(x$se)) {
warning(format_message("Model has no standard errors. Please fit model again with bootstrapped standard errors."), call. = FALSE)
return(NULL)
}
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(x$coef / x$se),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.cpglm <- function(x, ...) {
check_if_installed("cplm")
junk <- utils::capture.output(stats <- cplm::summary(x)$coefficients)
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(stats[, "t value"]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.zcpglm <- function(x,
component = c("all", "conditional", "zi", "zero_inflated"),
...) {
check_if_installed("cplm")
component <- match.arg(component)
junk <- utils::capture.output(stats <- cplm::summary(x)$coefficients)
params <- get_parameters(x)
tweedie <- data.frame(
Parameter = params$Parameter[params$Component == "conditional"],
Statistic = as.vector(stats$tweedie[, "z value"]),
Component = "conditional",
stringsAsFactors = FALSE,
row.names = NULL
)
zero <- data.frame(
Parameter = params$Parameter[params$Component == "zero_inflated"],
Statistic = as.vector(stats$zero[, "z value"]),
Component = "zero_inflated",
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .filter_component(rbind(tweedie, zero), component)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.manova <- function(x, ...) {
stats <- as.data.frame(summary(x)$stats)
out <- data.frame(
Parameter = rownames(stats),
Statistic = as.vector(stats[["approx F"]]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.maov <- function(x, ...) {
s <- summary(x)
out <- do.call(rbind, lapply(names(s), function(i) {
stats <- s[[i]]
missing <- is.na(stats[["F value"]])
data.frame(
Parameter = rownames(stats)[!missing],
Statistic = as.vector(stats[["F value"]][!missing]),
Response = gsub("\\s*Response ", "", i),
stringsAsFactors = FALSE,
row.names = NULL
)
}))
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.MANOVA <- function(x, ...) {
stats <- as.data.frame(x$WTS)
out <- data.frame(
Parameter = rownames(stats),
Statistic = as.vector(stats[[1]]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.RM <- get_statistic.MANOVA
get_statistic.rq <- function(x, ...) {
stat <- tryCatch(
{
cs <- stats::coef(summary(x))
cs[, "t value"]
},
error = function(e) {
cs <- stats::coef(summary(x, covariance = TRUE))
cs[, "t value"]
}
)
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = stat,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.rqs <- function(x, ...) {
stat <- tryCatch(
{
s <- suppressWarnings(summary(x, covariance = TRUE))
cs <- do.call(rbind, lapply(s, stats::coef))
cs[, "t value"]
},
error = function(e) {
NULL
}
)
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = stat,
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.crq <- function(x, ...) {
sc <- summary(x)
params <- get_parameters(x)
if (all(unlist(lapply(sc, is.list)))) {
list_sc <- lapply(sc, function(i) {
.x <- as.data.frame(i)
.x$Parameter <- rownames(.x)
.x
})
out <- do.call(rbind, list_sc)
out <- data.frame(
Parameter = params$Parameter,
Statistic = out$coefficients.T.Value,
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
} else {
out <- data.frame(
Parameter = params$Parameter,
Statistic = unname(sc$coefficients[, 5]),
stringsAsFactors = FALSE,
row.names = NULL
)
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.crqs <- get_statistic.crq
get_statistic.nlrq <- get_statistic.rq
get_statistic.rqss <- function(x,
component = c("all", "conditional", "smooth_terms"),
...) {
component <- match.arg(component)
cs <- summary(x)
stat <- c(as.vector(cs$coef[, "t value"]), as.vector(cs$qsstab[, "F value"]))
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = unname(stat),
Component = params$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.systemfit <- function(x, ...) {
cf <- stats::coef(summary(x))
f <- find_formula(x)
system_names <- names(f)
parameter_names <- row.names(cf)
out <- lapply(system_names, function(i) {
pattern <- paste0("^", i, "_(.*)")
params <- grepl(pattern, parameter_names)
data.frame(
Parameter = gsub(pattern, "\\1", parameter_names[params]),
Statistic = as.vector(cf[params, 3]),
Component = i,
stringsAsFactors = FALSE
)
})
out <- do.call(rbind, out)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.bigglm <- function(x, ...) {
parms <- get_parameters(x)
cs <- summary(x)$mat
se <- as.vector(cs[, 4])
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.biglm <- function(x, ...) {
parms <- get_parameters(x)
cs <- summary(x)$mat
se <- as.vector(cs[, 4])
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.LORgee <- function(x, ...) {
out <- get_statistic.default(x)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.crch <- function(x, ...) {
cs <- do.call(rbind, stats::coef(summary(x), model = "full"))
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.fixest <- function(x, ...) {
cs <- summary(x)$coeftable
params <- get_parameters(x)
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(cs[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.glmx <- function(x,
component = c("all", "conditional", "extra"),
...) {
component <- match.arg(component)
cf <- stats::coef(summary(x))
parms <- get_parameters(x)
out <- rbind(
data.frame(
Parameter = parms$Parameter[parms$Component == "conditional"],
Statistic = unname(cf$glm[, 3]),
Component = "conditional",
stringsAsFactors = FALSE,
row.names = NULL
),
data.frame(
Parameter = parms$Parameter[parms$Component == "extra"],
Statistic = cf$extra[, 3],
Component = "extra",
stringsAsFactors = FALSE,
row.names = NULL
)
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.gee <- function(x, robust = FALSE, ...) {
parms <- get_parameters(x)
cs <- stats::coef(summary(x))
if (isTRUE(robust)) {
stats <- as.vector(cs[, "Robust z"])
} else {
stats <- as.vector(cs[, "Naive z"])
}
out <- data.frame(
Parameter = parms$Parameter,
Statistic = stats,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.complmrob <- function(x, ...) {
parms <- get_parameters(x)
stat <- summary(x)$stats
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(stat[, "t value"]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.logistf <- function(x, ...) {
parms <- get_parameters(x)
utils::capture.output(s <- summary(x))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(stats::qchisq(1 - s$prob, df = 1)),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.epi.2by2 <- function(x, ...) {
stat <- x$massoc.detail$chi2.strata.uncor
out <- data.frame(
Parameter = "Chi2",
Statistic = stat$test.statistic,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.svyglm.nb <- function(x, ...) {
if (!isNamespaceLoaded("survey")) {
requireNamespace("survey", quietly = TRUE)
}
parms <- get_parameters(x)
se <- sqrt(diag(stats::vcov(x, stderr = "robust")))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.svyglm.zip <- get_statistic.svyglm.nb
get_statistic.svyglm <- function(x, ...) {
parms <- get_parameters(x)
vc <- get_varcov(x)
se <- sqrt(diag(vc))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.svyolr <- get_statistic.svyglm
get_statistic.betareg <- function(x,
component = c("all", "conditional", "precision"),
...) {
component <- match.arg(component)
parms <- get_parameters(x)
cs <- do.call(rbind, stats::coef(summary(x)))
se <- as.vector(cs[, 2])
out <- data.frame(
Parameter = parms$Parameter,
Statistic = parms$Estimate / se,
Component = parms$Component,
stringsAsFactors = FALSE,
row.names = NULL
)
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.DirichletRegModel <- function(x,
component = c("all", "conditional", "precision"),
...) {
component <- match.arg(component)
parms <- get_parameters(x)
junk <- utils::capture.output(cs <- summary(x)$coef.mat)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = unname(cs[, "z value"]),
Response = parms$Response,
stringsAsFactors = FALSE,
row.names = NULL
)
if (!is.null(parms$Component)) {
out$Component <- parms$Component
} else {
component <- "all"
}
if (component != "all") {
out <- out[out$Component == component, , drop = FALSE]
}
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.glimML <- function(x, ...) {
check_if_installed("aod")
parms <- get_parameters(x)
s <- methods::slot(aod::summary(x), "Coef")
out <- data.frame(
Parameter = parms$Parameter,
Statistic = s[, 3],
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.lrm <- function(x, ...) {
parms <- get_parameters(x)
stat <- stats::coef(x) / sqrt(diag(stats::vcov(x)))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(stat),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.ols <- get_statistic.lrm
get_statistic.rms <- get_statistic.lrm
get_statistic.psm <- get_statistic.lrm
get_statistic.orm <- function(x, ...) {
parms <- get_parameters(x)
vc <- stats::vcov(x)
parms <- parms[parms$Parameter %in% dimnames(vc)[[1]], ]
stat <- parms$Estimate / sqrt(diag(vc))
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(stat),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.rma <- function(x, ...) {
parms <- get_parameters(x)
stat <- x$zval
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(stat),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.metaplus <- function(x, ...) {
params <- get_parameters(x)
ci_low <- as.vector(x$results[, "95% ci.lb"])
ci_high <- as.vector(x$results[, "95% ci.ub"])
cis <- apply(cbind(ci_low, ci_high), MARGIN = 1, diff)
se <- cis / (2 * stats::qnorm(.975))
out <- data.frame(
Parameter = params$Parameter,
Statistic = as.vector(params$Estimate / se),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.bife <- function(x, ...) {
parms <- get_parameters(x)
cs <- summary(x)
out <- data.frame(
Parameter = parms$Parameter,
Statistic = as.vector(cs$cm[, 3]),
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.mediate <- function(x, ...) {
NULL
}
get_statistic.coeftest <- function(x, ...) {
out <- data.frame(
Parameter = row.names(x),
Statistic = x[, 3],
stringsAsFactors = FALSE,
row.names = NULL
)
attr(out, "statistic") <- find_statistic(x)
out
}
get_statistic.bfsl <- function(x, ...) {
cs <- stats::coef(x)
out <- data.frame(
Parameter = rownames(cs),
Statistic = as.vector(cs[, "Estimate"] / cs[, "Std. Error"]),
stringsAsFactors = FALSE,
row.names = NULL
)
out <- .remove_backticks_from_parameter_names(out)
attr(out, "statistic") <- find_statistic(x)
out
}
|
t_test <- function(x, formula,
response = NULL,
explanatory = NULL,
order = NULL,
alternative = "two-sided",
mu = 0,
conf_int = TRUE,
conf_level = 0.95,
...) {
check_conf_level(conf_level)
x <- tibble::as_tibble(x) %>%
mutate_if(is.character, as.factor) %>%
mutate_if(is.logical, as.factor)
response <- enquo(response)
explanatory <- enquo(explanatory)
x <- parse_variables(x = x, formula = formula,
response = response, explanatory = explanatory)
if (alternative %in% c("two-sided", "two_sided", "two sided", "two.sided")) {
alternative <- "two.sided"
}
if (has_explanatory(x)) {
order <- check_order(x, order, in_calculate = FALSE, stat = NULL)
x <- reorder_explanatory(x, order)
prelim <- stats::t.test(formula = as.formula(paste0(response_name(x),
" ~ ",
explanatory_name(x))),
data = x,
alternative = alternative,
mu = mu,
conf.level = conf_level,
...) %>%
broom::glance()
} else {
prelim <- stats::t.test(response_variable(x),
alternative = alternative,
mu = mu,
conf.level = conf_level) %>%
broom::glance()
}
if (conf_int) {
results <- prelim %>%
dplyr::select(
statistic, t_df = parameter, p_value = p.value, alternative,
estimate, lower_ci = conf.low, upper_ci = conf.high
)
} else {
results <- prelim %>%
dplyr::select(
statistic, t_df = parameter, p_value = p.value, alternative, estimate
)
}
results
}
t_stat <- function(x, formula,
response = NULL,
explanatory = NULL,
order = NULL,
alternative = "two-sided",
mu = 0,
conf_int = FALSE,
conf_level = 0.95,
...) {
.Deprecated(
new = "observe",
msg = c("The t_stat() wrapper has been deprecated in favor of the more " ,
"general observe(). Please use that function instead.")
)
check_conf_level(conf_level)
x <- tibble::as_tibble(x) %>%
mutate_if(is.character, as.factor) %>%
mutate_if(is.logical, as.factor)
response <- enquo(response)
explanatory <- enquo(explanatory)
x <- parse_variables(x = x, formula = formula,
response = response, explanatory = explanatory)
if (alternative %in% c("two-sided", "two_sided", "two sided", "two.sided")) {
alternative <- "two.sided"
}
if (has_explanatory(x)) {
order <- check_order(x, order, in_calculate = FALSE, stat = NULL)
x <- reorder_explanatory(x, order)
prelim <- stats::t.test(formula = as.formula(paste0(response_name(x),
" ~ ",
explanatory_name(x))),
data = x,
alternative = alternative,
mu = mu,
conf.level = conf_level,
...) %>%
broom::glance()
} else {
prelim <- stats::t.test(response_variable(x),
alternative = alternative,
mu = mu,
conf.level = conf_level) %>%
broom::glance()
}
results <- prelim %>%
dplyr::select(statistic) %>%
pull()
results
}
chisq_test <- function(x, formula, response = NULL,
explanatory = NULL, ...) {
response <- enquo(response)
explanatory <- enquo(explanatory)
x <- parse_variables(x = x, formula = formula,
response = response, explanatory = explanatory)
if (!(class(response_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The response variable of `{response_name(x)}` is not appropriate ',
"since the response variable is expected to be categorical."
)
}
if (has_explanatory(x) &&
!(class(explanatory_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The explanatory variable of `{explanatory_name(x)}` is not appropriate ',
"since the explanatory variable is expected to be categorical."
)
}
x <- x %>%
select(any_of(c(response_name(x), explanatory_name(x)))) %>%
mutate_if(is.character, as.factor) %>%
mutate_if(is.logical, as.factor)
stats::chisq.test(table(x), ...) %>%
broom::glance() %>%
dplyr::select(statistic, chisq_df = parameter, p_value = p.value)
}
chisq_stat <- function(x, formula, response = NULL,
explanatory = NULL, ...) {
.Deprecated(
new = "observe",
msg = c("The chisq_stat() wrapper has been deprecated in favor of the ",
"more general observe(). Please use that function instead.")
)
response <- enquo(response)
explanatory <- enquo(explanatory)
x <- parse_variables(x = x, formula = formula,
response = response, explanatory = explanatory)
if (!(class(response_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The response variable of `{response_name(x)}` is not appropriate ',
"since the response variable is expected to be categorical."
)
}
if (has_explanatory(x) &&
!(class(explanatory_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The explanatory variable of `{explanatory_name(x)}` is not appropriate ',
"since the response variable is expected to be categorical."
)
}
x <- x %>%
select(any_of(c(response_name(x), explanatory_name(x)))) %>%
mutate_if(is.character, as.factor) %>%
mutate_if(is.logical, as.factor)
suppressWarnings(stats::chisq.test(table(x), ...)) %>%
broom::glance() %>%
dplyr::select(statistic) %>%
pull()
}
check_conf_level <- function(conf_level) {
if (
(class(conf_level) != "numeric") | (conf_level < 0) | (conf_level > 1)
) {
stop_glue("The `conf_level` argument must be a number between 0 and 1.")
}
}
prop_test <- function(x, formula,
response = NULL,
explanatory = NULL,
p = NULL,
order = NULL,
alternative = "two-sided",
conf_int = TRUE,
conf_level = 0.95,
success = NULL,
correct = NULL,
z = FALSE,
...) {
response <- enquo(response)
explanatory <- enquo(explanatory)
x <- parse_variables(x = x, formula = formula,
response = response, explanatory = explanatory)
correct <- if (z) {FALSE} else if (is.null(correct)) {TRUE} else {correct}
if (!(class(response_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The response variable of `{response_name(x)}` is not appropriate\n',
"since the response variable is expected to be categorical."
)
}
if (has_explanatory(x) &&
!(class(explanatory_variable(x)) %in% c("logical", "character", "factor"))) {
stop_glue(
'The explanatory variable of `{explanatory_name(x)}` is not appropriate ',
"since the explanatory variable is expected to be categorical."
)
}
if (alternative %in% c("two-sided", "two_sided", "two sided", "two.sided")) {
alternative <- "two.sided"
}
lvls <- levels(factor(response_variable(x)))
if (!is.null(success)) {
check_type(success, rlang::is_string)
if (!(success %in% lvls)) {
stop_glue('{success} is not a valid level of {response_name(x)}.')
}
lvls <- c(success, lvls[lvls != success])
} else {
success <- lvls[1]
}
if (has_explanatory(x)) {
order <- check_order(x, order, in_calculate = FALSE, stat = NULL)
sum_table <- x %>%
select(response_name(x), explanatory_name(x)) %>%
mutate_if(is.character, as.factor) %>%
mutate_if(is.logical, as.factor) %>%
table()
sum_table <- sum_table[lvls, order]
prelim <- stats::prop.test(x = sum_table,
alternative = alternative,
conf.level = conf_level,
p = p,
correct = correct,
...)
} else {
response_tbl <- response_variable(x) %>%
factor() %>%
stats::relevel(success) %>%
table()
if (is.null(p)) {
message_glue(
"No `p` argument was hypothesized, so the test will ",
"assume a null hypothesis `p = .5`."
)
}
prelim <- stats::prop.test(x = response_tbl,
alternative = alternative,
conf.level = conf_level,
p = p,
correct = correct,
...)
}
if (length(prelim$estimate) <= 2) {
if (conf_int & is.null(p)) {
results <- prelim %>%
broom::glance() %>%
dplyr::select(statistic,
chisq_df = parameter,
p_value = p.value,
alternative,
lower_ci = conf.low,
upper_ci = conf.high)
} else {
results <- prelim %>%
broom::glance() %>%
dplyr::select(statistic,
chisq_df = parameter,
p_value = p.value,
alternative)
}
} else {
results <- prelim %>%
broom::glance() %>%
dplyr::select(statistic,
chisq_df = parameter,
p_value = p.value)
}
if (z) {
results <- calculate_z(x, results, success, p, order)
}
results
}
calculate_z <- function(x, results, success, p, order) {
exp <- if (has_explanatory(x)) {explanatory_name(x)} else {"NULL"}
form <- as.formula(paste0(response_name(x), " ~ ", exp))
stat <- x %>%
specify(formula = form, success = success) %>%
hypothesize(
null = if (has_explanatory(x)) {"independence"} else {"point"},
p = if (is.null(p) && !has_explanatory(x)) {.5} else {p}
) %>%
calculate(
stat = "z",
order = if (has_explanatory(x)) {order} else {NULL}
) %>%
dplyr::pull()
results$statistic <- stat
results$chisq_df <- NULL
results
}
|
sirt_import_lavaan_standardizedSolution <- function(...)
{
TAM::require_namespace_msg("lavaan")
res <- lavaan::standardizedSolution(...)
return(res)
}
|
library(shiny)
library(testthat)
test_that("testServer works with dir app", {
testServer(test_path("..", "test-modules", "06_tabsets"), {
session$setInputs(dist="norm", n=5)
expect_length(d(), 5)
session$setInputs(dist="unif", n=6)
expect_length(d(), 6)
})
testServer(test_path("..", "test-modules", "server_r"), {
session$setInputs(dist="norm", n=5)
expect_length(d(), 5)
session$setInputs(dist="unif", n=6)
expect_length(d(), 6)
})
})
test_that("testServer works when referencing external globals", {
testServer(test_path("..", "test-modules", "06_tabsets"), {
expect_equal(get("global", session$env), 123)
})
})
test_that("testServer defaults to the app at .", {
curwd <- getwd()
on.exit(setwd(curwd))
setwd(test_path("..", "test-modules", "06_tabsets"))
testServer(expr = {
expect_equal(get("global", session$env), 123)
})
})
test_that("runTests works with a dir app that calls modules and uses testServer", {
app <- test_path("..", "test-modules", "12_counter")
run <- testthat::expect_output(
print(runTests(app)),
"Shiny App Test Results\\n\\* Success\\n - 12_counter/tests/testthat\\.R"
)
expect_true(all(run$pass))
})
test_that("runTests works with a dir app that calls modules that return reactives and use brushing", {
app <- test_path("..", "test-modules", "107_scatterplot")
run <- testthat::expect_output(
print(runTests(app)),
"Shiny App Test Results\\n\\* Success\\n - 107_scatterplot/tests/testthat\\.R"
)
expect_true(all(run$pass))
})
test_that("a Shiny app object with a module inside can be tested", {
counterUI <- function(id, label = "Counter") {
ns <- NS(id)
tagList(
actionButton(ns("button"), label = label),
verbatimTextOutput(ns("out"))
)
}
counterServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
count <- reactiveVal(0)
observeEvent(input$button, {
count(count() + 1)
})
output$out <- renderText({
count()
})
count
}
)
}
ui <- fluidPage(
textInput("number", "A number"),
textOutput("numberDoubled"),
counterUI("counter1", "Counter
counterUI("counter2", "Counter
)
server <- function(input, output, session) {
counterServer("counter1")
counterServer("counter2")
doubled <- reactive( { as.integer(input$number) * 2 })
output$numberDoubled <- renderText({ doubled() })
}
app <- shinyApp(ui, server)
testServer(app, {
session$setInputs(number = "42")
expect_equal(doubled(), 84)
})
})
test_that("It's an error to pass arguments to a server", {
expect_error(testServer(test_path("..", "test-modules", "06_tabsets"), {}, args = list(an_arg = 123)))
})
|
`scores.pcnm` <-
function(x, choices, ...)
{
if (missing(choices))
x$vectors
else
x$vectors[, choices]
}
|
tri2nb <- function(coords, row.names = NULL) {
if (inherits(coords, "SpatialPoints")) {
if (!is.na(is.projected(coords)) && !is.projected(coords)) {
warning("tri2nb: coordinates should be planar")
}
coords <- coordinates(coords)
} else if (inherits(coords, "sfc")) {
if (!inherits(coords, "sfc_POINT"))
stop("Point geometries required")
if (attr(coords, "n_empty") > 0L)
stop("Empty geometries found")
if (!is.na(sf::st_is_longlat(coords)) && sf::st_is_longlat(coords))
warning("tri2nb: coordinates should be planar")
coords <- sf::st_coordinates(coords)
}
n <- nrow(coords)
if (n < 3) stop("too few coordinates")
if (!is.null(row.names)) {
if(length(row.names) != n)
stop("row.names wrong length")
if (length(unique(row.names)) != length(row.names))
stop("non-unique row.names given")
}
if (is.null(row.names)) row.names <- as.character(1:n)
stopifnot(!anyDuplicated(coords))
tri <- deldir::deldir(x=coords[,1], y=coords[,2])
from <- c(tri$delsgs[,5], tri$delsgs[,6])
to <- c(tri$delsgs[,6], tri$delsgs[,5])
df <- data.frame(from=as.integer(from), to=as.integer(to), weight=1)
attr(df, "n") <- tri$n.data
class(df) <- c(class(df), "spatial.neighbour")
df1 <- df[order(df$from),]
nb <- sn2listw(df1)$neighbours
attr(nb, "region.id") <- row.names
class(nb) <- "nb"
attr(nb, "tri") <- TRUE
attr(nb, "call") <- match.call()
nb <- sym.attr.nb(nb)
nb
}
|
get_random_color <- function() {
r_val <- runif(1, 0, 1)
g_val <- runif(1, 0, 1)
b_val <- runif(1, 0, 1)
alpha_val <- runif(1, 0, 1)
hex_val <- rgb(r_val, g_val, b_val, alpha_val)
return(hex_val)
}
test_that(
"A participant with no graphemes is classified as invalid by check_valid_get_twcv.",
{
p <- Participant$new()
res <- p$check_valid_get_twcv()
expect_false(res$valid)
expect_equal(res$reason_invalid, "no_color_responses")
expect_equal(res$twcv, NA)
})
test_that(
"A participant with just one grapheme is classified as invalid
by check_valid_get_twcv.",
{
p <- Participant$new()
g1 <- Grapheme$new(symbol='a')
g1$set_colors(c("
p$add_grapheme(g1)
res <- p$check_valid_get_twcv()
expect_false(res$valid)
expect_equal(res$reason_invalid, "too_few_graphemes_with_complete_responses")
expect_equal(res$twcv, NA)
})
test_that(
"A participant with two graphemes, of which one includes an NA
response color, is classified as invalid by check_valid_get_twcv
even when min_complete_graphemes is set to 1 and
complete_graphemes_only = FALSE.",
{
p <- Participant$new()
g1 <- Grapheme$new(symbol='a')
g1$set_colors(c("
g2 <- Grapheme$new(symbol='b')
g2$set_colors(c("
p$add_graphemes(list(g1, g2))
res <- p$check_valid_get_twcv(
min_complete_graphemes = 1,
complete_graphemes_only = FALSE
)
expect_false(res$valid)
expect_equal(res$reason_invalid, "hi_prop_tight_cluster")
expect_equal(res$twcv, 0)
})
test_that(
"A participant with 20 graphemes of same color is classified as invalid
by check_valid_get_twcv.",
{
p <- Participant$new()
for (l in LETTERS[1:20]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c("
p$add_grapheme(g)
}
res <- p$check_valid_get_twcv()
expect_false(res$valid)
expect_equal(res$reason_invalid, "few_clusters_low_twcv")
expect_equal(res$twcv, 0)
}
)
test_that(
"A participant with 20 graphemes, with 3 responses each,
of wildly varying (randomly generated) colors is classified as valid."
, {
p <- Participant$new()
for (l in LETTERS[1:20]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c(get_random_color(), get_random_color(), get_random_color()), "Luv")
p$add_grapheme(g)
}
res <- p$check_valid_get_twcv()
expect_true(res$valid)
expect_equal(res$reason_invalid, "")
expect_gt(res$twcv, 500)
}
)
test_that(
"check_valid_get_twcv: A participant with:
15 graphemes, with 2 responses each of wildly
varying (randomly generated) colors, and
8 graphemes of the same color
is classified as invalid when 'complete_graphemes_only = TRUE' (default)."
, {
p <- Participant$new()
for (l in LETTERS[1:15]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c(get_random_color(), get_random_color(), NA), "Luv")
p$add_grapheme(g)
}
for (l in LETTERS[16:23]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c("
p$add_grapheme(g)
}
res <- p$check_valid_get_twcv()
expect_false(res$valid)
expect_equal(res$reason_invalid, "hi_prop_tight_cluster")
expect_lt(res$twcv, 50)
expect_equal(res$num_clusters, 1)
}
)
test_that(
"check_valid_get_twcv: A participant with:
15 graphemes, with 2 responses each of wildly
varying (randomly generated) colors, and
8 graphemes of the same color
is classified as valid when 'complete_graphemes_only = FALSE'."
, {
p <- Participant$new()
for (l in LETTERS[1:15]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c(get_random_color(), get_random_color(), NA), "Luv")
p$add_grapheme(g)
}
for (l in LETTERS[16:23]) {
g <- Grapheme$new(symbol=l)
g$set_colors(c("
p$add_grapheme(g)
}
res <- p$check_valid_get_twcv(complete_graphemes_only = FALSE)
expect_true(res$valid)
expect_equal(res$reason_invalid, "")
expect_gt(res$twcv, 200)
expect_gt(res$num_clusters, 1)
}
)
|
save_models <- function(x, filename = "models.RDS", sanitize_phi = TRUE) {
if (sanitize_phi) {
attr(x, "recipe")$template <- NULL
attr(x, "recipe")$orig_data <- NULL
} else {
message("The model object being saved contains training data, minus ",
"ignored ID columns.\nIf there was PHI in training data, normal ",
"PHI protocols apply to the RDS file.")
}
saveRDS(x, filename)
return(invisible(NULL))
}
load_models <- function(filename) {
if (missing(filename)) {
filename <- file.choose()
mes <- paste0('Loading models. You could automate this with `load_models("',
filename, '")`')
message(mes)
}
x <- readRDS(filename)
attr(x, "loaded_from_rds") <- filename
if (!is.null(attr(x, "recipe")$template) | !is.null(attr(x, "recipe")$orig_data))
message("*** If there was PHI in training data, normal PHI protocols apply",
" to this model object. ***")
return(x)
}
|
expected <- eval(parse(text="NA_complex_"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(c0 = structure(integer(0), .Label = character(0), class = \"factor\")), .Names = \"c0\", row.names = character(0), class = \"data.frame\"), structure(list(c0 = structure(integer(0), .Label = character(0), class = \"factor\")), .Names = \"c0\", row.names = character(0), class = \"data.frame\"))"));
do.call(`as.complex`, argv);
}, o=expected);
|
rm(list=ls())
setwd("C:/Users/Tom/Documents/Kaggle/Santander/Data")
library(data.table)
library(bit64)
smallFraction <- 0.1
set.seed(14)
train <- fread("train_ver2.csv")
test <- fread("test_ver2.csv")
sampleSubmission <- fread("sample_submission.csv")
setkey(train, ncodpers)
setkey(test, ncodpers)
setkey(sampleSubmission, ncodpers)
table(train[[11]])
table(train[[12]])
table(train[[16]])
table(test[[11]])
table(test[[12]])
table(test[[16]])
numIdsTrain <- !train[[12]] %in% c("", "P")
train[[12]][numIdsTrain] <- as.numeric(train[[12]][numIdsTrain])
table(train[[12]])
test[[12]] <- as.character(test[[12]])
train$fecha_dato <- as.Date(train$fecha_dato, format="%Y-%m-%d")
test$fecha_dato <- as.Date(test$fecha_dato, format="%m/%d/%Y")
train$fecha_alta <- as.Date(train$fecha_alta, format="%Y-%m-%d")
test$fecha_alta <- as.Date(test$fecha_alta, format="%m/%d/%Y")
train$ult_fec_cli_1t <- as.Date(train$ult_fec_cli_1t, format="%Y-%m-%d")
test$ult_fec_cli_1t <- as.Date(test$ult_fec_cli_1t, format="%m/%d/%Y")
table(train$canal_entrada)
train$canal_entrada[!is.na(as.numeric(train$canal_entrada))] <-
suppressWarnings(
as.numeric(train$canal_entrada[!is.na(as.numeric(train$canal_entrada))])
)
table(train$canal_entrada)
nbTestCol <- ncol(test)
sameTrainTestClass <- sapply(test, class) == sapply(train[, 1:nbTestCol,
with=FALSE], class)
table(sameTrainTestClass)
if(any(!sameTrainTestClass)) browser()
uniqueCustomers <- sort(unique(train$ncodpers))
randomCustomers <- sample(uniqueCustomers,
round(length(uniqueCustomers)*smallFraction))
trainSmallRandom <- train[ncodpers %in% randomCustomers,]
testSmallRandom <- test[ncodpers %in% randomCustomers,]
cutoffNcodpers <- uniqueCustomers[round(length(uniqueCustomers)*smallFraction)]
trainSmallOrdered <- train[ncodpers <= cutoffNcodpers,]
testSmallOrdered <- test[ncodpers <= cutoffNcodpers,]
saveRDS(train, file.path(getwd(), "train.rds"))
saveRDS(test, file.path(getwd(), "test.rds"))
saveRDS(trainSmallRandom, file.path(getwd(), "trainSmallRandom.rds"))
saveRDS(testSmallRandom, file.path(getwd(), "testSmallRandom.rds"))
saveRDS(trainSmallOrdered, file.path(getwd(), "trainSmallOrdered.rds"))
saveRDS(testSmallOrdered, file.path(getwd(), "testSmallOrdered.rds"))
|
ptree_y <- function(newtree, node_id) {
p <- predict_party(newtree, node_id)[[1]]
return(p)
}
|
renderWebGL <- function(expr, width="auto", height="auto", env = parent.frame(),
quoted = FALSE){
func <- exprToFunction(expr, env, quoted)
return(function(shinysession, name, ...) {
open3d(useNULL = TRUE)
func()
prefix <- "gl_output_"
if (width == "auto") width <- shinysession$clientData[[paste(prefix,
name, "_width", sep = "")]]
if (height == "auto") height <- shinysession$clientData[[paste(prefix,
name, "_height", sep = "")]]
if (is.null(width) || is.null(height) || width <= 0 ||
height <= 0) return(NULL)
if (is.null(width) || !is.numeric(width)){
stop("Can't support non-numeric width parameter. 'width' must be in px.")
}
if (is.null(height) || !is.numeric(height)){
stop("Can't support non-numeric height parameter. 'height' must be in px.")
}
zoom <-
isolate(shinysession$clientData[[paste(prefix, name, "_zoom", sep="")]])
fov <-
isolate(shinysession$clientData[[paste(prefix, name, "_fov", sep="")]])
pan <-
isolate(shinysession$clientData[[paste(prefix, name, "_pan", sep="")]])
if (!is.null(zoom)){
par3d(zoom = zoom)
}
if (!is.null(fov)){
par3d(FOV=fov)
}
if (!is.null(pan)){
mat <- matrix(pan, ncol=4)
par3d(userMatrix=mat)
}
id <- paste(sample(c(letters, LETTERS), 10), collapse="")
tempDir <- paste(tempdir(), "/", id, "/", sep="")
tempFile <- file(file.path(tempdir(), paste(id,".html", sep="")), "w");
writeLines(paste("%", id, "WebGL%", sep=""),
tempFile)
close(tempFile)
writeWebGL(dir=tempDir, snapshot= FALSE,
template=file.path(tempdir(),paste(id,'.html', sep="")),
height=height, width=width, prefix=id)
lines <- readLines(paste(tempDir, "/index.html", sep=""))
lines <- lines[-1]
unlink(tempDir, recursive=TRUE)
unlink(paste(tempdir(), id,".html", sep=""))
rgl.close()
toRet <- paste(lines, collapse="\n")
return(list(prefix=id,html=HTML(toRet)))
})
}
|
iedb_arb_mhcii_nmer <-
function(clas)
{
i1=1
i2=length(dir(pattern=".Rdata"))
for(i in i1:i2)
{
load(dir(pattern=".Rdata")[i])
temp=ls(pattern=clas)
temp2=lapply(temp,function(x)
{tempm=get(x);
lapply(tempm,function(x)
{x@Core_Sequence}
)
}
)
org=NULL;for(j in 1:length(temp)){org=append(org,strsplit(temp[j],split="_",fixed=T)[[1]][1])}
rv=which(org=="mtbh37rv")
temp4=NULL; for(k in 1:length(temp2[[rv]])){for(l in 1:length(temp2)){temp4=c(temp4, length(intersect(temp2[[l]],temp2[[rv]][k])))}}
temp5=matrix(temp4, nrow=length(temp2[[rv]]), ncol=length(temp), byrow=T)
check1 = strsplit(temp,"_", fixed = TRUE);check2 = unlist(lapply(check1, function(x){return(x[1])}));
colnames(temp5)= check2
epitope_seq= as.matrix(temp2[[rv]],ncol=1,byrow=T)
gi_number=as.matrix(strsplit(temp[rv],split="epitopes",fixed=T)[[1]][2],ncol=1,byrow=T)
orthologs=as.matrix(length(temp)-1,ncol=1,byrow=T)
epitope_length=NULL;for(i in 1:length(get(temp[rv])))
{epitope_length=append(epitope_length,get(temp[rv])[[i]]@epitope_length)}
class=as.matrix("iedb_arb_mhcii",ncol=1,byrow=T);
allele=unlist(lapply(get(temp[rv]),function(x){x@Allele}))
conservation_ratio=NULL;for(m in 1:nrow(temp5))
{conservation_ratio=append(conservation_ratio,sum(temp5[m,1:ncol(temp5)])-1)}
checka=unlist(lapply(get(temp[rv]),function(x){x@IC50}))
temp6=as.data.frame(temp5)
temp6=cbind(gi_number,checka,allele,orthologs,epitope_length,epitope_seq,conservation_ratio,class,temp6)
colnames(temp6)[1:8]=c("ginumber","score","Allele","Number_of_Orthologs","Epitope_Length","Epitope_Sequence","Epitope_Conservation_Ratio","class")
temp7=temp6[1:nrow(temp6),1:8]
out <- data.frame(lapply(temp7, function(x) factor(unlist(x))))
metadata=cbind(as.character(out$ginumber),as.character(out$Allele),as.character(out$score),as.character(out$Epitope_Sequence),as.character(out$class),temp5)
colnames(metadata)[1:5]=c("ginumber","Allele","score","Epitope_Sequence","class")
write.table(out,file=paste("iedb_arb_mhcii_",strsplit(temp[rv],split="epitopes",fixed=T)[[1]][2],".txt",sep=""),sep="\t",row.names=F)
write.table(metadata,file=paste("iedb_arb_mhcii_",strsplit(temp[rv],split="epitopes",fixed=T)[[1]][2],"_metadata.txt",sep=""),sep="\t",row.names=F)
rm(list= ls()[!(ls() %in% c('clas'))])
}
}
|
sigma2j_cumh <- function(arm, teval) {
if (teval < 0 | teval >= arm$total_time) {
stop(paste("Time of evaluation must be in the interval [0, ", arm$total_time, ").", sep=""))
}
stats::integrate(function(x) hsurv(x, arm) / prob_risk(arm, x),
lower=0,
upper=teval)$value
}
sigma2j_surv <- function(arm, teval) {
psurv(teval, arm, lower.tail=F)^2 * sigma2j_cumh(arm, teval)
}
sigma2j_perc <- function(arm, perc) {
teval <- qsurv(perc, arm)
sigma2j_cumh(arm, teval) / hsurv(teval, arm)^2
}
deltaj_rmst <- function(x, arm) {
stats::integrate(function(y) psurv(y, arm, lower.tail=F),
lower=0,
upper=x)$value
}
sigma2j_rmst <- function(arm, teval) {
inner <- function(x) {
sapply(x, function(x1) stats::integrate(function(x2) psurv(x2, arm, lower.tail=F),
lower=x1,
upper=teval)$value
)
}
stats::integrate(function(x) inner(x)^2 * hsurv(x, arm) / prob_risk(arm, x),
lower=0,
upper=teval)$value
}
weight_wlr <- function(x, arm0, arm1, weight="1") {
n <- arm0$size + arm1$size
p1 <- arm1$size / n
p0 <- 1 - p1
if (weight=="1") {
1
} else if (weight=="n") {
n * (p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x))
} else if (weight=="sqrtN") {
sqrt( n * (p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x)) )
} else if (grepl("FH", weight)) {
weight <- strsplit(weight, "_")[[1]]
p <- as.numeric(substring(weight[2], 2))
q <- as.numeric(substring(weight[3], 2))
esurv <- p0 * psurv(x, arm0) + p1 * psurv(x, arm1)
esurv^p * (1-esurv)^q
} else {
stop("Please specify valid weight function.")
}
}
delta_wlr <- function(arm0, arm1, weight="1", approx="asymptotic") {
p1 <- arm1$size / (arm0$size + arm1$size)
p0 <- 1 - p1
if (approx == "event driven") {
if (sum(arm0$surv_shape != arm1$surv_shape) > 0 |
length( unique(arm1$surv_scale / arm0$surv_scale) ) > 1) {
stop("Hazard is not proportional over time.", call.=F)
} else if (weight != "1") {
stop("Weight must equal `1`.", call.=F)
}
theta <- c(arm0$surv_shape * log( arm1$surv_scale / arm0$surv_scale ))[1]
nu <- p0 * prob_event(arm0) + p1 * prob_event(arm1)
delta <- theta * p0 * p1 * nu
} else if (approx == "asymptotic") {
delta <- stats::integrate(function(x) weight_wlr(x, arm0, arm1, weight) *
(1 / p0 / prob_risk(arm0, x) + 1 / p1 / prob_risk(arm1, x)) ^ (-1) *
( hsurv(x, arm1) - hsurv(x, arm0) ),
lower=0,
upper=arm0$total_time)$value
} else if (approx == "generalized schoenfeld") {
delta <- stats::integrate(function(x) weight_wlr(x, arm0, arm1, weight) *
log( hsurv(x, arm1) / hsurv(x, arm0) ) *
p0 * prob_risk(arm0, x) * p1 * prob_risk(arm1, x) /
( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) )^2 *
( p0 * dens_event(arm0, x) + p1 * dens_event(arm1, x)),
lower=0,
upper=arm0$total_time)$value
} else {
stop("Please specify a valid approximation for the mean.", call.=F)
}
return(delta)
}
deltaj_wlr <- function(j, arm0, arm1, weight="1") {
p1 <- arm1$size / (arm0$size + arm1$size)
p0 <- 1 - p1
if (j==0) {
arm <- arm0
} else {
arm <- arm1
}
stats::integrate(function(x) weight_wlr(x, arm0, arm1, weight) *
(j - p1 * prob_risk(arm1, x) /
( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) )) *
(dens_event(arm, x) -
prob_risk(arm, x) *
( p0 * dens_event(arm0, x) + p1 * dens_event(arm1, x) ) /
( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) )),
lower=0,
upper=arm0$total_time)$value
}
sigma2_wlr <- function(arm0, arm1, weight="1", approx="asymptotic") {
p1 <- arm1$size / (arm0$size + arm1$size)
p0 <- 1 - p1
if (approx == "event driven") {
nu <- p0 * prob_event(arm0) + p1 * prob_event(arm1)
sigma2 <- p0 * p1 * nu
} else if (approx %in% c("asymptotic", "generalized schoenfeld")) {
sigma2 <- stats::integrate(function(x) weight_wlr(x, arm0, arm1, weight)^2 *
p0 * prob_risk(arm0, x) * p1 * prob_risk(arm1, x) /
( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) )^2 *
( p0 * dens_event(arm0, x) + p1 * dens_event(arm1, x)),
lower=0,
upper=arm0$total_time)$value
} else {
stop("Please specify a valid approximation for the mean.", call.=F)
}
return(sigma2)
}
sigma2j_wlr <- function(j, arm0, arm1, weight="1") {
p1 <- arm1$size / (arm0$size + arm1$size)
p0 <- 1 - p1
if (j==0) {
arm <- arm0
} else {
arm <- arm1
}
inner <- function(x) {
sapply(x, function(x1)
stats::integrate(function(x2) weight_wlr(x2, arm0, arm1, weight) *
(j - p1 * prob_risk(arm1, x2) / ( p0 * prob_risk(arm0, x2) + p1 * prob_risk(arm1, x2) )) *
( p0 * dens_event(arm0, x2) + p1 * dens_event(arm1, x2) ) /
( p0 * prob_risk(arm0, x2) + p1 * prob_risk(arm1, x2) ),
lower=0,
upper=x1)$value
)
}
sigma2jA <- stats::integrate(function(x) weight_wlr(x, arm0, arm1, weight)^2 *
(j - p1 * prob_risk(arm1, x) / ( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) ))^2 *
dens_event(arm, x),
lower=0,
upper=arm0$total_time)$value
sigma2jB <- -1 * deltaj_wlr(j, arm0, arm1, weight)^2
sigma2jC <- 2 * stats::integrate(function(x) inner(x) *
weight_wlr(x, arm0, arm1, weight) *
(j - p1 * prob_risk(arm1, x) / ( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) )) *
(( p0 * dens_event(arm0, x) + p1 * dens_event(arm1, x) ) /
( p0 * prob_risk(arm0, x) + p1 * prob_risk(arm1, x) ) *
prob_risk(arm, x) -
dens_event(arm, x)),
lower=0,
upper=arm0$total_time)$value
sigma2jA + sigma2jB + sigma2jC
}
tsigma2_wlr <- function(arm0, arm1, weight="1", approx="block") {
p1 <- arm1$size / (arm0$size + arm1$size)
p0 <- 1 - p1
if (approx %in% c("block", "simple")) {
tsigma2 <- p0 * sigma2j_wlr(0, arm0, arm1, weight) +
p1 * sigma2j_wlr(1, arm0, arm1, weight)
if (approx == "simple") {
tsigma2 <- p0 *
p1 *
(deltaj_wlr(0, arm0, arm1, weight) - deltaj_wlr(1, arm0, arm1, weight))^2 +
tsigma2
}
} else {
stop("Please specify a valid approximation for the variance.", call.=F)
}
return(tsigma2)
}
sigma2_clhr <- function(arm0, arm1) {
if (sum(arm0$surv_shape!=arm1$surv_shape)>0 |
length(unique(arm1$surv_scale/arm0$surv_scale))>1) {
warning("Hazard is not proportional over time.")
}
p1 <- arm1$size / (arm0$size + arm1$size)
1 / stats::integrate(function(x) ( 1 / (1 - p1) / dens_event(arm0, x) +
1/ p1 / dens_event(arm1, x) ) ^ (-1),
lower=0,
upper=arm0$total_time)$value
}
|
qlomax <- function (p, scale, shape) {
.Deprecated("VGAM::qlomax", package = "surveillance")
scale * ((1-p)^(-1/shape) - 1)
}
|
ht_single_prop_theo <- function(y, success, null, alternative, y_name,
show_var_types, show_summ_stats, show_res,
show_eda_plot, show_inf_plot){
n <- length(y)
p_hat <- sum(y == success) / n
se <- sqrt(p_hat * (1 - p_hat) / n)
z <- (p_hat - null) / se
if(alternative == "greater"){ x_min = p_hat; x_max = Inf }
if(alternative == "less"){ x_min = -Inf; x_max = p_hat }
if(alternative == "twosided"){
if(p_hat >= null){
x_min = c(null - (p_hat - null), p_hat)
x_max = c(-Inf, Inf)
}
if(p_hat <= null){
x_min = c(p_hat, null + (null - p_hat))
x_max = c(-Inf, Inf)
}
}
if(alternative == "greater"){ p_value <- pnorm(z, lower.tail = FALSE) }
if(alternative == "less"){ p_value <- pnorm(z, lower.tail = TRUE) }
if(alternative == "twosided"){
p_value <- 2 * pnorm(abs(z), lower.tail = FALSE)
}
if(show_var_types == TRUE){
cat(paste0("Single categorical variable, success: ", success,"\n"))
}
if(show_summ_stats == TRUE){
cat(paste0("n = ", n, ", p-hat = ", round(p_hat, 4), "\n"))
}
if(show_res == TRUE){
if(alternative == "greater"){
alt_sign <- ">"
} else if(alternative == "less"){
alt_sign <- "<"
} else {
alt_sign <- "!="
}
cat(paste0("H0: p = ", null, "\n"))
cat(paste0("HA: p ", alt_sign, " ", null, "\n"))
p_val_to_print <- ifelse(round(p_value, 4) == 0, "< 0.0001", round(p_value, 4))
cat(paste0("z = ", round(z, 4), "\n"))
cat(paste0("p_value = ", p_val_to_print))
}
d_eda <- data.frame(y = y)
eda_plot <- ggplot2::ggplot(data = d_eda, ggplot2::aes(x = y), environment = environment()) +
ggplot2::geom_bar(fill = "
ggplot2::xlab(y_name) +
ggplot2::ylab("") +
ggplot2::ggtitle("Sample Distribution")
d_for_plot <- data.frame(x = c(null - 4*se, null + 4*se))
inf_plot <- ggplot2::ggplot(d_for_plot, ggplot2::aes_string(x = 'x')) +
ggplot2::stat_function(fun = dnorm, args = list(mean = null, sd = se), color = "
ggplot2::annotate("rect", xmin = x_min, xmax = x_max, ymin = 0, ymax = Inf,
alpha = 0.3, fill = "
ggplot2::ggtitle("Null Distribution") +
ggplot2::xlab("") +
ggplot2::ylab("") +
ggplot2::geom_vline(xintercept = p_hat, color = "
if(show_eda_plot & !show_inf_plot){
print(eda_plot)
}
if(!show_eda_plot & show_inf_plot){
print(inf_plot)
}
if(show_eda_plot & show_inf_plot){
gridExtra::grid.arrange(eda_plot, inf_plot, ncol = 2)
}
return(list(SE = se, z = z, p_value = p_value))
}
|
summary.stratEst.data <- function( object , ...){
c("stratEst.data", NextMethod())
}
|
FitFile <- function(conn) {
header <- NA
bytes_left <- NA
update_bytes_left <- function(.bytes_read) {
bytes_left <<- bytes_left + .bytes_read
}
def_mesgs <- list(mesgs = NULL, nums = NULL)
def_mesg_counter <- 1
append_def_mesg <- function(def_mesg) {
def_mesgs$mesgs[[def_mesg_counter]] <<- def_mesg
def_mesgs$nums[[def_mesg_counter]] <<- def_mesg$local_mesg_num
def_mesg_counter <<- def_mesg_counter + 1
def_mesg
}
fetch_def_mesg <- function(num) {
def_mesgs$mesgs[[
match(num, def_mesgs$nums, nomatch = NA_integer_)]]
}
data_mesgs <- list()
data_mesg_counter <- 1
append_data_mesg <- function(data_mesg) {
data_mesgs[[data_mesg_counter]] <<- data_mesg
data_mesg_counter <<- data_mesg_counter + 1
data_mesg
}
environment()
}
|
accrual.T.hedging <-
function(n,T,m,tm,np){
S=1000
Pgrid=seq(1:S)/S
logPlike=(n*Pgrid)*log(T*Pgrid)+lgamma(n*Pgrid+m)-(n*Pgrid+m)*log(T*Pgrid+tm)-lgamma(n*Pgrid)
Pdensity=exp(logPlike+100)/sum(exp(logPlike+100))
Ppost=sample(Pgrid,10000,prob=Pdensity,replace=TRUE)
theta=1/rgamma(S,shape=n*Ppost+m,rate=T*Ppost+tm)
simulated.duration=rep(NA,S)
for (i in 1:S) {
wait=rexp(np-m,1/theta[i])
simulated.duration[i]=tm+sum(wait)
}
P.hedging=quantile(Ppost,prob=c(0.025,0.5,0.975))
TOT.hedging=quantile(simulated.duration, prob=c(0.025, 0.5,0.975))
return(list(TOT.hedging,P.hedging,simulated.duration))
}
|
group.mean <- function(var, grp) {
grp <- as.factor(grp)
grp <- as.numeric(grp)
var <- as.numeric(var)
return(tapply(var, grp, mean, na.rm = TRUE)[grp])
}
|
context("PipeOpTargetMutate")
test_that("PipeOpTargetMutate - basic properties", {
expect_pipeop_class(PipeOpTargetMutate, list(id = "po"))
po = PipeOpTargetMutate$new("po")
expect_pipeop(po)
g = Graph$new()
g$add_pipeop(PipeOpTargetMutate$new())
g$add_pipeop(LearnerRegrRpart$new())
g$add_pipeop(PipeOpTargetInvert$new())
g$add_edge(src_id = "targetmutate", dst_id = "targetinvert", src_channel = 1L, dst_channel = 1L)
g$add_edge(src_id = "targetmutate", dst_id = "regr.rpart", src_channel = 2L, dst_channel = 1L)
g$add_edge(src_id = "regr.rpart", dst_id = "targetinvert", src_channel = 1L, dst_channel = 2L)
expect_graph(g)
task = mlr_tasks$get("boston_housing")
task_copy = task$clone(deep = TRUE)
address_in = address(task)
train_out = g$train(task)
expect_null(train_out[[1L]])
expect_length(g$state[[1L]], 0L)
expect_length(g$state[[3L]], 0L)
predict_out = g$predict(task)
expect_equal(task, task_copy)
expect_equal(address_in, address(task))
learner = LearnerRegrRpart$new()
learner$train(task)
expect_equal(learner$predict(task), predict_out[[1L]])
})
test_that("PipeOpTargetMutate - log base 2 trafo", {
g = Graph$new()
g$add_pipeop(PipeOpTargetMutate$new("logtrafo",
param_vals = list(
trafo = function(x) log(x, base = 2),
inverter = function(x) list(response = 2 ^ x$response))
)
)
g$add_pipeop(LearnerRegrRpart$new())
g$add_pipeop(PipeOpTargetInvert$new())
g$add_edge(src_id = "logtrafo", dst_id = "targetinvert", src_channel = 1L, dst_channel = 1L)
g$add_edge(src_id = "logtrafo", dst_id = "regr.rpart", src_channel = 2L, dst_channel = 1L)
g$add_edge(src_id = "regr.rpart", dst_id = "targetinvert", src_channel = 1L, dst_channel = 2L)
task = mlr_tasks$get("boston_housing")
train_out = g$train(task)
predict_out = g$predict(task)
dat = task$data()
dat$medv = log(dat$medv, base = 2)
task_log = TaskRegr$new("boston_housing_log", backend = dat, target = "medv")
learner = LearnerRegrRpart$new()
learner$train(task_log)
learner_predict_out = learner$predict(task_log)
expect_equal(2 ^ learner_predict_out$truth, predict_out[[1L]]$truth)
expect_equal(2 ^ learner_predict_out$response, predict_out[[1L]]$response)
})
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(PupillometryR)
data("pupil_data")
pupil_data$ID <- as.character(pupil_data$ID)
pupil_data <- subset(pupil_data, ID != 8)
pupil_data$LPupil[pupil_data$LPupil == -1] <- NA
pupil_data$RPupil[pupil_data$RPupil == -1] <- NA
library(ggplot2)
theme_set(theme_classic(base_size = 12))
Sdata <- make_pupillometryr_data(data = pupil_data,
subject = ID,
trial = Trial,
time = Time,
condition = Type)
new_data <- replace_missing_data(data = Sdata)
head(new_data)
plot(new_data, pupil = LPupil, group = 'condition')
plot(new_data, pupil = LPupil, group = 'subject')
regressed_data <- regress_data(data = new_data,
pupil1 = RPupil,
pupil2 = LPupil)
mean_data <- calculate_mean_pupil_size(data = regressed_data,
pupil1 = RPupil,
pupil2 = LPupil)
plot(mean_data, pupil = mean_pupil, group = 'subject')
mean_data <- downsample_time_data(data = mean_data,
pupil = mean_pupil,
timebin_size = 50,
option = 'median')
missing <- calculate_missing_data(mean_data,
mean_pupil)
head(missing)
mean_data2 <- clean_missing_data(mean_data,
pupil = mean_pupil,
trial_threshold = .75,
subject_trial_threshold = .75)
filtered_data <- filter_data(data = mean_data2,
pupil = mean_pupil,
filter = 'median',
degree = 11)
plot(filtered_data, pupil = mean_pupil, group = 'subject')
int_data <- interpolate_data(data = filtered_data,
pupil = mean_pupil,
type = 'linear')
plot(int_data, pupil = mean_pupil, group = 'subject')
base_data <- baseline_data(data = int_data,
pupil = mean_pupil,
start = 0,
stop = 100)
plot(base_data, pupil = mean_pupil, group = 'subject')
window <- create_window_data(data = base_data,
pupil = mean_pupil)
plot(window, pupil = mean_pupil, windows = F, geom = 'boxplot')
head(window)
t.test(mean_pupil ~ Type, paired = T, data = window)
timeslots <- create_time_windows(data = base_data,
pupil = mean_pupil,
breaks = c(0, 2000, 4000, 6000, 8000, 10000))
plot(timeslots, pupil = mean_pupil, windows = T, geom = 'raincloud')
head(timeslots)
lm(mean_pupil ~ Window * Type, data = timeslots)
library(mgcv)
base_data$IDn <- as.numeric(base_data$ID)
base_data$Typen <- ifelse(base_data$Type == 'Easy', .5, -.5)
base_data$Trialn <- as.numeric(substr(base_data$Trial, 5, 5))
base_data$Trialn <- ifelse(base_data$Typen == .5, base_data$Trialn, base_data$Trialn + 3)
base_data$ID <- as.factor(base_data$ID)
base_data$Trial <- as.factor(base_data$Trial)
m1 <- bam(mean_pupil ~ s(Time) +
s(Time, by = Typen),
data = base_data,
family = gaussian)
summary(m1)
plot(base_data, pupil = mean_pupil, group = 'condition', model = m1)
qqnorm(resid(m1))
itsadug::acf_resid(m1)
base_data$Event <- interaction(base_data$ID, base_data$Trial, drop = T)
model_data <- base_data
model_data <- itsadug::start_event(model_data,
column = 'Time', event = 'Event')
model_data <- droplevels(model_data[order(model_data$ID,
model_data$Trial,
model_data$Time),])
m2 <- bam(mean_pupil ~ Typen +
s(Time, by = Typen) +
s(Time, Event, bs = 'fs', m = 1),
data = base_data,
family = gaussian,
discrete = T,
AR.start = model_data$start.event, rho = .6)
summary(m2)
qqnorm(resid(m2))
itsadug::acf_resid(m2)
plot(base_data, pupil = mean_pupil, group = 'condition', model = m2)
differences <- create_difference_data(data = base_data,
pupil = mean_pupil)
plot(differences, pupil = mean_pupil, geom = 'line')
spline_data <- create_functional_data(data = differences,
pupil = mean_pupil,
basis = 10,
order = 4)
plot(spline_data, pupil = mean_pupil, geom = 'line', colour = 'blue')
ft_data <- run_functional_t_test(data = spline_data,
pupil = mean_pupil,
alpha = 0.05)
plot(ft_data, show_divergence = T, colour = 'red', fill = 'orange')
|
rocsvm.solve <- function(K, lambda, rho = 1, eps = 1.0e-8)
{
N <- dim(K)[1]
obj <- solve.QP(Dmat = (K + diag(rep(eps, N)))/lambda,
dvec = rep(rho, N),
Amat = cbind(diag(N), -diag(N)),
bvec = c(rep(0, N), rep(-1, N)))
value <- list(alpha = obj$solution, value = obj$value)
return(value)
}
|
calcOrigin <- function(x1, y1, x2, y2, origin, hand) {
xm <- (x1 + x2)/2
ym <- (y1 + y2)/2
dx <- x2 - x1
dy <- y2 - y1
slope <- dy/dx
oslope <- -1/slope
tmpox <- ifelse(!is.finite(slope),
xm,
ifelse(!is.finite(oslope),
xm + origin*(x2 - x1)/2,
xm + origin*(x2 - x1)/2))
tmpoy <- ifelse(!is.finite(slope),
ym + origin*(y2 - y1)/2,
ifelse(!is.finite(oslope),
ym,
ym + origin*(y2 - y1)/2))
sintheta <- -1
ox <- xm - (tmpoy - ym)*sintheta
oy <- ym + (tmpox - xm)*sintheta
list(x=ox, y=oy)
}
interleave <- function(ncp, ncurve, val, sval, eval, e) {
sval <- rep(sval, length.out=ncurve)
eval <- rep(eval, length.out=ncurve)
result <- matrix(NA, ncol=ncurve, nrow=ncp+1)
m <- matrix(val, ncol=ncurve)
for (i in 1L:ncurve) {
if (e[i])
result[,i] <- c(m[,i], eval[i])
else
result[,i] <- c(sval[i], m[,i])
}
as.numeric(result)
}
calcSquareControlPoints <- function(x1, y1, x2, y2,
curvature, angle, ncp,
debug=FALSE) {
dx <- x2 - x1
dy <- y2 - y1
slope <- dy/dx
end <- (slope > 1 |
(slope < 0 & slope > -1))
if (curvature < 0)
end <- !end
startx <- ifelse(end,
x1,
ifelse(abs(slope) > 1, x2 - dx, x2 - sign(slope)*dy))
starty <- ifelse(end,
y1,
ifelse(abs(slope) > 1, y2 - sign(slope)*dx, y2 - dy))
endx <- ifelse(end,
ifelse(abs(slope) > 1, x1 + dx, x1 + sign(slope)*dy),
x2)
endy <- ifelse(end,
ifelse(abs(slope) > 1, y1 + sign(slope)*dx, y1 + dy),
y2)
cps <- calcControlPoints(startx, starty, endx, endy,
curvature, angle, ncp,
debug)
ncurve <- length(x1)
cps$x <- interleave(ncp, ncurve, cps$x, startx, endx, end)
cps$y <- interleave(ncp, ncurve, cps$y, starty, endy, end)
list(x=cps$x, y=cps$y, end=end)
}
calcControlPoints <- function(x1, y1, x2, y2, curvature, angle, ncp,
debug=FALSE) {
xm <- (x1 + x2)/2
ym <- (y1 + y2)/2
dx <- x2 - x1
dy <- y2 - y1
slope <- dy/dx
if (is.null(angle)) {
angle <- ifelse(slope < 0,
2*atan(abs(slope)),
2*atan(1/slope))
} else {
angle <- angle/180*pi
}
sina <- sin(angle)
cosa <- cos(angle)
cornerx <- xm + (x1 - xm)*cosa - (y1 - ym)*sina
cornery <- ym + (y1 - ym)*cosa + (x1 - xm)*sina
if (debug) {
grid.points(cornerx, cornery, default.units="inches",
pch=16, size=unit(3, "mm"),
gp=gpar(col="grey"))
}
beta <- -atan((cornery - y1)/(cornerx - x1))
sinb <- sin(beta)
cosb <- cos(beta)
newx2 <- x1 + dx*cosb - dy*sinb
newy2 <- y1 + dy*cosb + dx*sinb
scalex <- (newy2 - y1)/(newx2 - x1)
newx1 <- x1*scalex
newx2 <- newx2*scalex
ratio <- 2*(sin(atan(curvature))^2)
origin <- curvature - curvature/ratio
if (curvature > 0)
hand <- "right"
else
hand <- "left"
oxy <- calcOrigin(newx1, y1, newx2, newy2, origin, hand)
ox <- oxy$x
oy <- oxy$y
dir <- switch(hand,
left=-1,
right=1)
maxtheta <- pi + sign(origin*dir)*2*atan(abs(origin))
theta <- seq(0, dir*maxtheta,
dir*maxtheta/(ncp + 1))[c(-1, -(ncp + 2))]
costheta <- cos(theta)
sintheta <- sin(theta)
cpx <- ox + ((newx1 - ox) %*% t(costheta)) -
((y1 - oy) %*% t(sintheta))
cpy <- oy + ((y1 - oy) %*% t(costheta)) +
((newx1 - ox) %*% t(sintheta))
cpx <- cpx/scalex
sinnb <- sin(-beta)
cosnb <- cos(-beta)
finalcpx <- x1 + (cpx - x1)*cosnb - (cpy - y1)*sinnb
finalcpy <- y1 + (cpy - y1)*cosnb + (cpx - x1)*sinnb
if (debug) {
ox <- ox/scalex
fox <- x1 + (ox - x1)*cosnb - (oy - y1)*sinnb
foy <- y1 + (oy - y1)*cosnb + (ox - x1)*sinnb
grid.points(fox, foy, default.units="inches",
pch=16, size=unit(1, "mm"),
gp=gpar(col="grey"))
grid.circle(fox, foy, sqrt((ox - x1)^2 + (oy - y1)^2),
default.units="inches",
gp=gpar(col="grey"))
}
list(x=as.numeric(t(finalcpx)), y=as.numeric(t(finalcpy)))
}
cbDiagram <- function(x1, y1, x2, y2, cps) {
grid.segments(x1, y1, x2, y2,
gp=gpar(col="grey"),
default.units="inches")
grid.points(x1, y1, pch=16, size=unit(1, "mm"),
gp=gpar(col="green"),
default.units="inches")
grid.points(x2, y2, pch=16, size=unit(1, "mm"),
gp=gpar(col="red"),
default.units="inches")
grid.points(cps$x, cps$y, pch=16, size=unit(1, "mm"),
default.units="inches",
gp=gpar(col="blue"))
}
straightCurve <- function(x1, y1, x2, y2, arrow, debug) {
if (debug) {
xm <- (x1 + x2)/2
ym <- (y1 + y2)/2
cbDiagram(x1, y1, x2, y2, list(x=xm, y=ym))
}
segmentsGrob(x1, y1, x2, y2,
default.units="inches",
arrow=arrow, name="segment")
}
calcCurveGrob <- function(x, debug) {
x1 <- x$x1
x2 <- x$x2
y1 <- x$y1
y2 <- x$y2
curvature <- x$curvature
angle <- x$angle
ncp <- x$ncp
shape <- x$shape
square <- x$square
squareShape <- x$squareShape
inflect <- x$inflect
arrow <- x$arrow
open <- x$open
x1 <- convertX(x1, "inches", valueOnly=TRUE)
y1 <- convertY(y1, "inches", valueOnly=TRUE)
x2 <- convertX(x2, "inches", valueOnly=TRUE)
y2 <- convertY(y2, "inches", valueOnly=TRUE)
if (any(x1 == x2 & y1 == y2))
stop("end points must not be identical")
maxn <- max(length(x1),
length(y1),
length(x2),
length(y2))
x1 <- rep(x1, length.out=maxn)
y1 <- rep(y1, length.out=maxn)
x2 <- rep(x2, length.out=maxn)
y2 <- rep(y2, length.out=maxn)
if (!is.null(arrow))
arrow <- rep(arrow, length.out=maxn)
if (curvature == 0) {
children <- gList(straightCurve(x1, y1, x2, y2, arrow, debug))
} else {
if (angle < 1 || angle > 179) {
children <- gList(straightCurve(x1, y1, x2, y2, arrow, debug))
} else {
if (square && any(x1 == x2 | y1 == y2)) {
subset <- x1 == x2 | y1 == y2
straightGrob <- straightCurve(x1[subset], y1[subset],
x2[subset], y2[subset],
arrow, debug)
x1 <- x1[!subset]
x2 <- x2[!subset]
y1 <- y1[!subset]
y2 <- y2[!subset]
if (!is.null(arrow))
arrow <- arrow[!subset]
} else {
straightGrob <- NULL
}
ncurve <- length(x1)
if (ncurve == 0) {
children <- gList(straightGrob)
} else {
if (inflect) {
xm <- (x1 + x2)/2
ym <- (y1 + y2)/2
shape1 <- rep(rep(shape, length.out=ncp), ncurve)
shape2 <- rev(shape1)
if (square) {
cps1 <- calcSquareControlPoints(x1, y1, xm, ym,
curvature, angle,
ncp,
debug=debug)
cps2 <- calcSquareControlPoints(xm, ym, x2, y2,
-curvature, angle,
ncp,
debug=debug)
shape1 <- interleave(ncp, ncurve, shape1,
squareShape, squareShape,
cps1$end)
shape2 <- interleave(ncp, ncurve, shape2,
squareShape, squareShape,
cps2$end)
ncp <- ncp + 1
} else {
cps1 <- calcControlPoints(x1, y1, xm, ym,
curvature, angle, ncp,
debug=debug)
cps2 <- calcControlPoints(xm, ym, x2, y2,
-curvature, angle, ncp,
debug=debug)
}
if (debug) {
cbDiagram(x1, y1, xm, ym, cps1)
cbDiagram(xm, ym, x2, y2, cps2)
}
idset <- 1L:ncurve
splineGrob <-
xsplineGrob(c(x1, cps1$x, xm, cps2$x, x2),
c(y1, cps1$y, ym, cps2$y, y2),
id=c(idset, rep(idset, each=ncp),
idset, rep(idset, each=ncp),
idset),
default.units="inches",
shape=c(rep(0, ncurve), shape1,
rep(0, ncurve), shape2,
rep(0, ncurve)),
arrow=arrow, open=open,
name="xspline")
if (is.null(straightGrob)) {
children <- gList(splineGrob)
} else {
children <- gList(straightGrob, splineGrob)
}
} else {
shape <- rep(rep(shape, length.out=ncp), ncurve)
if (square) {
cps <- calcSquareControlPoints(x1, y1, x2, y2,
curvature, angle,
ncp,
debug=debug)
shape <- interleave(ncp, ncurve, shape,
squareShape, squareShape,
cps$end)
ncp <- ncp + 1
} else {
cps <- calcControlPoints(x1, y1, x2, y2,
curvature, angle, ncp,
debug=debug)
}
if (debug) {
cbDiagram(x1, y1, x2, y2, cps)
}
idset <- 1L:ncurve
splineGrob <- xsplineGrob(c(x1, cps$x, x2),
c(y1, cps$y, y2),
id=c(idset,
rep(idset, each=ncp), idset),
default.units="inches",
shape=c(rep(0, ncurve), shape,
rep(0, ncurve)),
arrow=arrow, open=open,
name="xspline")
if (is.null(straightGrob)) {
children <- gList(splineGrob)
} else {
children <- gList(straightGrob, splineGrob)
}
}
}
}
}
gTree(children=children,
name=x$name, gp=x$gp, vp=x$vp)
}
validDetails.curve <- function(x) {
if ((!is.unit(x$x1) || !is.unit(x$y1)) ||
(!is.unit(x$x2) || !is.unit(x$y2)))
stop("'x1', 'y1', 'x2', and 'y2' must be units")
x$curvature <- as.numeric(x$curvature)
x$angle <- x$angle %% 180
x$ncp <- as.integer(x$ncp)
if (x$shape < -1 || x$shape > 1)
stop("'shape' must be between -1 and 1")
x$square <- as.logical(x$square)
if (x$squareShape < -1 || x$squareShape > 1)
stop("'squareShape' must be between -1 and 1")
x$inflect <- as.logical(x$inflect)
if (!is.null(x$arrow) && !inherits(x$arrow, "arrow"))
stop("'arrow' must be an arrow object or NULL")
x$open <- as.logical(x$open)
x
}
makeContent.curve <- function(x) {
calcCurveGrob(x, x$debug)
}
xDetails.curve <- function(x, theta) {
cg <- calcCurveGrob(x, FALSE)
if (length(cg$children) == 1)
xDetails(cg$children[[1]], theta)
else
xDetails(cg, theta)
}
yDetails.curve <- function(x, theta) {
cg <- calcCurveGrob(x, FALSE)
if (length(cg$children) == 1)
yDetails(cg$children[[1]], theta)
else
yDetails(cg, theta)
}
widthDetails.curve <- function(x) {
cg <- calcCurveGrob(x, FALSE)
if (length(cg$children) == 1)
widthDetails(cg$children[[1]])
else
widthDetails(cg)
}
heightDetails.curve <- function(x) {
cg <- calcCurveGrob(x, FALSE)
if (length(cg$children) == 1)
heightDetails(cg$children[[1]])
else
heightDetails(cg)
}
curveGrob <- function(x1, y1, x2, y2, default.units="npc",
curvature=1, angle=90, ncp=1,
shape=0.5, square=TRUE, squareShape=1,
inflect=FALSE, arrow=NULL, open=TRUE,
debug=FALSE,
name=NULL, gp=gpar(), vp=NULL) {
if (!is.unit(x1))
x1 <- unit(x1, default.units)
if (!is.unit(y1))
y1 <- unit(y1, default.units)
if (!is.unit(x2))
x2 <- unit(x2, default.units)
if (!is.unit(y2))
y2 <- unit(y2, default.units)
gTree(x1=x1, y1=y1, x2=x2, y2=y2,
curvature=curvature, angle=angle, ncp=ncp,
shape=shape, square=square, squareShape=squareShape,
inflect=inflect, arrow=arrow, open=open, debug=debug,
name=name, gp=gp, vp=vp,
cl="curve")
}
grid.curve <- function(...) {
grid.draw(curveGrob(...))
}
arcCurvature <- function(theta) {
if (theta < 1 || theta > 359)
return(0)
angle <- 0.5*theta/180*pi
1/sin(angle) - 1/tan(angle)
}
|
.abs<-function(x){
return (abs(x[!is.na(x)]))
}
data.Normalization<-function (x, type = "n0", normalization = "column", ...)
{
bycolumn = T
if (normalization == "row")
bycolumn = F
if (is.vector(x) && !is.list(x)) {
if (is.numeric(resul <- x)) {
resul <- switch(type, n0 = x, n1 = (x - mean(x, ...))/sd(x,
...), n2 = (x - median(x, ...))/mad(x, ...),
n3 = (x - mean(x, ...))/(max(x, ...) - min(x,
...)), n3a = (x - median(x, ...))/(max(x, ...) -
min(x, ...)), n4 = (x - min(x, ...))/(max(x,
...) - min(x, ...)), n5 = (x - mean(x, ...))/(max(.abs((x) -
mean(x, ...)))), n5a = (x - median(x, ...))/(max(.abs((x) -
median(x, ...)))), n6 = x/sd(x, ...), n6a = x/mad(x,
...), n7 = x/(max(x, ...) - min(x, ...)), n8 = x/max(x,
...), n9 = x/mean(x, ...), n9a = x/median(x,
...), n10 = x/sum(x, ...), n11 = x/(sum(x^2,
...)^0.5), n12 = (x - mean(x, ...))/(sum((x -
mean(x, ...))^2, ...)^0.5), n12a = (x - median(x,
...))/(sum((x - median(x, ...))^2, ...)^0.5),
n13 = (x - ((max(x, ...) + min(x, ...))/2))/((max(x,
...) - min(x, ...))/2))
params <- switch(type, n0 = c(0, 1), n1 = c(mean(x,
...), sd(x, ...)), n2 = c(median(x, ...), mad(x,
...)), n3 = c(mean(x, ...), max(x, ...) - min(x,
...)), n3a = c(median(x, ...), max(x, ...) -
min(x, ...)), n4 = c(min(x, ...), max(x, ...) -
min(x, ...)), n5 = c(mean(x, ...), max(.abs((x) -
mean(x, ...)))), n5a = c((median(x, ...)), (max(.abs((x) -
median(x, ...))))), n6 = c(0, sd(x, ...)), n6a = c(0,
mad(x, ...)), n7 = c(0, (max(x, ...) - min(x,
...))), n8 = c(0, max(x, ...)), n9 = c(0/mean(x,
...)), n9a = c(0/median(x, ...)), n10 = c(0/sum(x,
...)), n11 = c(0, (sum(x^2, ...)^0.5)), n12 = c((mean(x,
...)), (sum((x - mean(x, ...))^2, ...)^0.5)),
n12a = c((median(x, ...)), (sum((x - median(x,
...))^2, ...)^0.5)), n13 = c((((max(x, ...) +
min(x, ...))/2)), ((max(x, ...) - min(x, ...))/2)))
center <- params[1]
scale <- params[2]
}
else warning("Data not numeric, normalization not applicable")
names(resul) <- names(x)
}
else if (is.data.frame(x)) {
resul <- NULL
params <- NULL
if (bycolumn) {
for (nn in names(x)) {
if (is.numeric(x[, nn])) {
resul <- switch(type, n0 = cbind(resul, (x[,
nn])), n1 = cbind(resul, (x[, nn] - mean(x[,
nn], ...))/(sd(x[, nn], ...))), n2 = cbind(resul,
(x[, nn] - median(x[, nn], ...))/(mad(x[,
nn], ...))), n3 = cbind(resul, (x[, nn] -
mean(x[, nn], ...))/(max(x[, nn], ...) -
min(x[, nn], ...))), n3a = cbind(resul, (x[,
nn] - median(x[, nn], ...))/(max(x[, nn],
...) - min(x[, nn], ...))), n4 = cbind(resul,
(x[, nn] - min(x[, nn], ...))/(max(x[, nn],
...) - min(x[, nn], ...))), n5 = cbind(resul,
(x[, nn] - mean(x[, nn], ...))/(max(.abs(x[,
nn] - mean(x[, nn], ...))))), n5a = cbind(resul,
(x[, nn] - median(x[, nn], ...))/(max(.abs(x[,
nn] - median(x[, nn], ...))))), n6 = cbind(resul,
(x[, nn])/sd(x[, nn], ...)), n6a = cbind(resul,
(x[, nn])/mad(x[, nn], ...)), n7 = cbind(resul,
(x[, nn])/(max(x[, nn], ...) - min(x[, nn],
...))), n8 = cbind(resul, (x[, nn])/(max(x[,
nn], ...))), n9 = cbind(resul, (x[, nn])/(mean(x[,
nn], ...))), n9a = cbind(resul, (x[, nn])/(median(x[,
nn], ...))), n10 = cbind(resul, (x[, nn])/(sum(x[,
nn], ...))), n11 = cbind(resul, (x[, nn])/(sum(x[,
nn]^2, ...)^0.5)), n12 = cbind(resul, (x[,
nn] - mean(x[, nn], ...))/(sum((x[, nn] -
mean(x[, nn], ...))^2, ...)^0.5)), n12a = cbind(resul,
(x[, nn] - median(x[, nn], ...))/(sum((x[,
nn] - median(x[, nn], ...))^2, ...)^0.5)),
n13 = cbind(resul, (x[, nn] - ((max(x[, nn],
...) + min(x[, nn], ...))/2))/((max(x[,
nn], ...) - min(x[, nn], ...))/2)))
p <- switch(type, n0 = c(0, 1), n1 = c((mean(x[,
nn], ...)), (sd(x[, nn], ...))), n2 = c(median(x[,
nn], ...), (mad(x[, nn], ...))), n3 = c((mean(x[,
nn], ...)), (max(x[, nn], ...) - min(x[,
nn], ...))), n3a = c(median(x[, nn], ...),
(max(x[, nn], ...) - min(x[, nn], ...))),
n4 = c((min(x[, nn], ...)), (max(x[, nn],
...) - min(x[, nn], ...))), n5 = c((mean(x[,
nn], ...)), (max(.abs(mean(x[, nn], ...))))),
n5a = c((x[, nn] - median(x[, nn], ...)),
(max(.abs(median(x[, nn], ...))))), n6 = c(0,
sd(x[, nn], ...)), n6a = c((0), mad(x[,
nn], ...)), n7 = c(0, max(x[, nn], ...) -
min(x[, nn], ...)), n8 = c(0, (max(x[,
nn], ...))), n9 = c(0, mean(x[, nn], ...)),
n9a = c(0, median(x[, nn], ...)), n10 = c(0,
sum(x[, nn], ...)), n11 = c(0, (sum(x[,
nn]^2, ...)^0.5)), n12 = c((mean(x[, nn],
...)), (sum((mean(x[, nn], ...))^2, ...)^0.5)),
n12a = c(median(x[, nn], ...), (sum((x[,
nn] - median(x[, nn], ...))^2, ...)^0.5)),
n13 = c(((max(x[, nn], ...) + min(x[, nn],
...))/2), ((max(x[, nn], ...) - min(x[,
nn], ...))/2)))
params <- cbind(params, p)
}
else {
resul <- cbind(resul, x[, nn], ...)
params <- cbind(params, c(NA, NA))
warning("Data not numeric, normalization not applicable")
}
}
center <- params[1, ]
scale <- params[2, ]
}
else {
for (nn in 1:nrow(x)) {
if (sum(is.na(as.numeric((x[nn, ])))) == 0) {
resul <- switch(type, n0 = rbind(resul, (x[nn,
])), n1 = rbind(resul, (x[nn, ] - mean(as.numeric(x[nn,
], ...)))/(sd(as.numeric(x[nn, ], ...)))),
n2 = rbind(resul, (x[nn, ] - median(as.numeric(x[nn,
], ...)))/(mad(as.numeric(x[nn, ], ...)))),
n3 = rbind(resul, (x[nn, ] - mean(as.numeric(x[nn,
], ...)))/(max(as.numeric(x[nn, ], ...)) -
min(as.numeric(x[nn, ], ...)))), n3a = rbind(resul,
(x[nn, ] - median(as.numeric(x[nn, ], ...)))/(max(as.numeric(x[nn,
], ...)) - min(as.numeric(x[nn, ], ...)))),
n4 = rbind(resul, (x[nn, ] - min(as.numeric(x[nn,
], ...)))/(max(as.numeric(x[nn, ], ...)) -
min(as.numeric(x[nn, ], ...)))), n5 = rbind(resul,
(x[nn, ] - mean(as.numeric(x[nn, ], ...)))/(max(.abs(as.numeric(x[nn,
], ...) - mean(as.numeric(x[nn, ], ...)))))),
n5a = rbind(resul, (x[nn, ] - median(as.numeric(x[nn,
], ...)))/(max(.abs(as.numeric(x[nn, ],
...) - median(as.numeric(x[nn, ], ...)))))),
n6 = rbind(resul, (x[nn, ])/sd(as.numeric(x[nn,
], ...))), n6a = rbind(resul, (x[nn, ])/mad(as.numeric(x[nn,
], ...))), n7 = rbind(resul, (x[nn, ])/(max(as.numeric(x[nn,
], ...)) - min(as.numeric(x[nn, ], ...)))),
n8 = rbind(resul, (x[nn, ])/(max(as.numeric(x[nn,
], ...)))), n9 = rbind(resul, (x[nn, ])/(mean(as.numeric(x[nn,
], ...)))), n9a = rbind(resul, (x[nn, ])/(median(as.numeric(x[nn,
], ...)))), n10 = rbind(resul, (x[nn, ])/(sum(as.numeric(x[nn,
], ...)))), n11 = rbind(resul, (x[nn, ])/(sum(as.numeric(x[nn,
])^2, ...)^0.5)), n12 = rbind(resul, (x[nn,
] - mean(as.numeric(x[nn, ], ...)))/(sum((as.numeric(x[nn,
], ...) - mean(as.numeric(x[nn, ], ...)))^2,
...)^0.5)), n12a = rbind(resul, (x[nn,
] - median(as.numeric(x[nn, ], ...)))/(sum((as.numeric(x[nn,
]) - median(as.numeric(x[nn, ], ...)))^2,
...)^0.5)), n13 = rbind(resul, (x[nn, ] -
((max(as.numeric(x[nn, ], ...)) + min(as.numeric(x[nn,
], ...)))/2))/((max(as.numeric(x[nn,
], ...)) - min(as.numeric(x[nn, ], ...)))/2)))
p <- switch(type, n0 = c(0, 1), n1 = c(mean(x[nn,
], ...), (sd(x[nn, ], ...))), n2 = c(median(x[nn,
], ...), (mad(x[nn, ], ...))), n3 = c((mean(x[nn,
], ...)), (max(x[nn, ], ...) - min(x[nn,
], ...))), n3a = c(median(x[nn, ], ...),
(max(x[nn, ], ...) - min(x[nn, ], ...))),
n4 = c((min(x[nn, ], ...)), (max(x[nn, ],
...) - min(x[nn, ], ...))), n5 = c((mean(x[nn,
], ...)), (max(.abs(mean(x[nn, ], ...))))),
n5a = c((x[nn, ] - median(x[nn, ], ...)),
(max(.abs(median(x[nn, ], ...))))), n6 = c(0,
sd(x[nn, ], ...)), n6a = c((0), mad(x[nn,
], ...)), n7 = c(0, max(x[nn, ], ...) -
min(x[nn, ], ...)), n8 = c(0, max(x[nn,
], ...)), n9 = c(0, mean(x[nn, ], ...)),
n9a = c(0, median(x[nn, ], ...)), n10 = c(0,
sum(x[nn, ], ...)), n11 = c(0, (sum(x[nn,
]^2, ...)^0.5)), n12 = c((mean(x[nn, ],
...)), (sum((mean(x[nn, ], ...))^2, ...)^0.5)),
n12a = c(median(x[nn, ], ...), (sum((x[nn,
] - median(x[nn, ], ...))^2, ...)^0.5)),
n13 = c(((max(x[nn, ], ...) + min(x[nn, ],
...))/2), ((max(x[nn, ], ...) - min(x[nn,
], ...))/2)))
params <- cbind(params, p)
}
else {
resul <- rbind(resul, x[nn, ])
params <- cbind(params, c(NA, NA))
warning("Data not numeric, normalization not applicable")
}
}
}
resul <- data.frame(resul)
center <- params[1, ]
scale <- params[2, ]
names(resul) <- names(x)
row.names(resul) <- row.names(x)
if (bycolumn) {
if (!is.null(dimnames(x)[[2]])) {
names(center) <- dimnames(x)[[2]]
names(scale) <- dimnames(x)[[2]]
}
else {
names(center) <- 1:ncol(x)
names(scale) <- 1:ncol(x)
}
}
else {
if (!is.null(dimnames(x)[[1]])) {
names(center) <- dimnames(x)[[1]]
names(scale) <- dimnames(x)[[1]]
}
else {
names(center) <- 1:nrow(x)
names(scale) <- 1:nrow(x)
}
}
}
else if (is.matrix(x)) {
if (is.numeric(resul <- x)) {
params <- NULL
resul <- NULL
if (bycolumn) {
for (i in 1:ncol(x)) {
resul <- switch(type, n0 = cbind(resul, (x[,
i])), n1 = cbind(resul, (x[, i] - mean(x[,
i], ...))/(sd(x[, i], ...))), n2 = cbind(resul,
(x[, i] - median(x[, i], ...))/(mad(x[, i],
...))), n3 = cbind(resul, (x[, i] - mean(x[,
i], ...))/(max(x[, i], ...) - min(x[, i],
...))), n3a = cbind(resul, (x[, i] - median(x[,
i], ...))/(max(x[, i], ...) - min(x[, i],
...))), n4 = cbind(resul, (x[, i] - min(x[,
i], ...))/(max(x[, i], ...) - min(x[, i],
...))), n5 = cbind(resul, (x[, i] - mean(x[,
i], ...))/(max(.abs(x[, i] - mean(x[, i],
...))))), n5a = cbind(resul, (x[, i] - median(x[,
i], ...))/(max(.abs(x[, i] - median(x[, i],
...))))), n6 = cbind(resul, (x[, i])/sd(x[,
i], ...)), n6a = cbind(resul, (x[, i])/mad(x[,
i], ...)), n7 = cbind(resul, (x[, i])/(max(x[,
i], ...) - min(x[, i], ...))), n8 = cbind(resul,
(x[, i])/(max(x[, i], ...))), n9 = cbind(resul,
(x[, i])/(mean(x[, i], ...))), n9a = cbind(resul,
(x[, i])/(median(x[, i], ...))), n10 = cbind(resul,
(x[, i])/(sum(x[, i], ...))), n11 = cbind(resul,
(x[, i])/(sum(x[, i]^2, ...)^0.5)), n12 = cbind(resul,
(x[, i] - mean(x[, i], ...))/(sum((x[, i] -
mean(x[, i], ...))^2, ...)^0.5)), n12a = cbind(resul,
(x[, i] - median(x[, i], ...))/(sum((x[,
i] - median(x[, i], ...))^2, ...)^0.5)),
n13 = cbind(resul, (x[, i] - ((max(x[, i],
...) + min(x[, i], ...))/2))/((max(x[,
i], ...) - min(x[, i], ...))/2)))
p <- switch(type, n0 = c(0, 1), n1 = c((mean(x[,
i], ...)), (sd(x[, i], ...))), n2 = c(median(x[,
i], ...), (mad(x[, i], ...))), n3 = c((mean(x[,
i], ...)), (max(x[, i], ...) - min(x[, i],
...))), n3a = c(median(x[, i], ...), (max(x[,
i], ...) - min(x[, i], ...))), n4 = c((min(x[,
i], ...)), (max(x[, i], ...) - min(x[, i],
...))), n5 = c((mean(x[, i], ...)), (max(.abs(mean(x[,
i], ...))))), n5a = c((x[, i] - median(x[,
i], ...)), (max(.abs(median(x[, i], ...))))),
n6 = c(0, sd(x[, i], ...)), n6a = c((0),
mad(x[, i], ...)), n7 = c(0, max(x[, i],
...) - min(x[, i], ...)), n8 = c(0, max(x[,
i], ...)), n9 = c(0, mean(x[, i], ...)),
n9a = c(0, median(x[, i], ...)), n10 = c(0,
sum(x[, i], ...)), n11 = c(0, (sum(x[,
i]^2, ...)^0.5)), n12 = c((mean(x[, i],
...)), (sum((mean(x[, i], ...))^2, ...)^0.5)),
n12a = c(median(x[, i], ...), (sum((x[, i] -
median(x[, i], ...))^2, ...)^0.5)), n13 = c(((max(x[,
i], ...) + min(x[, i], ...))/2), ((max(x[,
i], ...) - min(x[, i], ...))/2)))
params <- cbind(params, p)
}
}
else {
for (i in 1:nrow(x)) {
resul <- switch(type, n0 = rbind(resul, (x[i,
])), n1 = rbind(resul, (x[i, ] - mean(x[i,
], ...))/(sd(x[i, ], ...))), n2 = rbind(resul,
(x[i, ] - median(x[i, ], ...))/(mad(x[i,
], ...))), n3 = rbind(resul, (x[i, ] -
mean(x[i, ], ...))/(max(x[i, ], ...) - min(x[i,
], ...))), n3a = rbind(resul, (x[i, ] - median(x[i,
], ...))/(max(x[i, ], ...) - min(x[i, ],
...))), n4 = rbind(resul, (x[i, ] - min(x[i,
], ...))/(max(x[i, ], ...) - min(x[i, ],
...))), n5 = rbind(resul, (x[i, ] - mean(x[i,
], ...))/(max(.abs(x[i, ] - mean(x[i, ],
...))))), n5a = rbind(resul, (x[i, ] - median(x[i,
], ...))/(max(.abs(x[i, ] - median(x[i, ],
...))))), n6 = rbind(resul, (x[i, ])/sd(x[i,
], ...)), n6a = rbind(resul, (x[i, ])/mad(x[i,
], ...)), n7 = rbind(resul, (x[i, ])/(max(x[i,
], ...) - min(x[i, ], ...))), n8 = rbind(resul,
(x[i, ])/(max(x[i, ], ...))), n9 = rbind(resul,
(x[i, ])/(mean(x[i, ], ...))), n9a = rbind(resul,
(x[i, ])/(median(x[i, ], ...))), n10 = rbind(resul,
(x[i, ])/(sum(x[i, ], ...))), n11 = rbind(resul,
(x[i, ])/(sum(x[i, ]^2, ...)^0.5)), n12 = rbind(resul,
(x[i, ] - mean(x[i, ], ...))/(sum((x[i, ] -
mean(x[i, ], ...))^2, ...)^0.5)), n12a = rbind(resul,
(x[i, ] - median(x[i, ], ...))/(sum((x[i,
] - median(x[i, ], ...))^2, ...)^0.5)),
n13 = rbind(resul, (x[i, ] - ((max(x[i, ],
...) + min(x[i, ], ...))/2))/((max(x[i,
], ...) - min(x[i, ], ...))/2)))
p <- switch(type, n0 = c(0, 1), n1 = c(mean(x[i],
...), sd(x[i, ], ...)), n2 = c(median(x[i,
], ...), (mad(x[i, ], ...))), n3 = c((mean(x[i,
], ...)), (max(x[i, ], ...) - min(x[i, ],
...))), n3a = c(median(x[i, ], ...), (max(x[i,
], ...) - min(x[i, ], ...))), n4 = c((min(x[i,
], ...)), (max(x[i, ], ...) - min(x[i, ],
...))), n5 = c((mean(x[i, ], ...)), (max(.abs(mean(x[i,
], ...))))), n5a = c((x[i, ] - median(x[i,
], ...)), (max(.abs(median(x[i, ], ...))))),
n6 = c(0, sd(x[i, ], ...)), n6a = c((0),
mad(x[i, ], ...)), n7 = c(0, max(x[i, ],
...) - min(x[i, ], ...)), n8 = c(0, max(x[i,
], ...)), n9 = c(0, mean(x[i, ], ...)),
n9a = c(0, median(x[i, ], ...)), n10 = c(0,
sum(x[i, ], ...)), n11 = c(0, (sum(x[i,
]^2, ...)^0.5)), n12 = c((mean(x[i, ],
...)), (sum((mean(x[i, ], ...))^2, ...)^0.5)),
n12a = c(median(x[i, ], ...), (sum((x[i,
] - median(x[i, ], ...))^2, ...)^0.5)),
n13 = c(((max(x[i, ], ...) + min(x[i, ],
...))/2), ((max(x[i, ], ...) - min(x[i,
], ...))/2)))
params <- cbind(params, p)
}
}
center <- params[1, ]
scale <- params[2, ]
if (bycolumn) {
if (!is.null(dimnames(x)[[2]])) {
names(center) <- dimnames(x)[[2]]
names(scale) <- dimnames(x)[[2]]
}
else {
names(center) <- 1:ncol(x)
names(scale) <- 1:ncol(x)
}
}
else {
if (!is.null(dimnames(x)[[1]])) {
names(center) <- dimnames(x)[[1]]
names(scale) <- dimnames(x)[[1]]
}
else {
names(center) <- 1:nrow(x)
names(scale) <- 1:nrow(x)
}
}
}
else {
warning("Data not numeric, normalization not applicable")
center <- NA
scale <- NA
}
dimnames(resul) <- dimnames(x)
}
else if (is.list(x)) {
resul <- list(length(x))
center <- list(length(x))
scale <- list(length(x))
xx <- as.numeric(x)
center <- switch(type, n0 = 0, n1 = mean(xx, ...), n2 = (median(xx,
...)), n3 = (mean(xx, ...)), n3a = (median(xx, ...)),
n4 = (min(xx, ...)), n5 = (mean(xx, ...)), n5a = (median(xx,
...)), n6 = 0, n6a = 0, n7 = 0, n8 = 0, n9 = 0,
n9a = 0, n10 = 0, n11 = 0, n12 = (mean(xx, ...)),
n12a = (median(xx, ...)), n13 = (((max(xx, ...) +
min(xx, ...))/2)))
scale <- switch(type, n0 = 1, n1 = sd(xx), n2 = mad(xx,
...), n3 = (max(xx, ...) - min(xx, ...)), n3a = (max(xx,
...) - min(xx, ...)), n4 = (max(xx, ...) - min(xx,
...)), n5 = (max(.abs((xx) - mean(xx, ...)))), n5a = (max(.abs((xx) -
median(xx, ...)))), n6 = sd(xx), n6a = mad(xx, ...),
n7 = (max(xx, ...) - min(xx, ...)), n8 = (max(xx,
...)), n9 = (mean(xx, ...)), n9a = (median(xx,
...)), n10 = (sum(xx, ...)), n11 = (sum(xx^2,
...)^0.5), n12 = (sum((xx - mean(xx, ...))^2,
...)^0.5), n12a = (sum((xx - median(xx, ...))^2,
...)^0.5), n13 = ((max(xx, ...) - min(xx, ...))/2))
for (i in 1:length(x)) if (is.numeric(resul[[i]] <- x[[i]])) {
resul[[i]] <- switch(type, n0 = x[[i]], n1 = (x[[i]] -
mean(xx, ...))/sd(xx), n2 = (x[[i]] - median(xx,
...))/mad(xx, ...), n3 = (x[[i]] - mean(xx, ...))/(max(xx,
...) - min(xx, ...)), n3a = (x[[i]] - median(xx,
...))/(max(xx, ...) - min(xx, ...)), n4 = (x[[i]] -
min(xx, ...))/(max(xx, ...) - min(xx, ...)),
n5 = (x[[i]] - mean(xx, ...))/(max(.abs((xx) -
mean(xx, ...)))), n5a = (x[[i]] - median(xx,
...))/(max(.abs((xx) - median(xx, ...)))),
n6 = x[[i]]/sd(xx), n6a = x[[i]]/mad(xx, ...),
n7 = x[[i]]/(max(xx, ...) - min(xx, ...)), n8 = x[[i]]/(max(xx,
...)), n9 = x[[i]]/(mean(xx, ...)), n9a = x[[i]]/(median(xx,
...)), n10 = x[[i]]/(sum(xx, ...)), n11 = x[[i]]/(sum(xx^2,
...)^0.5), n12 = (x[[i]] - mean(xx, ...))/(sum((xx -
mean(xx, ...))^2, ...)^0.5), n12a = (x[[i]] -
median(xx, ...))/(sum((xx - median(xx, ...))^2,
...)^0.5), n13 = (x[[i]] - ((max(xx, ...) +
min(xx, ...))/2))/((max(xx, ...) - min(xx,
...))/2))
}
else {
warning("Data not numeric, normalization not applicable")
}
}
else if (!is.numeric(resul <- x)) {
warning("Data not numeric, normalization not applicable")
center <- NA
scale <- NA
}
else stop("unknown input type")
if (is.numeric(t <- x)) {
if (sum(as.numeric(x) <= 0) > 0) {
if (type == "n6" || type == "n6a" || type == "n7" ||
type == "n8" || type == "n9" || type == "n9a" ||
type == "n10" || type == "n11") {
warning("Data for this kind of normalization should be positive")
}
}
}
attr(resul, "normalized:shift") <- center
attr(resul, "normalized:scale") <- scale
resul
}
|
\dontrun{
current.mode <- tmap_mode("view")
data(World, metro)
tm_basemap(leaflet::providers$Stamen.Watercolor) +
tm_shape(metro, bbox = "India") + tm_dots(col = "red", group = "Metropolitan areas") +
tm_tiles(paste0("http://services.arcgisonline.com/arcgis/rest/services/Canvas/",
"World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}"), group = "Labels")
opts <- tmap_options(basemaps = c(Canvas = "Esri.WorldGrayCanvas", Imagery = "Esri.WorldImagery"),
overlays = c(Labels = paste0("http://services.arcgisonline.com/arcgis/rest/services/Canvas/",
"World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}")))
qtm(World, fill = "HPI", fill.palette = "RdYlGn")
tmap_options(opts)
tmap_mode(current.mode)
}
|
datagrid_proxy <- function(shinyId, session = shiny::getDefaultReactiveDomain()) {
if (is.null(session)) {
stop("grid_proxy must be called from the server function of a Shiny app")
}
if (!is.null(session$ns) && nzchar(session$ns(NULL)) && substring(shinyId, 1, nchar(session$ns(""))) != session$ns("")) {
shinyId <- session$ns(shinyId)
}
structure(
list(
session = session,
id = shinyId,
x = list()
),
class = c("datagrid_proxy", "htmlwidgetProxy")
)
}
grid_proxy_add_row <- function(proxy, data) {
data <- as.data.frame(data)
if (is.character(proxy)) {
proxy <- datagrid_proxy(proxy)
}
.call_proxy(
proxy = proxy,
name = "grid-add-rows",
nrow = nrow(data),
ncol = ncol(data),
data = unname(data),
colnames = names(data)
)
}
grid_proxy_delete_row <- function(proxy, index) {
if (is.character(proxy)) {
proxy <- datagrid_proxy(proxy)
}
.call_proxy(
proxy = proxy,
name = "grid-delete-rows",
index = list1(as.numeric(index) - 1)
)
}
|
library(tidyquant)
get <- "economic.data"
context(paste0("Testing tq_get(get = '", get, "')"))
test1 <- tq_get("CPIAUCSL", get = get,
from = "2016-01-01", to = "2016-06-01",
adjust = TRUE, type = "splits")
test2 <- tq_get("CPIAUCSL", get = get,
from = "2016-01-01", to = "2016-06-01",
adjust = FALSE, type = "price")
test_that("Test returns tibble with correct rows and columns.", {
expect_is(test1, "tbl")
expect_is(test2, "tbl")
expect_identical(test1, test2)
expect_equal(nrow(test1), 6)
expect_equal(ncol(test1), 3)
})
test_that("Test prints warning message on invalid x input.", {
expect_warning(tq_get("XYZ", get = get))
})
test_that("Test returns NA on invalid x input.", {
expect_equal(suppressWarnings(tq_get("XYZ", get = get)), NA)
})
|
skip_on_cran()
skip_on_os(os = "windows")
local_edition(3)
work_path <- "./generated_r_files"
if (fs::dir_exists(path = work_path)) {
fs::dir_delete(path = work_path)
}
fs::dir_create(path = work_path)
write_draft_snapshot_test <- function(dataset,
file_name,
tbl_name = NULL,
path = work_path,
lang = NULL,
output_type = "R",
add_comments = TRUE) {
tbl <- dataset
suppressMessages(
expect_true(
draft_validation(
tbl = tbl,
tbl_name = tbl_name,
file_name = file_name,
path = work_path,
lang = lang,
output_type = output_type,
add_comments = add_comments,
overwrite = TRUE
)
)
)
path <- list.files(path = work_path, pattern = file_name, full.names = TRUE)
expect_snapshot(readLines(con = path) %>% paste0(collapse = "\n"))
}
test_that("draft validations for data tables can be generated", {
write_draft_snapshot_test(dataset = gt::countrypops, file_name = "countrypops")
write_draft_snapshot_test(dataset = gt::sza, file_name = "sza")
write_draft_snapshot_test(dataset = gt::gtcars, file_name = "gtcars")
write_draft_snapshot_test(dataset = gt::sp500, file_name = "sp500")
write_draft_snapshot_test(dataset = gt::pizzaplace, file_name = "pizzaplace")
write_draft_snapshot_test(dataset = gt::exibble, file_name = "exibble")
write_draft_snapshot_test(dataset = ggplot2::diamonds, file_name = "diamonds")
write_draft_snapshot_test(dataset = ggplot2::economics_long, file_name = "economics_long")
write_draft_snapshot_test(dataset = ggplot2::faithfuld, file_name = "faithfuld")
write_draft_snapshot_test(dataset = ggplot2::luv_colours, file_name = "luv_colours")
write_draft_snapshot_test(dataset = ggplot2::midwest, file_name = "midwest")
write_draft_snapshot_test(dataset = ggplot2::mpg, file_name = "mpg")
write_draft_snapshot_test(dataset = ggplot2::msleep, file_name = "msleep")
write_draft_snapshot_test(dataset = ggplot2::presidential, file_name = "presidential")
write_draft_snapshot_test(dataset = ggplot2::seals, file_name = "seals")
write_draft_snapshot_test(dataset = ggplot2::txhousing, file_name = "txhousing")
write_draft_snapshot_test(dataset = dplyr::band_instruments, file_name = "band_instruments")
write_draft_snapshot_test(dataset = dplyr::band_members, file_name = "band_members")
write_draft_snapshot_test(dataset = dplyr::starwars, file_name = "starwars")
write_draft_snapshot_test(dataset = dplyr::storms, file_name = "storms")
write_draft_snapshot_test(dataset = tidyr::billboard, file_name = "billboard")
write_draft_snapshot_test(dataset = tidyr::construction, file_name = "construction")
write_draft_snapshot_test(dataset = tidyr::fish_encounters, file_name = "fish_encounters")
write_draft_snapshot_test(dataset = tidyr::population, file_name = "population")
write_draft_snapshot_test(dataset = tidyr::relig_income, file_name = "relig_income")
write_draft_snapshot_test(dataset = tidyr::smiths, file_name = "smiths")
write_draft_snapshot_test(dataset = tidyr::us_rent_income, file_name = "us_rent_income")
write_draft_snapshot_test(dataset = tidyr::who, file_name = "who")
write_draft_snapshot_test(dataset = tidyr::world_bank_pop, file_name = "world_bank_pop")
write_draft_snapshot_test(dataset = lubridate::lakers, file_name = "lakers")
write_draft_snapshot_test(dataset = datasets::airquality, file_name = "airquality")
write_draft_snapshot_test(dataset = datasets::chickwts, file_name = "chickwts")
write_draft_snapshot_test(dataset = datasets::iris, file_name = "iris")
write_draft_snapshot_test(dataset = datasets::LifeCycleSavings, file_name = "LifeCycleSavings")
write_draft_snapshot_test(dataset = datasets::longley, file_name = "longley")
write_draft_snapshot_test(dataset = datasets::morley, file_name = "morley")
write_draft_snapshot_test(dataset = datasets::mtcars, file_name = "mtcars")
write_draft_snapshot_test(dataset = datasets::Orange, file_name = "Orange")
write_draft_snapshot_test(dataset = datasets::pressure, file_name = "pressure")
write_draft_snapshot_test(dataset = datasets::quakes, file_name = "quakes")
write_draft_snapshot_test(dataset = datasets::rock, file_name = "rock")
write_draft_snapshot_test(dataset = datasets::swiss, file_name = "swiss")
write_draft_snapshot_test(dataset = datasets::USJudgeRatings, file_name = "USJudgeRatings")
})
test_that("draft validations for data tables can be generated in different languages", {
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_en", lang = "en")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_fr", lang = "fr")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_de", lang = "de")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_it", lang = "it")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_es", lang = "es")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_pt", lang = "pt")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_tr", lang = "tr")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_zh", lang = "zh")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_ru", lang = "ru")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_pl", lang = "pl")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_da", lang = "da")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_sv", lang = "sv")
write_draft_snapshot_test(dataset = pointblank::small_table, file_name = "st_nl", lang = "nl")
})
test_that("draft validations for data tables can be generated in .Rmd format", {
write_draft_snapshot_test(dataset = gt::countrypops, file_name = "countrypops_rmd", output_type = "Rmd")
write_draft_snapshot_test(dataset = gt::sza, file_name = "sza_rmd", output_type = "Rmd")
write_draft_snapshot_test(dataset = gt::gtcars, file_name = "gtcars_rmd", output_type = "Rmd")
write_draft_snapshot_test(dataset = gt::sp500, file_name = "sp500_rmd", output_type = "Rmd")
write_draft_snapshot_test(dataset = gt::pizzaplace, file_name = "pizzaplace_rmd", output_type = "Rmd")
write_draft_snapshot_test(dataset = gt::exibble, file_name = "exibble_rmd", output_type = "Rmd")
})
test_that("draft validations for data tables can be generated without comments", {
write_draft_snapshot_test(dataset = gt::countrypops, file_name = "countrypops_no_comments", add_comments = FALSE)
})
test_that("an invalid path used in `draft_validation()` will result in an error", {
expect_error(draft_validation(tbl = gt::countrypops, file_name = "countrypops", path = "invalid/path"))
})
test_that("a file created with `draft_validation()` cannot be overwritten by default", {
suppressMessages(
draft_validation(tbl = gt::countrypops, file_name = "countrypops_new", path = work_path)
)
expect_error(
suppressMessages(
draft_validation(tbl = gt::countrypops, file_name = "countrypops_new", path = work_path)
)
)
expect_error(
regexp = NA,
suppressMessages(
draft_validation(tbl = gt::countrypops, file_name = "countrypops_new", path = work_path, overwrite = TRUE)
)
)
})
test_that("messages emitted by `draft_validation()` can be quieted", {
expect_message(
draft_validation(tbl = gt::countrypops, file_name = "countrypops", path = work_path, overwrite = TRUE)
)
expect_message(
regexp = NA,
draft_validation(tbl = gt::countrypops, file_name = "countrypops", path = work_path, overwrite = TRUE, quiet = TRUE)
)
})
if (fs::dir_exists(path = work_path)) {
fs::dir_delete(path = work_path)
}
|
init.nii <- function(new.nii, ref.nii=NULL, dims, pixdim=NULL, orient=NULL, datatype=16, init.value=NA) {
fid <- file(new.nii, "w+b")
if (!is.null(ref.nii)) {
dims <- info.nii(ref.nii, "xyz")
pixdim <- info.nii(ref.nii, "pixdim")
orient <- info.nii(ref.nii, "orient")
datatype <- info.nii(ref.nii, "datatype")
} else {
if (is.null(pixdim)) { pixdim <- c(-1,2,2,2,1,0,0,0) }
if (is.null(orient)) {
orient$qform_code <- 2
orient$sform_code <- 2
orient$quatern_b <- 0
orient$quatern_c <- 1
orient$quatern_d <- 0
orient$qoffset_x <- 90
orient$qoffset_y <- -126
orient$qoffset_z <- -72
orient$srow_x <- c(-2,0,0,90)
orient$srow_y <- c(0,2,0,-126)
orient$srow_z <- c(0,0,2,-72)
}
}
datatype.lut <- c(2L, 4L, 8L, 16L, 32L, 64L, 128L, 256L, 512L, 768L, 1024L, 1280L)
bitpix.lut <- c(8L, 16L, 32L, 32L, 64L, 64L, 24L, 8L, 16L, 32L, 64L, 64L)
idx <- which(datatype.lut == datatype)
if (length(idx)==0) { stop(sprintf("Datatype %s is not supported.", datatype)) }
datatype <- as.integer(datatype)
bitpix <- bitpix.lut[idx]
writeBin(348L, fid, size = 4)
suppressWarnings(writeChar("", fid, nchars = 10, eos = NULL))
suppressWarnings(writeChar("", fid, nchars = 18, eos = NULL))
writeBin(0L, fid, size = 4)
writeBin(0L, fid, size = 2)
writeChar("r", fid, nchars = 1, eos = NULL)
writeBin(0L, fid, size = 1)
img.dims <- rep(1,8)
img.dims[1] <- length(dims)
img.dims[2:(1+length(dims))] <- dims
writeBin(as.integer(img.dims), fid, size = 2)
writeBin(as.double(0), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(0L, fid, size = 2)
writeBin(datatype, fid, size = 2)
writeBin(bitpix, fid, size = 2)
writeBin(1L, fid, size = 2)
writeBin(as.double(pixdim), fid, size = 4)
writeBin(as.double(352), fid, size = 4)
writeBin(as.double(1), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(0L, fid, size = 2)
writeBin(0L, fid, size = 1)
writeBin(2L, fid, size = 1)
writeBin(as.double(0), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(as.double(0), fid, size = 4)
writeBin(0L, fid, size = 4)
writeBin(0L, fid, size = 4)
suppressWarnings(writeChar("R_nifti_io", fid, nchars = 80, eos = NULL))
suppressWarnings(writeChar("", fid, nchars = 24, eos = NULL))
writeBin(as.integer(orient$qform_code), fid, size = 2)
writeBin(as.integer(orient$sform_code), fid, size = 2)
writeBin(as.double(orient$quatern_b), fid, size = 4)
writeBin(as.double(orient$quatern_c), fid, size = 4)
writeBin(as.double(orient$quatern_d), fid, size = 4)
writeBin(as.double(orient$qoffset_x), fid, size = 4)
writeBin(as.double(orient$qoffset_y), fid, size = 4)
writeBin(as.double(orient$qoffset_z), fid, size = 4)
writeBin(as.double(orient$srow_x), fid, size = 4)
writeBin(as.double(orient$srow_y), fid, size = 4)
writeBin(as.double(orient$srow_z), fid, size = 4)
suppressWarnings(writeChar("0", fid, nchars = 16, eos = NULL))
suppressWarnings(writeChar("n+1", fid, nchars = 4, eos = NULL))
writeBin(c(0L,0L,0L,0L), fid, size = 1)
data <- array(init.value, dim=dims[1:3])
if (length(dims==3)) { dims <- c(dims, 1) }
for (i in 1:dims[4]) {
switch(as.character(datatype),
`2` = writeBin(as.integer(data), fid, size = bitpix/8),
`4` = writeBin(as.integer(data), fid, size = bitpix/8),
`8` = writeBin(as.integer(data), fid, size = bitpix/8),
`16` = writeBin(as.double(data), fid, size = bitpix/8),
`32` = writeBin(as.double(data), fid, size = bitpix/8),
`64` = writeBin(as.double(data), fid, size = bitpix/8),
`128` = writeBin(as.integer(data), fid, size = bitpix/8),
`256` = writeBin(as.integer(data), fid, size = bitpix/8),
`512` = writeBin(as.integer(data), fid, size = bitpix/8),
`768` = writeBin(as.integer(data), fid, size = bitpix/8),
`1024` = writeBin(as.integer(data), fid, size = bitpix/8),
`1280` = writeBin(as.integer(data), fid, size = bitpix/8))
}
close(fid)
}
|
D_regularized <-
function(data,
mv.vars,
group.var,
group.values,
alpha = 0.5,
nfolds = 10,
s = "lambda.min",
type.measure = "deviance",
rename.output = TRUE,
out = FALSE,
size = NULL,
fold = FALSE,
fold.var = NULL,
pcc = FALSE,
auc = FALSE,
pred.prob = FALSE,
prob.cutoffs = seq(0, 1, 0.20)) {
if (out & fold) {
D_regularized_fold_out(
data = data,
mv.vars = mv.vars,
group.var = group.var,
group.values = group.values,
alpha = alpha,
s = s,
type.measure = type.measure,
rename.output = rename.output,
size = size,
fold.var = fold.var,
pcc = pcc,
auc = auc,
pred.prob = pred.prob,
prob.cutoffs = prob.cutoffs
)
}
else if (out & !fold) {
D_regularized_out(
data = data,
mv.vars = mv.vars,
group.var = group.var,
group.values = group.values,
alpha = alpha,
size = size,
s = s,
type.measure = type.measure,
rename.output = rename.output,
pcc = pcc,
auc = auc,
pred.prob = pred.prob,
prob.cutoffs = prob.cutoffs
)
}
else if (!out & fold) {
D_regularized_fold(
data = data,
mv.vars = mv.vars,
group.var = group.var,
group.values = group.values,
alpha = alpha,
s = s,
type.measure = type.measure,
rename.output = rename.output,
fold.var = fold.var
)
}
else {
D_regularized_vanilla(
data = data,
mv.vars = mv.vars,
group.var = group.var,
group.values = group.values,
alpha = alpha,
s = s,
type.measure = type.measure,
rename.output = rename.output
)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.