code
stringlengths 1
13.8M
|
---|
publish.MIresult <- function(object,
confint.method,
pvalue.method,
digits=c(2,4),
print=TRUE,
factor.reference="extraline",
intercept,
units=NULL,
fit,
data,
...){
pvalMIresult <- function(object){
se <- sqrt(diag(stats::vcov(object)))
p <- 2*stats::pnorm(-abs(object$coef/se))
p
}
if (missing(fit)) stop("Need the model fitted in the complete cases.")
object$xlevels <- fit$xlevels
object$formula <- fit$formula
if (missing(data)){
if (is.null(fit$data)) stop("Need original data set via argument 'data' because argument 'fit' does not provide them.")
else{
object$data <- fit$data
}
}else object$data <- data
object$terms <- fit$terms
class(object) <- c(class(object),class(fit))
if ('glm' %in% class(fit))
object$family <- fit$family
if (!missing(confint.method) && confint.method!="default") stop("Can only do simple Wald confidence intervals based on MIresults.")
if (!missing(pvalue.method)) stop("Can only do simple Wald test p-values based on MIresults.")
if (missing(intercept)){
intercept <- 1*(class(fit)[1] == "lm" ||
(class(fit)[1]=="glm" && stats::family(fit)!="binomial"))
}
rt <- regressionTable(object,
confint.method="default",
pvalue.method=pvalMIresult,
factor.reference=factor.reference,
intercept=intercept,
units=units)
srt <- summary.regressionTable(rt,
digits=digits,
print=FALSE,...)
XXsrt <- do.call(labelUnits,c(list(x=srt),list(...),srt$Variable))
if (print==TRUE)
publish(srt$regressionTable,...)
invisible(srt)
} |
test_that("Mmethods() messages",{
expect_error(Mmethods("Ogle"),
"should be one of")
})
test_that("metaM() messages",{
expect_error(metaM("Ogle"),
"should be one of")
expect_error(metaM("tmax"),
"must be given to")
expect_error(metaM("PaulyL",Linf=200,K=0.3),
"must be given to")
expect_error(metaM("PaulyL",Linf=200,T=10),
"must be given to")
expect_error(metaM("PaulyL",K=0.3,T=10),
"must be given to")
expect_error(metaM("PaulyL",K=0.3,a=3),
"unused argument")
expect_error(metaM("HoenigO"),
"must be given to")
expect_error(metaM("HoenigO",Linf=200),
"must be given to")
expect_warning(metaM("PaulyL",Linf=200,K=0.3,T=-3),
"seems unreasonable")
expect_warning(metaM("PaulyL",Linf=200,K=0.3,T=33),
"seems unreasonable")
expect_error(metaM("PaulyL",Linf=200,K=-0.3,T=13),
"'K' must be positive")
expect_error(metaM("PaulyL",Linf=0,K=0.3,T=13),
"'Linf' must be positive")
expect_warning(metaM("PaulyL",Linf=2000,K=0.3,T=13),
"'Linf' value seems unreasonable")
expect_error(metaM("HoenigO",tmax=0),
"'tmax' must be positive")
expect_warning(metaM("HoenigO",tmax=110),
"'tmax' value seems unreasonable")
expect_error(metaM("K1",K=0),
"'K' must be positive")
expect_warning(metaM("K1",K=5),
"'K' value seems unreasonable")
})
test_that("metaM() output",{
meths <- c("PaulyL","PaulyW","HoenigO","HoenigOF","HoenigO2","HoenigO2F",
"JensenK1","Gislason","AlversonCarney","Charnov","ZhangMegreyD",
"RikhterEfanov1","RikhterEfanov2")
for (i in meths) {
expect_is(metaM(i,tmax=3,Linf=12.93,Winf=20.79,K=0.23,t0=-1.23,
b=3.22,t50=0.83,T=17,L=3),"numeric")
}
for (i in meths) {
tmp <- metaM(i,justM=FALSE,tmax=3,Linf=12.93,Winf=20.79,K=0.23,t0=-1.23,
b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"metaM")
expect_equal(mode(tmp),"list")
expect_equal(tmp[["method"]],i)
expect_message(print(tmp))
}
tmp <- metaM(meths[1:2],tmax=3,Linf=12.93,Winf=20.79,K=0.23,t0=-1.23,
b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),2)
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,meths[1:2])
expect_equal(ncol(tmp),2)
tmp <- metaM(meths,tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),length(meths))
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,meths)
expect_equal(ncol(tmp),2)
expect_message(tmp <- metaM(meths,justM=FALSE,tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3))
tmp <- metaM(Mmethods("tmax"),tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),length(Mmethods("tmax")))
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,Mmethods("tmax"))
expect_equal(ncol(tmp),2)
tmp <- metaM(Mmethods("K"),tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),length(Mmethods("K")))
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,Mmethods("K"))
expect_equal(ncol(tmp),2)
tmp <- metaM(Mmethods("Pauly"),tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),length(Mmethods("Pauly")))
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,Mmethods("Pauly"))
expect_equal(ncol(tmp),2)
tmp <- metaM(Mmethods("Hoenig"),tmax=3,Linf=12.93,Winf=20.79,
K=0.23,t0=-1.23,b=3.22,t50=0.83,T=17,L=3)
expect_is(tmp,"data.frame")
expect_equal(nrow(tmp),length(Mmethods("Hoenig")))
expect_equal(names(tmp),c("method","M"))
expect_equal(tmp$method,Mmethods("Hoenig"))
expect_equal(ncol(tmp),2)
})
test_that("metaM() matches results from Kenchington (2014)",{
meths <- c("PaulyL","PaulyW","HoenigO","HoenigOF","HoenigO2","HoenigO2F",
"JensenK1","Gislason","AlversonCarney","Charnov","ZhangMegreyD",
"RikhterEfanov1","RikhterEfanov2")
tmp <- metaM(meths,tmax=3,Linf=12.93,Winf=20.79,K=0.23,t0=-1.23,
b=3.22,t50=0.83,T=17,L=3)
tmp <- data.frame(tmp,expM=c(0.69,0.66,1.43,1.42,1.69,1.83,0.35,2.71,
2.30,2.06,1.17,1.58,1.22))
expect_equivalent(round(tmp$M,2)[-7],tmp$expM[-7])
tmp <- metaM(meths,tmax=8,Linf=8.306,Winf=8.68,K=0.204,t0=-0.64,
b=3.26,t50=2,T=8,L=2)
tmp <- data.frame(tmp,expM=c(0.51,0.46,0.55,0.61,0.58,0.64,0.31,
2.44,0.71,1.73,0.77,0.77,0.93))
expect_equivalent(round(tmp$M,2)[-c(4,6)],tmp$expM[-c(4,6)])
meths <- c("PaulyL","PaulyW","HoenigO","HoenigOF","HoenigO2","HoenigO2F",
"JensenK1","Gislason","AlversonCarney","Charnov","ZhangMegreyP",
"RikhterEfanov1","RikhterEfanov2")
tmp <- metaM(meths,tmax=5.5,Linf=19.76,Winf=17.3,K=0.571,t0=-0.91
,b=3.276,t50=0.49,T=19,L=10)
tmp <- data.frame(tmp,expM=c(1.16,1.30,0.79,0.77,0.88,0.87,0.86,
1.78,0.75,1.59,0.33,2.39,1.53))
expect_equivalent(round(tmp$M,2),tmp$expM)
})
test_that("metaM() matches M.empirical() from fishmethods for Rio Formosa Seahorse",{
if (require(fishmethods)) {
meths <- c("PaulyL","PaulyW","HoenigO","HoenigOF","AlversonCarney","Gislason")
tmp <- metaM(meths,tmax=5.5,Linf=19.76,Winf=17.3,K=0.571,t0=-0.91,
b=3.276,t50=0.49,T=19,L=10)
tmp2 <- M.empirical(Linf=19.76,Winf=17.3,Kl=0.571,Kw=0.571,TC=19,
Bl=10,tmax=5.5,method=c(1:4,9))
tmp <- data.frame(tmp,tmp2)
expect_equivalent(round(tmp$M,3),tmp$M.1)
}
}) |
load_fasta <- function(msa, keep.singletons=FALSE) {
if(class(msa)=="character"){
if (!file.exists(msa)) stop("Invalid msa or the file does not exist!")
seqs <- ape::read.FASTA(msa)
} else if(class(msa)=="matrix"){
seqs <- ape::as.DNAbin(msa)
} else if(class(msa)=="DNAbin"){
seqs <- msa
} else{
stop("incorrect input for msa!")
}
if (!is.logical(keep.singletons)) stop("Invalid keep.singletons! Must be on of TRUE/FALSE.")
seq_names <- labels(seqs)
seqs <- as.character(as.matrix(seqs))
rownames(seqs) <- seq_names
seqs[is.na(seqs)] <- "-"
if (nrow(seqs)<3) stop("Less than 3 sequences!")
warning("Characters not in acgtnACGTN- will be treated as missing (-)...")
conserved <- colSums(t(t(seqs)==seqs[1,]))==nrow(seqs)
seqs <- seqs[, !conserved]
if(!keep.singletons){
is_singleton <- apply(seqs, 2, function(x){
tab <- table(x)
return(x %in% names(tab)[tab==1])
})
seqs[is_singleton] <- "-"
}
seqs[seqs=="n"] <- "-"
return(seqs)
} |
mwin <- function (dat,win,conv=1,verbose=T)
{
if(verbose) cat("\n----- DETERMINING PARAMETERS OF DYNAMIC MOVING WINDOW -----\n")
dat=data.frame(dat)
ipts <- length(dat[,1])
if(verbose) cat(" * Number of data points=", ipts,"\n")
if(conv != 1 && conv != 2 && conv != 3)
{
cat("\n**** ERROR: conv must be set to 1, 2, or 3\n")
stop("**** TERMINATING NOW!")
}
if(conv == 1 || conv == 2)
{
if(verbose) cat(" * Sorting\n")
dat <- dat[order(dat[,1],na.last=NA,decreasing=F),]
}
if(conv == 3)
{
if(verbose) cat(" * Sorting\n")
dat <- dat[order(dat[,1],na.last=NA,decreasing=T),]
dat[1]=-1*dat[1]
}
if(length(dat[,1]) != ipts)
{
cat("\n**** ERROR: empty entires found\n")
stop("**** TERMINATING NOW!")
}
dtest <- dat[2:ipts,1]-dat[1:(ipts-1),1]
if(any(dtest == 0))
{
cat("\n**** ERROR: duplicate stratigraphic levels found.\n")
stop("**** TERMINATING NOW!")
}
x <- dat[,1]
getwin1 <- function (ipts,win,x)
{
F_dat = .Fortran( 'mwincenter_r',
ipts=as.integer(ipts),winsize=as.double(win),x=as.double(x),
npts=integer(1),n1=integer(ipts),n2=integer(ipts),avex=double(ipts),
midx1=double(ipts),midx2=double(ipts)
)
return(F_dat)
}
getwin2 <- function (ipts,win,x)
{
F_dat = .Fortran( 'mwin_r',
ipts=as.integer(ipts),winsize=as.double(win),x=as.double(x),
npts=integer(1),n1=integer(ipts),n2=integer(ipts),avex=double(ipts),
midx1=double(ipts),midx2=double(ipts)
)
return(F_dat)
}
if(conv == 1) out <- getwin1(ipts,win,x)
if(conv == 2 || conv == 3) out <- getwin2(ipts,win,x)
npts=out$npts
out2=data.frame(cbind(out$n1[1:npts],out$n2[1:npts],out$avex[1:npts],out$midx1[1:npts],out$midx2[1:npts]))
colnames(out2) = c("n1","n2","avex","center","midpoint")
if(conv == 3)
{
out2[3] = -1*out2[3]
out2[4] = -1*out2[4]
out2[5] = -1*out2[5]
out2[,1] = ipts - out$n2[1:npts] + 1
out2[,2] = ipts - out$n1[1:npts] + 1
out2 <- out2[order(out2[,4],na.last=NA,decreasing=F),]
}
if(verbose)
{
if(any(out2[,1]==out2[,2])) cat("\n**** WARNING: some windows contain only one data point!\n")
}
return(out2)
} |
setGeneric(
name = "getCellSize",
def = function(object, ...) {
standardGeneric("getCellSize")
}
) |
test_that("`predict_coding_impact` works", {
path2annovar_csv <- system.file("extdata/example.hg19_multianno.csv",
package = "driveR")
expect_is(metapred_df <- predict_coding_impact(path2annovar_csv), "data.frame")
expect_equal(ncol(metapred_df), 2)
tmp <- read.csv(path2annovar_csv)
tmp <- tmp[tmp$CADD_phred == ".", ]
path2corner <- tempfile()
write.csv(tmp, path2corner, row.names = FALSE)
expect_is(metapred_df <- predict_coding_impact(path2corner), "data.frame")
expect_equal(nrow(metapred_df), 0)
expect_equal(ncol(metapred_df), 2)
})
test_that("`predict_coding_impact` argument checks work", {
expect_error(predict_coding_impact("invalid/path/to/csv"),
"The file used for `annovar_csv_path` does not exist")
path2annovar_csv <- system.file("extdata/example.hg19_multianno.csv",
package = "driveR")
annovar_df <- read.csv(path2annovar_csv)
annovar_df$Gene.refGene <- NULL
path2annovar_csv <- tempfile()
write.csv(annovar_df, path2annovar_csv, row.names = FALSE)
nec_cols <- c("Gene.refGene",
"SIFT_score", "Polyphen2_HDIV_score", "LRT_score",
"MutationTaster_score", "MutationAssessor_score",
"FATHMM_score", "GERP.._RS", "phyloP7way_vertebrate",
"CADD_phred", "VEST3_score", "SiPhy_29way_logOdds",
"DANN_score")
expect_error(predict_coding_impact(path2annovar_csv),
paste0("The table in `annovar_csv_path` should contain all of the following columns: ",
paste(dQuote(nec_cols), collapse = ", ")))
path2annovar_csv <- system.file("extdata/example.hg19_multianno.csv",
package = "driveR")
expect_error(predict_coding_impact(path2annovar_csv,
keep_highest_score = "INVALID"),
"`keep_highest_score` should be logical")
expect_error(predict_coding_impact(path2annovar_csv,
keep_single_symbol = "INVALID"),
"`keep_single_symbol` should be logical")
})
test_that("`create_features_df` works", {
path2annovar_csv <- system.file("extdata/example.hg19_multianno.csv",
package = "driveR")
path2phenolyzer_out <- system.file("extdata/example.annotated_gene_list",
package = "driveR")
expect_is(features_df <- create_features_df(annovar_csv_path = path2annovar_csv,
scna_df = example_scna_table,
phenolyzer_annotated_gene_list_path = path2phenolyzer_out),
"data.frame")
expect_equal(ncol(features_df), 27)
expect_is(create_features_df(annovar_csv_path = path2annovar_csv,
scna_df = example_scna_table,
prep_phenolyzer_input = TRUE),
"character")
path2annovar_csv <- system.file("extdata/example_cohort.hg19_multianno.csv",
package = "driveR")
path2phenolyzer_out <- system.file("extdata/example_cohort.annotated_gene_list",
package = "driveR")
expect_is(features_df <- create_features_df(annovar_csv_path = path2annovar_csv,
scna_df = example_cohort_scna_table,
phenolyzer_annotated_gene_list_path = path2phenolyzer_out,
batch_analysis = TRUE),
"data.frame")
expect_equal(ncol(features_df), 27)
tmp <- read.csv(path2annovar_csv)
tmp <- tmp[tmp$CADD_phred == ".", ]
path2corner <- tempfile()
write.csv(tmp, path2corner, row.names = FALSE)
expect_is(features_df <- create_features_df(annovar_csv_path = path2corner,
scna_df = example_scna_table,
phenolyzer_annotated_gene_list_path = path2phenolyzer_out),
"data.frame")
expect_equal(ncol(features_df), 27)
tmp <- tmp[1:2, ]
tmp$cosmic91_coding <- tmp$cosmic91_noncoding <- "."
path2corner <- tempfile()
write.csv(tmp, path2corner, row.names = FALSE)
tmp_scna_table <- example_scna_table[1:2, ]
tmp_scna_table$log2ratio <- .1
expect_warning(features_df <- create_features_df(annovar_csv_path = path2corner,
scna_df = tmp_scna_table,
phenolyzer_annotated_gene_list_path = path2phenolyzer_out))
})
test_that("`create_features_df` argument check works", {
expect_error(create_features_df(prep_phenolyzer_input = "INVALID"),
"`prep_phenolyzer_input` should be logical")
})
test_that("`prioritize_driver_genes` works", {
expect_is(drivers_df <- prioritize_driver_genes(example_features_table, "LUAD"),
"data.frame")
})
test_that("`prioritize_driver_genes` argument check works", {
expect_error(prioritize_driver_genes(example_features_table, "INVALID"),
"`cancer_type` should be one of the short names in `MTL_submodel_descriptions`")
expect_error(prioritize_driver_genes(matrix()),
"`features_df` should be a data frame")
expect_error(prioritize_driver_genes(example_features_table[, -1], "LUAD"),
"`features_df` should contain exactly 27 columns")
req_names <- c("gene_symbol", "metaprediction_score", "noncoding_score",
"scna_score", "hotspot_double_hit", "phenolyzer_score",
"hsa03320", "hsa04010", "hsa04020", "hsa04024", "hsa04060",
"hsa04066", "hsa04110", "hsa04115", "hsa04150", "hsa04151",
"hsa04210", "hsa04310", "hsa04330", "hsa04340", "hsa04350",
"hsa04370", "hsa04510", "hsa04512", "hsa04520", "hsa04630",
"hsa04915")
tmp <- example_features_table
colnames(tmp)[1] <- "INVALID"
expect_error(prioritize_driver_genes(tmp, "LUAD"),
paste0("`features_df` should contain the following columns: ",
paste(dQuote(req_names), collapse = ", ")))
}) |
library("rentrez")
library("httr")
library("XML")
library("ape")
library("BoSSA")
set_config(config(http_version = 0))
tree <- read.tree(paste(find.package("BoSSA"),"/extdata/polerovirus_from_genbank_MAFFT.tre",sep=""))
plot(tree,cex=0.4,no.margin=TRUE)
nodelabels(cex=0.8)
root_tree <- root(tree,node=231,resolve=TRUE)
plot(root_tree,cex=0.4,no.margin=TRUE)
write.tree(root_tree,"polerovirus_ROOTED.tre")
refpkg_path <- paste(find.package("BoSSA"),"/extdata/polerovirus.refpkg",sep="")
refpkg(refpkg_path)
refpkg(refpkg_path,type="tree",cex.text=0.3,rank_tree="species")
refpkg(refpkg_path,type="pie",rank_pie="species",cex.text=0.6)
refpkg(refpkg_path,type="krona")
citation("BoSSA") |
beta_bda_prior <- function(x) {
return(-2.5 * log(x[1] + x[2]))
}
beta_gamma_prior <- function(x, hpars) {
return(stats::dgamma(x[1], shape = hpars[1], rate = hpars[2], log = TRUE) +
stats::dgamma(x[2], shape = hpars[3], rate = hpars[4], log = TRUE))
}
beta_gamma_hpars <- function() {
return(c(1, 0.01, 1, 0.01))
}
beta_phi_to_theta <- function(phi) {
apb <- exp(phi[2])
beta <- apb / (1 + exp(phi[1]))
return(c(apb - beta, beta))
}
beta_log_j <- function(theta) {
return(-log(theta[1]) - log(theta[2]))
}
beta_init_ests <- function(data, param) {
prob <- data[, 1] / data[, 2]
mp <- mean(prob)
vp <- stats::var(prob)
if (vp < mp * (1 - mp)) {
mult <- (mp * (1 - mp) / vp - 1)
alpha <- mp * mult
beta <- (1 - mp) * mult
} else {
alpha <- 0.1
beta <- alpha * mp / (1 - mp)
}
if (param == "trans") {
init <- c(log(alpha / beta), log(alpha + beta))
} else {
init <- c(alpha, beta)
}
return(init)
}
beta_create_ru_list <- function(param) {
d <- 2L
var_names <- c("alpha", "beta")
if (param == "trans") {
lower <- c(-Inf, -Inf)
upper <- c(Inf, Inf)
} else {
lower <- c(0, 0)
upper <- c(Inf, Inf)
}
return(list(d = d, lower = lower, upper = upper, var_names = var_names))
} |
ki_station_list <- function(hub, search_term, bounding_box, group_id, return_fields) {
garbage <- c(
"^
"^Template\\s", "\\sTEST$",
"\\sTEMP$", "\\stest\\s"
)
if (missing(return_fields)) {
return_fields <- "station_name,station_no,station_id,station_latitude,station_longitude"
} else {
if (!inherits(return_fields, "character")) {
stop(
"User supplied return_fields must be comma separated string or vector of strings"
)
}
}
api_url <- check_hub(hub)
api_query <- list(
service = "kisters",
type = "queryServices",
request = "getStationList",
format = "json",
kvp = "true",
returnfields = paste(
return_fields,
collapse = ","
)
)
if (!missing(search_term)) {
search_term <- paste(search_term,
toupper(search_term),
tolower(search_term),
sep = ","
)
api_query[["station_name"]] <- search_term
}
if (!missing(bounding_box)) {
bounding_box <- paste(bounding_box, collapse = ",")
api_query[["bbox"]] <- bounding_box
}
if (!missing(group_id)) {
api_query[["stationgroup_id"]] <- group_id
}
raw <- tryCatch(
{
httr::GET(
url = api_url,
query = api_query,
httr::timeout(15)
)
},
error = function(e) {
return(e)
}
)
check_ki_response(raw)
raw_content <- httr::content(raw, "text")
json_content <- jsonlite::fromJSON(raw_content)
if (inherits(json_content, "character")) {
return("No matches for search term.")
}
content_dat <- tibble::as_tibble(
x = json_content,
.name_repair = "minimal"
)[-1, ]
names(content_dat) <- json_content[1, ]
if ("station_name" %in% names(content_dat)) {
content_dat <- content_dat[!grepl(
paste(garbage, collapse = "|"),
content_dat$station_name
), ]
}
content_dat <- suppressWarnings(
dplyr::mutate_at(
content_dat,
dplyr::vars(
dplyr::one_of(c("station_latitude", "station_longitude"))
),
as.double
)
)
return(content_dat)
} |
hct_method_single <-
function(dummy, mu0, p, m, n, hct, alpha0, p1, ss, sampling.p)
{
n1=ceiling(n*sampling.p)
n2=n-n1
tau=2*mu0/(sqrt(1/n1+1/n2))
zscore_alt=rt(m, df=n-2, ncp=tau)
pvalue_alt=2*pt(abs(zscore_alt),df=n-2, lower.tail=F)
pvalue_null=gen_sim_pvalue_null(p, m, alpha0)
pvalue=c(pvalue_alt, pvalue_null)
pvalue=sort(pvalue, method='quick')[1:ceiling(p*alpha0)]
pvalue_threshold=hct(pvalue, p, n)
u=(sum(zscore_alt>=0 & pvalue_alt<=pvalue_threshold)-sum(zscore_alt < 0 & pvalue_alt<=pvalue_threshold))*mu0
v=sum(pvalue<=pvalue_threshold)
get_pcc_ss(u, v, p1, ss)
} |
eval_compactness_loc <- function(gene_sigs_list,names_sigs, mRNA_expr_matrix, names_datasets, out_dir = '~',file=NULL,showResults = FALSE,radar_plot_values,logged=T,origin=NULL){
grDevices::dev.new()
max_title_length <- -999
for(i in 1:length(names_sigs)){
for(j in 1:length(names_datasets)){
if(nchar(paste0(names_datasets[[j]] ,' ',names_sigs[[i]])) > max_title_length){
max_title_length <- nchar(paste0(names_datasets[[j]] ,' ',names_sigs[[i]]))
}
}
}
graphics::par(cex.main=min(0.8,(3*6/max_title_length)),cex.lab = 0.6,oma=c(2,0,0,0),mar=c(0,0,0,0))
hmaps <- lapply(1:(length(names_sigs) *length(names_datasets)),function(i) {
dataset_ind <- i %% length(names_datasets)
if (dataset_ind == 0 ){
dataset_ind <- length(names_datasets)
}
sig_ind <- ceiling(i/length(names_datasets))
gene_sig <- gene_sigs_list[[names_sigs[sig_ind]]]
if(is.matrix(gene_sig)){gene_sig = as.vector(gene_sig);}
data.matrix = mRNA_expr_matrix[[names_datasets[dataset_ind]]]
inter <- intersect(gene_sig, row.names(data.matrix))
autocors <- stats::cor(t(stats::na.omit(data.matrix[inter,])),method='spearman')
if(!dir.exists(file.path(out_dir,'autocorrelation_matrices'))){
dir.create(file.path(out_dir,'autocorrelation_matrices'))
}
utils::write.table(autocors,file=file.path(out_dir,'autocorrelation_matrices', paste0('autocorrelation_matrix_',names_sigs[sig_ind],'_',names_datasets[dataset_ind],'.txt')),quote=F,sep='\t')
tryCatch({
gplots::heatmap.2( stats::na.omit(autocors),
col = gplots::colorpanel(100,"blue","white","red"),
trace = "none",
na.color="grey",
labRow=rownames(autocors),
labCol=colnames(autocors),
main = paste0("\n\nIntra-sig. Corr.\n", names_datasets[[dataset_ind]] ,' ',names_sigs[[sig_ind]]),
dendrogram = "col",
symbreaks = T,
Rowv = T,Colv=T ,key.xlab='Rho',key.ylab=NA, key.title=NA,cexRow=max(min(0.5,(4*4/length(rownames(autocors)))),0.06),cexCol=max(min(0.5,(4*4/length(rownames(autocors)))),0.06),margins=c(1+(max(nchar(rownames(autocors)))/2),1+ (max(nchar(rownames(autocors)))/2)))
},
error=function(err){
graphics::plot.new()
graphics::title(paste0('\n\nToo many NA values in \n',names_datasets[dataset_ind],' ',names_sigs[sig_ind]))
cat(paste0("There was an error, ",names_datasets[dataset_ind]," ", names_sigs[sig_ind]," ", err,'\n'), file=file)
})
grab_grob()
})
draw.heatmaps(hmaps,names_datasets,names_sigs)
grDevices::dev.copy(grDevices::pdf,file.path(out_dir,'sig_autocor_hmps.pdf'),width=4*(length(names_datasets)),height=4*(length(names_sigs)))
if(grDevices::dev.cur()!=1){
g <- grDevices::dev.off()
}
if(grDevices::dev.cur()!=1){
g <- grDevices::dev.off()
}
graphics::par(mar=c(0,0,0,0),cex=0.6)
graphics::plot.new()
legend_names <- c()
legend_cols <- c()
legend_lty <- c()
for(k in 1:length(names_sigs)){
for (i in 1:length(names_datasets) ){
legend_names <- c(legend_names,paste0(names_datasets[i],' ',names_sigs[k]))
legend_cols <- c(legend_cols,i)
legend_lty <- c(legend_lty,k)
}
}
l <- graphics::legend(0, 0,legend_names,col=legend_cols,lty=legend_lty,lwd=rep(1,times=(length(names_datasets) * length(names_sigs))),pt.cex=1,cex=min(0.5,(4*10/max_title_length)), plot=FALSE)
w <- graphics::grconvertX(l$rect$w, to='ndc')- graphics::grconvertX(0, to='ndc')
w <- graphics::grconvertX(w,from="ndc",to="inches") + graphics::grconvertX(10,from="device",to="inches")
if (showResults){
grDevices::dev.new()
}else{
grDevices::pdf(file.path(out_dir,'sig_autocor_dens.pdf'),width=5,height=5)
}
graphics::par(cex.main=0.8,cex.lab = 0.6,mar=c(3,3,4,1),mfrow=c(1,1),xpd=TRUE,omi=(c(0,0,0,w)))
max_dens <- -9999
max_x_coord <- -9999
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
if(is.matrix(gene_sig)){gene_sig = as.vector(gene_sig);}
for (i in 1:length(names_datasets) ){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig, row.names(data.matrix))
autocors <- stats::cor(t(stats::na.omit(data.matrix[inter,])),method='spearman')
if(dim(autocors)[1] > 1){
cur_max <- max(stats::density(unlist(stats::na.omit(autocors)))$y)
if (max_dens < cur_max){
max_dens <- cur_max
}
cur_max <- max(stats::density(unlist(stats::na.omit(autocors)))$x)
if (max_x_coord < cur_max){
max_x_coord <- cur_max
}
}
}
}
plots_count <- 0
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
if(is.matrix(gene_sig)){gene_sig = as.vector(gene_sig);}
for (i in 1:length(names_datasets) ){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter <- intersect(gene_sig, row.names(data.matrix))
autocors <- stats::cor(t(stats::na.omit(data.matrix[inter,])),method='spearman')
if(dim(autocors)[1] > 1){
if (plots_count==0){
graphics::plot(stats::density(unlist(stats::na.omit(autocors))),ylim=c(0,ceiling(max_dens)),xlim=c(-1,1),col=i,main=NA,lwd=2,lty=k)
plots_count <- 1
}else{
graphics::lines(stats::density(unlist(stats::na.omit(autocors))),ylim=c(0,ceiling(max_dens)),xlim=c(-1,1),col=i,main=NA,lwd=2,lty=k)
}
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['autocor_median'] <- stats::median(autocors,na.rm=T)
}else{
radar_plot_values[[names_sigs[k]]][[names_datasets[i]]]['autocor_median'] <- 0
}
}
}
graphics::mtext(side = 2, line = 2, 'Density',cex=0.8)
graphics::mtext(side = 1, line = 2, 'Rho',cex=0.8)
graphics::mtext(side = 3, line = 2,'Intra-sig. Corr. Density')
op <- graphics::par(cex=0.6)
graphics::legend(graphics::par('usr')[2]+0.05, graphics::par('usr')[4],xpd=NA,legend_names,col=legend_cols,lty=legend_lty,lwd=rep(1,times=(length(names_datasets) * length(names_sigs))),pt.cex=1,cex=min(0.5,(4*10/max_title_length)))
if(showResults){
grDevices::dev.copy(grDevices::pdf,file.path(out_dir,'sig_autocor_dens.pdf'),width=5,height=5)
}
if(grDevices::dev.cur()!=1){
g <- grDevices::dev.off()
}
if (length(names_datasets) > 1){
for(k in 1:length(names_sigs)){
gene_sig <- gene_sigs_list[[names_sigs[k]]]
if(is.matrix(gene_sig)){gene_sig = as.vector(gene_sig);}
if (showResults){
grDevices::dev.new()
}else{
grDevices::pdf(file.path(out_dir,paste0('sig_autocor_rankProd_',names_sigs[k],'.pdf')),width=10,height=10)
}
graphics::par(cex.main=0.8,cex.lab = 0.6,oma=c(2,2,2,2),mar=c(4,4,4,4))
overall_rank_mat <- matrix(NA,nrow=length(unique(gene_sig)),ncol=length(names_datasets))
row.names(overall_rank_mat) <- unique(gene_sig)
colnames(overall_rank_mat) <- names_datasets
for (i in 1:length(names_datasets)){
data.matrix = mRNA_expr_matrix[[names_datasets[i]]]
inter = intersect(unique(gene_sig),rownames(data.matrix))
autocors <- stats::cor(t(stats::na.omit(data.matrix[inter,])),method='spearman')
median_scores <- as.matrix(apply(autocors,2,function(x) {stats::median(stats::na.omit(x))}))
overall_rank_mat[rownames(median_scores),i] <- median_scores[,1]
}
if(is.null(origin)){
origin <- rep(1,length(names_datasets))
}
RP.out <-RankProd::RPadvance(data = overall_rank_mat,cl = rep(1,times=length(names_datasets)),origin = origin ,logged = T,gene.names=rownames(overall_rank_mat))
RankProd::plotRP(RP.out ,cutoff=0.05)
table_rank_prod <- cbind(RP.out$pfp,RP.out$pval,RP.out$RPs)
colnames(table_rank_prod) <- c(paste0("pfp_",colnames(RP.out$pfp)),paste0('p_val',colnames(RP.out$pval)),paste0("Rank_Product_",colnames(RP.out$RPs)))
if(!dir.exists(file.path(out_dir,'rank_prod'))){
dir.create(file.path(out_dir,'rank_prod'))
}
utils::write.csv(table_rank_prod[order(table_rank_prod[,1]),],file=file.path(out_dir, 'rank_prod',paste0('rank_product_table1_',names_sigs[k],'.txt')),quote=F)
utils::write.csv(table_rank_prod[order(table_rank_prod[,2]),],file=file.path(out_dir, 'rank_prod',paste0('rank_product_table2_',names_sigs[k],'.txt')),quote=F)
cat("Intra-sig. corr. rank product successfully computed.\n", file=file)
if(showResults){
grDevices::dev.copy(grDevices::pdf,file.path(out_dir,paste0('sig_autocor_rankProd_',names_sigs[k],'.pdf')),width=10,height=10)
}
if(grDevices::dev.cur()!=1){
g <- grDevices::dev.off()
}
}
cat("Intra-sig. corr. metrics successfully computed.\n", file=file)
}else{
cat("Rank product not computed as there is only one dataset.\n", file=file)
}
radar_plot_values
} |
.row_names_info <- function(x, type = 1L)
.Internal(shortRowNames(x, type))
row.names <- function(x) UseMethod("row.names")
row.names.data.frame <- function(x) as.character(attr(x, "row.names"))
row.names.default <- function(x) if(!is.null(dim(x))) rownames(x)
.set_row_names <- function(n)
if(n > 0) c(NA_integer_, -n) else integer()
`row.names<-` <- function(x, value) UseMethod("row.names<-")
`.rowNamesDF<-` <- function(x, make.names = FALSE, value)
{
if (!is.data.frame(x)) x <- as.data.frame(x)
n <- .row_names_info(x, 2L)
if(is.null(value)) {
attr(x, "row.names") <- .set_row_names(n)
return(x)
}
if( is.object(value) || !is.integer(value) )
value <- as.character(value)
if(n == 0L) {
if(!is.null(attr(x, "row.names")) && length(value) > 0L)
stop("invalid 'row.names' length")
}
else if (length(value) != n) {
if(isFALSE(make.names)) stop("invalid 'row.names' length")
else if(is.na(make.names)) {
attr(x, "row.names") <- .set_row_names(n)
return(x)
}
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
else if((nv <- length(value)) < n)
value <- c(value, rep_len(value[nv], n-nv))
else
value <- value[seq_len(n)]
}
if (anyDuplicated(value)) {
if(isFALSE(make.names)) {
nonuniq <- sort(unique(value[duplicated(value)]))
warning(ngettext(length(nonuniq),
sprintf("non-unique value when setting 'row.names': %s",
sQuote(nonuniq[1L])),
sprintf("non-unique values when setting 'row.names': %s",
paste(sQuote(nonuniq), collapse = ", "))),
domain = NA, call. = FALSE)
stop("duplicate 'row.names' are not allowed")
}
else if(is.na(make.names)) {
value <- .set_row_names(
if(n == 0L && is.null(.row_names_info(x, 0L)) && length(x) > 0L)
length(x[[1L]])
else n)
}
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
else
value <- make.names(value, unique=TRUE)
}
else if (anyNA(value)) {
if(isFALSE(make.names))
stop("missing values in 'row.names' are not allowed")
if(is.na(make.names))
value <- .set_row_names(n)
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
else
value <- make.names(value, unique=TRUE)
}
attr(x, "row.names") <- value
x
}
`row.names<-.data.frame` <- function(x, value) `.rowNamesDF<-`(x, value=value)
`row.names<-.default` <- function(x, value) `rownames<-`(x, value)
is.na.data.frame <- function (x)
{
y <- if (length(x)) {
do.call(cbind, lapply(x, is.na))
} else matrix(FALSE, length(row.names(x)), 0)
if(.row_names_info(x) > 0L) rownames(y) <- row.names(x)
y
}
anyNA.data.frame <- function(x, recursive = FALSE)
any(vapply(x, anyNA, NA, USE.NAMES = FALSE))
is.data.frame <- function(x) inherits(x, "data.frame")
I <- function(x) { class(x) <- unique.default(c("AsIs", oldClass(x))); x }
print.AsIs <- function (x, ...)
{
cl <- oldClass(x)
oldClass(x) <- cl[cl != "AsIs"]
NextMethod("print")
invisible(x)
}
t.data.frame <- function(x)
{
x <- as.matrix(x)
NextMethod("t")
}
dim.data.frame <- function(x) c(.row_names_info(x, 2L), length(x))
dimnames.data.frame <- function(x) list(row.names(x), names(x))
`dimnames<-.data.frame` <- function(x, value)
{
d <- dim(x)
if(!is.list(value) || length(value) != 2L)
stop("invalid 'dimnames' given for data frame")
value[[1L]] <- as.character(value[[1L]])
value[[2L]] <- as.character(value[[2L]])
if(d[[1L]] != length(value[[1L]]) || d[[2L]] != length(value[[2L]]))
stop("invalid 'dimnames' given for data frame")
row.names(x) <- value[[1L]]
names(x) <- value[[2L]]
x
}
as.data.frame <- function(x, row.names = NULL, optional = FALSE, ...)
{
if(is.null(x))
return(as.data.frame(list()))
UseMethod("as.data.frame")
}
as.data.frame.default <- function(x, ...)
stop(gettextf("cannot coerce class %s to a data.frame",
sQuote(deparse(class(x))[1L])),
domain = NA)
as.data.frame.data.frame <- function(x, row.names = NULL, ...)
{
cl <- oldClass(x)
i <- match("data.frame", cl)
if(i > 1L)
class(x) <- cl[ - (1L:(i-1L))]
if(!is.null(row.names)){
nr <- .row_names_info(x, 2L)
if(length(row.names) == nr)
attr(x, "row.names") <- row.names
else
stop(sprintf(ngettext(nr,
"invalid 'row.names', length %d for a data frame with %d row",
"invalid 'row.names', length %d for a data frame with %d rows"),
length(row.names), nr), domain = NA)
}
x
}
as.data.frame.list <-
function(x, row.names = NULL, optional = FALSE, ...,
cut.names = FALSE, col.names = names(x), fix.empty.names = TRUE,
check.names = !optional,
stringsAsFactors = FALSE)
{
new.nms <- !missing(col.names)
if(cut.names) {
maxL <- if(is.logical(cut.names)) 256L else as.integer(cut.names)
if(any(long <- nchar(col.names, "bytes", keepNA = FALSE) > maxL))
col.names[long] <- paste(substr(col.names[long], 1L, maxL - 6L), "...")
else cut.names <- FALSE
}
m <- match(names(formals(data.frame))[-1L],
col.names, 0L)
if(any.m <- any(m)) col.names[m] <- paste0("..adfl.", col.names[m])
if(new.nms || any.m || cut.names) names(x) <- col.names
alis <- c(list(check.names = check.names, fix.empty.names = fix.empty.names,
stringsAsFactors = stringsAsFactors),
if(!missing(row.names)) list(row.names = row.names))
x <- do.call(data.frame, c(x, alis))
if(any.m) names(x) <- sub("^\\.\\.adfl\\.", "", names(x))
x
}
as.data.frame.vector <- function(x, row.names = NULL, optional = FALSE, ...,
nm = deparse1(substitute(x)))
{
force(nm)
nrows <- length(x)
if(!(is.null(row.names) || (is.character(row.names) && length(row.names) == nrows))) {
warning(gettextf(
"'row.names' is not a character vector of length %d -- omitting it. Will be an error!",
nrows), domain = NA)
row.names <- NULL
}
if(is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if(length(row.names <- names(x)) != nrows || anyDuplicated(row.names))
row.names <- .set_row_names(nrows)
}
if(!is.null(names(x))) names(x) <- NULL
value <- list(x)
if(!optional) names(value) <- nm
structure(value, row.names = row.names, class = "data.frame")
}
as.data.frame.ts <- function(x, ...)
{
if(is.matrix(x))
as.data.frame.matrix(x, ...)
else
as.data.frame.vector(x, ...)
}
as.data.frame.raw <- as.data.frame.vector
as.data.frame.factor <- as.data.frame.vector
as.data.frame.ordered <- as.data.frame.vector
as.data.frame.integer <- as.data.frame.vector
as.data.frame.logical <- as.data.frame.vector
as.data.frame.numeric <- as.data.frame.vector
as.data.frame.complex <- as.data.frame.vector
as.data.frame.character <-
function(x, ..., stringsAsFactors = FALSE)
{
nm <- deparse1(substitute(x))
if(stringsAsFactors) x <- factor(x)
if(!"nm" %in% ...names())
as.data.frame.vector(x, ..., nm = nm)
else as.data.frame.vector(x, ...)
}
as.data.frame.matrix <- function(x, row.names = NULL, optional = FALSE, make.names = TRUE, ...,
stringsAsFactors = FALSE)
{
d <- dim(x)
nrows <- d[[1L]]
ncols <- d[[2L]]
ic <- seq_len(ncols)
dn <- dimnames(x)
if(is.null(row.names)) row.names <- dn[[1L]]
collabs <- dn[[2L]]
if(any(empty <- !nzchar(collabs)))
collabs[empty] <- paste0("V", ic)[empty]
value <- vector("list", ncols)
if(mode(x) == "character" && stringsAsFactors) {
for(i in ic)
value[[i]] <- as.factor(x[,i])
} else {
for(i in ic)
value[[i]] <- as.vector(x[,i])
}
autoRN <- (is.null(row.names) || length(row.names) != nrows)
if(length(collabs) == ncols)
names(value) <- collabs
else if(!optional)
names(value) <- paste0("V", ic)
class(value) <- "data.frame"
if(autoRN)
attr(value, "row.names") <- .set_row_names(nrows)
else
.rowNamesDF(value, make.names=make.names) <- row.names
value
}
as.data.frame.model.matrix <-
function(x, row.names = NULL, optional = FALSE, make.names = TRUE, ...)
{
d <- dim(x)
nrows <- d[[1L]]
dn <- dimnames(x)
row.names <- dn[[1L]]
value <- list(x)
if(!optional) names(value) <- deparse(substitute(x))[[1L]]
class(value) <- "data.frame"
if(!is.null(row.names)) {
row.names <- as.character(row.names)
if(length(row.names) != nrows)
stop(sprintf(ngettext(length(row.names),
"supplied %d row name for %d rows",
"supplied %d row names for %d rows"),
length(row.names), nrows), domain = NA)
.rowNamesDF(value, make.names=make.names) <- row.names
}
else attr(value, "row.names") <- .set_row_names(nrows)
value
}
as.data.frame.array <- function(x, row.names = NULL, optional = FALSE, ...)
{
d <- dim(x)
if(length(d) == 1L) {
value <- as.data.frame.vector( c(x), row.names, optional, ...)
if(!optional) names(value) <- deparse(substitute(x))[[1L]]
value
} else if (length(d) == 2L) {
as.data.frame.matrix(x, row.names, optional, ...)
} else {
dn <- dimnames(x)
dim(x) <- c(d[1L], prod(d[-1L]))
if(!is.null(dn)) {
if(length(dn[[1L]])) rownames(x) <- dn[[1L]]
for(i in 2L:length(d))
if(is.null(dn[[i]])) dn[[i]] <- seq_len(d[i])
colnames(x) <- interaction(expand.grid(dn[-1L]))
}
as.data.frame.matrix(x, row.names, optional, ...)
}
}
`[.AsIs` <- function(x, i, ...) I(NextMethod("["))
as.data.frame.AsIs <- function(x, row.names = NULL, optional = FALSE, ...)
{
if(length(dim(x)) == 2L)
as.data.frame.model.matrix(x, row.names, optional)
else {
nrows <- length(x)
nm <- deparse1(substitute(x))
if(is.null(row.names)) {
autoRN <- FALSE
if (nrows == 0L)
row.names <- character()
else if(length(row.names <- names(x)) == nrows &&
!anyDuplicated(row.names)) {
}
else {
autoRN <- TRUE
row.names <- .set_row_names(nrows)
}
} else
autoRN <- is.integer(row.names) && length(row.names) == 2L &&
is.na(rn1 <- row.names[[1L]]) && rn1 < 0
value <- list(x)
if(!optional) names(value) <- nm
class(value) <- "data.frame"
attr(value, "row.names") <- row.names
value
}
}
data.frame <-
function(..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
fix.empty.names = TRUE,
stringsAsFactors = FALSE)
{
data.row.names <-
if(check.rows && is.null(row.names))
function(current, new, i) {
if(is.character(current)) new <- as.character(new)
if(is.character(new)) current <- as.character(current)
if(anyDuplicated(new))
return(current)
if(is.null(current))
return(new)
if(all(current == new) || all(current == ""))
return(new)
stop(gettextf(
"mismatch of row names in arguments of 'data.frame\', item %d", i),
domain = NA)
}
else function(current, new, i) {
if(is.null(current)) {
if(anyDuplicated(new)) {
warning(gettextf(
"some row.names duplicated: %s --> row.names NOT used",
paste(which(duplicated(new)), collapse=",")),
domain = NA)
current
} else new
} else current
}
object <- as.list(substitute(list(...)))[-1L]
mirn <- missing(row.names)
mrn <- is.null(row.names)
x <- list(...)
n <- length(x)
if(n < 1L) {
if(!mrn) {
if(is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if(anyNA(row.names))
stop("row names contain missing values")
if(anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s",
paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")),
domain = NA)
} else row.names <- integer()
return(structure(list(), names = character(),
row.names = row.names,
class = "data.frame"))
}
vnames <- names(x)
if(length(vnames) != n)
vnames <- character(n)
no.vn <- !nzchar(vnames)
vlist <- vnames <- as.list(vnames)
nrows <- ncols <- integer(n)
for(i in seq_len(n)) {
xi <- if(is.character(x[[i]]) || is.list(x[[i]]))
as.data.frame(x[[i]], optional = TRUE,
stringsAsFactors = stringsAsFactors)
else as.data.frame(x[[i]], optional = TRUE)
nrows[i] <- .row_names_info(xi)
ncols[i] <- length(xi)
namesi <- names(xi)
if(ncols[i] > 1L) {
if(length(namesi) == 0L) namesi <- seq_len(ncols[i])
vnames[[i]] <- if(no.vn[i]) namesi
else paste(vnames[[i]], namesi, sep=".")
} else if(length(namesi)) {
vnames[[i]] <- namesi
} else if (fix.empty.names && no.vn[[i]]) {
tmpname <- deparse(object[[i]], nlines = 1L)[1L]
if(startsWith(tmpname, "I(") && endsWith(tmpname, ")")) {
ntmpn <- nchar(tmpname, "c")
tmpname <- substr(tmpname, 3L, ntmpn - 1L)
}
vnames[[i]] <- tmpname
}
if(mirn && nrows[i] > 0L) {
rowsi <- attr(xi, "row.names")
if(any(nzchar(rowsi)))
row.names <- data.row.names(row.names, rowsi, i)
}
nrows[i] <- abs(nrows[i])
vlist[[i]] <- xi
}
nr <- max(nrows)
for(i in seq_len(n)[nrows < nr]) {
xi <- vlist[[i]]
if(nrows[i] > 0L && (nr %% nrows[i] == 0L)) {
xi <- unclass(xi)
fixed <- TRUE
for(j in seq_along(xi)) {
xi1 <- xi[[j]]
if(is.vector(xi1) || is.factor(xi1))
xi[[j]] <- rep(xi1, length.out = nr)
else if(is.character(xi1) && inherits(xi1, "AsIs"))
xi[[j]] <- structure(rep(xi1, length.out = nr),
class = class(xi1))
else if(inherits(xi1, "Date") || inherits(xi1, "POSIXct"))
xi[[j]] <- rep(xi1, length.out = nr)
else {
fixed <- FALSE
break
}
}
if (fixed) {
vlist[[i]] <- xi
next
}
}
stop(gettextf("arguments imply differing number of rows: %s",
paste(unique(nrows), collapse = ", ")),
domain = NA)
}
value <- unlist(vlist, recursive=FALSE, use.names=FALSE)
vnames <- as.character(unlist(vnames[ncols > 0L]))
if(fix.empty.names && any(noname <- !nzchar(vnames)))
vnames[noname] <- paste0("Var.", seq_along(vnames))[noname]
if(check.names) {
if(fix.empty.names)
vnames <- make.names(vnames, unique=TRUE)
else {
nz <- nzchar(vnames)
vnames[nz] <- make.names(vnames[nz], unique=TRUE)
}
}
names(value) <- vnames
if(!mrn) {
if(length(row.names) == 1L && nr != 1L) {
if(is.character(row.names))
row.names <- match(row.names, vnames, 0L)
if(length(row.names) != 1L ||
row.names < 1L || row.names > length(vnames))
stop("'row.names' should specify one of the variables")
i <- row.names
row.names <- value[[i]]
value <- value[ - i]
} else if ( !is.null(row.names) && length(row.names) != nr )
stop("row names supplied are of the wrong length")
} else if( !is.null(row.names) && length(row.names) != nr ) {
warning("row names were found from a short variable and have been discarded")
row.names <- NULL
}
class(value) <- "data.frame"
if(is.null(row.names))
attr(value, "row.names") <- .set_row_names(nr)
else {
if(is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if(anyNA(row.names))
stop("row names contain missing values")
if(anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s",
paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")),
domain = NA)
row.names(value) <- row.names
}
value
}
`[.data.frame` <-
function(x, i, j, drop = if(missing(i)) TRUE else length(cols) == 1)
{
mdrop <- missing(drop)
Narg <- nargs() - !mdrop
has.j <- !missing(j)
if(!all(names(sys.call()) %in% c("", "drop"))
&& !isS4(x))
warning("named arguments other than 'drop' are discouraged")
if(Narg < 3L) {
if(!mdrop) warning("'drop' argument will be ignored")
if(missing(i)) return(x)
if(is.matrix(i))
return(as.matrix(x)[i])
nm <- names(x); if(is.null(nm)) nm <- character()
if(!is.character(i) && anyNA(nm)) {
names(nm) <- names(x) <- seq_along(x)
y <- NextMethod("[")
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
cols <- names(y) <- nm[cols]
} else {
y <- NextMethod("[")
cols <- names(y)
if(!is.null(cols) && anyNA(cols))
stop("undefined columns selected")
}
if(anyDuplicated(cols)) names(y) <- make.unique(cols)
attr(y, "row.names") <- .row_names_info(x, 0L)
attr(y, "class") <- oldClass(x)
return(y)
}
if(missing(i)) {
if(drop && !has.j && length(x) == 1L) return(.subset2(x, 1L))
nm <- names(x); if(is.null(nm)) nm <- character()
if(has.j && !is.character(j) && anyNA(nm)) {
names(nm) <- names(x) <- seq_along(x)
y <- .subset(x, j)
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
cols <- names(y) <- nm[cols]
} else {
y <- if(has.j) .subset(x, j) else x
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
}
if(drop && length(y) == 1L) return(.subset2(y, 1L))
if(anyDuplicated(cols)) names(y) <- make.unique(cols)
nrow <- .row_names_info(x, 2L)
if(drop && !mdrop && nrow == 1L)
return(structure(y, class = NULL, row.names = NULL))
else {
attr(y, "class") <- oldClass(x)
attr(y, "row.names") <- .row_names_info(x, 0L)
return(y)
}
}
xx <- x
cols <- names(xx)
x <- vector("list", length(x))
x <- .Internal(copyDFattr(xx, x))
oldClass(x) <- attr(x, "row.names") <- NULL
if(has.j) {
nm <- names(x); if(is.null(nm)) nm <- character()
if(!is.character(j) && anyNA(nm))
names(nm) <- names(x) <- seq_along(x)
x <- x[j]
cols <- names(x)
if(drop && length(x) == 1L) {
if(is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
xj <- .subset2(.subset(xx, j), 1L)
return(if(length(dim(xj)) != 2L) xj[i] else xj[i, , drop = FALSE])
}
if(anyNA(cols)) stop("undefined columns selected")
if(!is.null(names(nm))) cols <- names(x) <- nm[cols]
nxx <- structure(seq_along(xx), names=names(xx))
sxx <- match(nxx[j], seq_along(xx))
} else sxx <- seq_along(x)
rows <- NULL
if(is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
for(j in seq_along(x)) {
xj <- xx[[ sxx[j] ]]
x[[j]] <- if(length(dim(xj)) != 2L) xj[i] else xj[i, , drop = FALSE]
}
if(drop) {
n <- length(x)
if(n == 1L) return(x[[1L]])
if(n > 1L) {
xj <- x[[1L]]
nrow <- if(length(dim(xj)) == 2L) dim(xj)[1L] else length(xj)
drop <- !mdrop && nrow == 1L
} else drop <- FALSE
}
if(!drop) {
if(is.null(rows)) rows <- attr(xx, "row.names")
rows <- rows[i]
if((ina <- anyNA(rows)) | (dup <- anyDuplicated(rows))) {
if (!dup && is.character(rows)) dup <- "NA" %in% rows
if(ina)
rows[is.na(rows)] <- "NA"
if(dup)
rows <- make.unique(as.character(rows))
}
if(has.j && anyDuplicated(nm <- names(x)))
names(x) <- make.unique(nm)
if(is.null(rows)) rows <- attr(xx, "row.names")[i]
attr(x, "row.names") <- rows
oldClass(x) <- oldClass(xx)
}
x
}
`[[.data.frame` <- function(x, ..., exact=TRUE)
{
na <- nargs() - !missing(exact)
if(!all(names(sys.call()) %in% c("", "exact")))
warning("named arguments other than 'exact' are discouraged")
if(na < 3L)
(function(x, i, exact)
if(is.matrix(i)) as.matrix(x)[[i]]
else .subset2(x, i, exact=exact))(x, ..., exact=exact)
else {
col <- .subset2(x, ..2, exact=exact)
i <- if(is.character(..1))
pmatch(..1, row.names(x), duplicates.ok = TRUE)
else ..1
col[[i, exact = exact]]
}
}
`[<-.data.frame` <- function(x, i, j, value)
{
if(!all(names(sys.call()) %in% c("", "value")))
warning("named arguments are discouraged")
nA <- nargs()
if(nA == 4L) {
has.i <- !missing(i)
has.j <- !missing(j)
}
else if(nA == 3L) {
if (is.atomic(value) && !is.null(names(value)))
names(value) <- NULL
if(missing(i) && missing(j)) {
i <- j <- NULL
has.i <- has.j <- FALSE
if(is.null(value)) return(x[logical()])
} else {
if(is.numeric(i) && is.matrix(i) && ncol(i) == 2) {
index <- rep.int(FALSE, prod(dim(x)))
dim(index) <- dim(x)
tryCatch(index[i] <- TRUE,
error = function(e) stop(conditionMessage(e), call.=FALSE))
o <- order(i[,2], i[,1])
N <- length(value)
if (length(o) %% N != 0L)
warning("number of items to replace is not a multiple of replacement length")
if (N < length(o))
value <- rep(value, length.out=length(o))
value <- value[o]
i <- index
}
if(is.logical(i) && is.matrix(i) && all(dim(i) == dim(x))) {
nreplace <- sum(i, na.rm=TRUE)
if(!nreplace) return(x)
N <- length(value)
if(N > 1L && N < nreplace && (nreplace %% N) == 0L)
value <- rep(value, length.out = nreplace)
if(N > 1L && (length(value) != nreplace))
stop("'value' is the wrong length")
n <- 0L
nv <- nrow(x)
for(v in seq_len(dim(i)[2L])) {
thisvar <- i[, v, drop = TRUE]
nv <- sum(thisvar, na.rm = TRUE)
if(nv) {
if(is.matrix(x[[v]]))
x[[v]][thisvar, ] <- if(N > 1L) value[n+seq_len(nv)] else value
else
x[[v]][thisvar] <- if(N > 1L) value[n+seq_len(nv)] else value
}
n <- n+nv
}
return(x)
}
if(is.matrix(i))
stop("unsupported matrix index in replacement")
j <- i
i <- NULL
has.i <- FALSE
has.j <- TRUE
}
}
else
stop("need 0, 1, or 2 subscripts")
if ((has.j && !length(j)) ||
(has.i && !length(i) && !has.j))
return(x)
cl <- oldClass(x)
class(x) <- NULL
new.cols <- NULL
nvars <- length(x)
nrows <- .row_names_info(x, 2L)
if(has.i && length(i)) {
rows <- NULL
if(anyNA(i))
stop("missing values are not allowed in subscripted assignments of data frames")
if(char.i <- is.character(i)) {
rows <- attr(x, "row.names")
ii <- match(i, rows)
nextra <- sum(new.rows <- is.na(ii))
if(nextra > 0L) {
ii[new.rows] <- seq.int(from = nrows + 1L, length.out = nextra)
new.rows <- i[new.rows]
}
i <- ii
}
if(!is.logical(i) &&
(char.i && nextra || all(i >= 0L) && (nn <- max(i)) > nrows)) {
if(is.null(rows)) rows <- attr(x, "row.names")
if(!char.i) {
nrr <- (nrows + 1L):nn
if(inherits(value, "data.frame") &&
(dim(value)[1L]) >= length(nrr)) {
new.rows <- attr(value, "row.names")[seq_along(nrr)]
repl <- duplicated(new.rows) | match(new.rows, rows, 0L)
if(any(repl)) new.rows[repl] <- nrr[repl]
}
else new.rows <- nrr
}
x <- xpdrows.data.frame(x, rows, new.rows)
rows <- attr(x, "row.names")
nrows <- length(rows)
}
iseq <- seq_len(nrows)[i]
if(anyNA(iseq)) stop("non-existent rows not allowed")
}
else iseq <- NULL
if(has.j) {
if(anyNA(j))
stop("missing values are not allowed in subscripted assignments of data frames")
if(is.character(j)) {
if("" %in% j) stop("column name \"\" cannot match any column")
jseq <- match(j, names(x))
if(anyNA(jseq)) {
n <- is.na(jseq)
jseq[n] <- nvars + seq_len(sum(n))
new.cols <- j[n]
}
}
else if(is.logical(j) || min(j) < 0L)
jseq <- seq_along(x)[j]
else {
jseq <- j
if(max(jseq) > nvars) {
new.cols <- paste0("V",
seq.int(from = nvars + 1L, to = max(jseq)))
if(length(new.cols) != sum(jseq > nvars))
stop("new columns would leave holes after existing columns")
if(is.list(value) && !is.null(vnm <- names(value))) {
p <- length(jseq)
if(length(vnm) < p) vnm <- rep_len(vnm, p)
new.cols <- vnm[jseq > nvars]
}
}
}
}
else jseq <- seq_along(x)
if(has.i && !length(iseq) && all(1L <= jseq & jseq <= nvars))
return(`class<-`(x, cl))
if(anyDuplicated(jseq))
stop("duplicate subscripts for columns")
n <- length(iseq)
if(n == 0L) n <- nrows
p <- length(jseq)
if (is.null(value)) {
value <- list(NULL)
}
m <- length(value)
if(!is.list(value)) {
if(p == 1L) {
N <- NROW(value)
if(N > n)
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, n), domain = NA)
if(N < n && N > 0L)
if(n %% N == 0L && length(dim(value)) <= 1L)
value <- rep(value, length.out = n)
else
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
if (!is.null(names(value))) names(value) <- NULL
value <- list(value)
} else {
if(m < n*p && (m == 0L || (n*p) %% m))
stop(sprintf(ngettext(m,
"replacement has %d item, need %d",
"replacement has %d items, need %d"),
m, n*p), domain = NA)
value <- matrix(value, n, p)
value <- split(c(value), col(value))
}
dimv <- c(n, p)
} else {
value <- unclass(value)
lens <- vapply(value, NROW, 1L)
for(k in seq_along(lens)) {
N <- lens[k]
if(n != N && length(dim(value[[k]])) == 2L)
stop(sprintf(ngettext(N,
"replacement element %d is a matrix/data frame of %d row, need %d",
"replacement element %d is a matrix/data frame of %d rows, need %d"),
k, N, n),
domain = NA)
if(N > 0L && N < n && n %% N)
stop(sprintf(ngettext(N,
"replacement element %d has %d row, need %d",
"replacement element %d has %d rows, need %d"),
k, N, n), domain = NA)
if(N > 0L && N < n) value[[k]] <- rep(value[[k]], length.out = n)
if(N > n) {
warning(sprintf(ngettext(N,
"replacement element %d has %d row to replace %d rows",
"replacement element %d has %d rows to replace %d rows"),
k, N, n), domain = NA)
value[[k]] <- value[[k]][seq_len(n)]
}
}
dimv <- c(n, length(value))
}
nrowv <- dimv[1L]
if(nrowv < n && nrowv > 0L) {
if(n %% nrowv == 0L)
value <- value[rep_len(seq_len(nrowv), n),,drop = FALSE]
else
stop(sprintf(ngettext(nrowv,
"%d row in value to replace %d rows",
"%d rows in value to replace %d rows"),
nrowv, n), domain = NA)
}
else if(nrowv > n)
warning(sprintf(ngettext(nrowv,
"replacement data has %d row to replace %d rows",
"replacement data has %d rows to replace %d rows"),
nrowv, n), domain = NA)
ncolv <- dimv[2L]
jvseq <- seq_len(p)
if(ncolv < p) jvseq <- rep_len(seq_len(ncolv), p)
else if(p != 0L && ncolv > p) {
warning(sprintf(ngettext(ncolv,
"provided %d variable to replace %d variables",
"provided %d variables to replace %d variables"),
ncolv, p), domain = NA)
new.cols <- new.cols[seq_len(p)]
}
if(length(new.cols)) {
nm <- names(x)
rows <- .row_names_info(x, 0L)
a <- attributes(x); a["names"] <- NULL
x <- c(x, vector("list", length(new.cols)))
attributes(x) <- a
names(x) <- c(nm, new.cols)
attr(x, "row.names") <- rows
}
if(has.i)
for(jjj in seq_len(p)) {
jj <- jseq[jjj]
vjj <- value[[ jvseq[[jjj]] ]]
if(jj <= nvars) {
if(length(dim(x[[jj]])) != 2L)
x[[jj]][iseq ] <- vjj
else x[[jj]][iseq, ] <- vjj
} else {
x[[jj]] <- vjj[FALSE]
if(length(dim(vjj)) == 2L) {
length(x[[jj]]) <- nrows * ncol(vjj)
dim(x[[jj]]) <- c(nrows, ncol(vjj))
x[[jj]][iseq, ] <- vjj
} else {
length(x[[jj]]) <- nrows
x[[jj]][iseq] <- vjj
}
}
}
else if(p > 0L)
for(jjj in p:1L) {
o <- order(jseq)
jseq <- jseq[o]
jvseq <- jvseq[o]
jj <- jseq[jjj]
v <- value[[ jvseq[[jjj]] ]]
if (!is.null(v) && nrows > 0L && !length(v)) length(v) <- nrows
x[[jj]] <- v
if (!is.null(v) && is.atomic(x[[jj]]) && !is.null(names(x[[jj]])))
names(x[[jj]]) <- NULL
}
if(length(new.cols) > 0L) {
new.cols <- names(x)
if(anyDuplicated(new.cols)) names(x) <- make.unique(new.cols)
}
class(x) <- cl
x
}
`[[<-.data.frame` <- function(x, i, j, value)
{
if(!all(names(sys.call()) %in% c("", "value")))
warning("named arguments are discouraged")
cl <- oldClass(x)
class(x) <- NULL
nrows <- .row_names_info(x, 2L)
if(is.atomic(value) && !is.null(names(value))) names(value) <- NULL
if(nargs() < 4L) {
nc <- length(x)
if(!is.null(value)) {
N <- NROW(value)
if(N > nrows)
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
if(N < nrows)
if(N > 0L && (nrows %% N == 0L) && length(dim(value)) <= 1L)
value <- rep(value, length.out = nrows)
else
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
}
x[[i]] <- value
if(length(x) > nc) {
nc <- length(x)
if(names(x)[nc] == "") names(x)[nc] <- paste0("V", nc)
names(x) <- make.unique(names(x))
}
class(x) <- cl
return(x)
}
if(missing(i) || missing(j))
stop("only valid calls are x[[j]] <- value or x[[i,j]] <- value")
rows <- attr(x, "row.names")
nvars <- length(x)
if(n <- is.character(i)) {
ii <- match(i, rows)
n <- sum(new.rows <- is.na(ii))
if(n > 0L) {
ii[new.rows] <- seq.int(from = nrows + 1L, length.out = n)
new.rows <- i[new.rows]
}
i <- ii
}
if(all(i >= 0L) && (nn <- max(i)) > nrows) {
if(n == 0L) {
nrr <- (nrows + 1L):nn
if(inherits(value, "data.frame") &&
(dim(value)[1L]) >= length(nrr)) {
new.rows <- attr(value, "row.names")[seq_len(nrr)]
repl <- duplicated(new.rows) | match(new.rows, rows, 0L)
if(any(repl)) new.rows[repl] <- nrr[repl]
}
else new.rows <- nrr
}
x <- xpdrows.data.frame(x, rows, new.rows)
rows <- attr(x, "row.names")
nrows <- length(rows)
}
iseq <- seq_len(nrows)[i]
if(anyNA(iseq))
stop("non-existent rows not allowed")
if(is.character(j)) {
if("" %in% j) stop("column name \"\" cannot match any column")
jseq <- match(j, names(x))
if(anyNA(jseq))
stop(gettextf("replacing element in non-existent column: %s",
j[is.na(jseq)]), domain = NA)
}
else if(is.logical(j) || min(j) < 0L)
jseq <- seq_along(x)[j]
else {
jseq <- j
if(max(jseq) > nvars)
stop(gettextf("replacing element in non-existent column: %s",
jseq[jseq > nvars]), domain = NA)
}
if(length(iseq) > 1L || length(jseq) > 1L)
stop("only a single element should be replaced")
x[[jseq]][[iseq]] <- value
class(x) <- cl
x
}
`$<-.data.frame` <- function(x, name, value)
{
cl <- oldClass(x)
class(x) <- NULL
nrows <- .row_names_info(x, 2L)
if(!is.null(value)) {
N <- NROW(value)
if(N > nrows)
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
if (N < nrows)
if (N > 0L && (nrows %% N == 0L) && length(dim(value)) <= 1L)
value <- rep(value, length.out = nrows)
else
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
if(is.atomic(value) && !is.null(names(value))) names(value) <- NULL
}
x[[name]] <- value
class(x) <- cl
return(x)
}
xpdrows.data.frame <- function(x, old.rows, new.rows)
{
nc <- length(x)
nro <- length(old.rows)
nrn <- length(new.rows)
nr <- nro + nrn
for (i in seq_len(nc)) {
y <- x[[i]]
dy <- dim(y)
cy <- oldClass(y)
class(y) <- NULL
if (length(dy) == 2L) {
dny <- dimnames(y)
if (length(dny[[1L]]) > 0L)
dny[[1L]] <- c(dny[[1L]], new.rows)
z <- array(y[1L], dim = c(nr, nc), dimnames = dny)
z[seq_len(nro), ] <- y
class(z) <- cy
x[[i]] <- z
}
else {
ay <- attributes(y)
if (length(names(y)) > 0L)
ay$names <- c(ay$names, new.rows)
length(y) <- nr
attributes(y) <- ay
class(y) <- cy
x[[i]] <- y
}
}
nm <- c(old.rows, new.rows)
if (any(duplicated(nm))) nm <- make.unique(as.character(nm))
attr(x, "row.names") <- nm
x
}
cbind.data.frame <- function(..., deparse.level = 1)
data.frame(..., check.names = FALSE)
rbind.data.frame <- function(..., deparse.level = 1, make.row.names = TRUE,
stringsAsFactors = FALSE,
factor.exclude = TRUE)
{
match.names <- function(clabs, nmi)
{
if(identical(clabs, nmi)) NULL
else if(length(nmi) == length(clabs) && all(nmi %in% clabs)) {
m <- pmatch(nmi, clabs, 0L)
if(any(m == 0L))
stop("names do not match previous names")
m
} else stop("names do not match previous names")
}
allargs <- list(...)
allargs <- allargs[lengths(allargs) > 0L]
if(length(allargs)) {
nr <- vapply(allargs, function(x)
if(is.data.frame(x)) .row_names_info(x, 2L)
else if(is.list(x)) length(x[[1L]])
else length(x), 1L)
if(any(n0 <- nr == 0L)) {
if(all(n0)) return(allargs[[1L]])
allargs <- allargs[!n0]
}
}
n <- length(allargs)
if(n == 0L)
return(list2DF())
nms <- names(allargs)
if(is.null(nms))
nms <- character(n)
cl <- NULL
perm <- rows <- vector("list", n)
if(make.row.names) {
rlabs <- rows
autoRnms <- TRUE
Make.row.names <- function(nmi, ri, ni, nrow)
{
if(nzchar(nmi)) {
if(autoRnms) autoRnms <<- FALSE
if(ni == 0L) character()
else if(ni > 1L) paste(nmi, ri, sep = ".")
else nmi
}
else if(autoRnms && nrow > 0L && identical(ri, seq_len(ni)))
as.integer(seq.int(from = nrow + 1L, length.out = ni))
else {
if(autoRnms && (nrow > 0L || !identical(ri, seq_len(ni))))
autoRnms <<- FALSE
ri
}
}
}
smartX <- isTRUE(factor.exclude)
nrow <- 0L
value <- clabs <- NULL
all.levs <- list()
for(i in seq_len(n)) {
xi <- allargs[[i]]
nmi <- nms[i]
if(is.matrix(xi)) allargs[[i]] <- xi <-
as.data.frame(xi, stringsAsFactors = stringsAsFactors)
if(inherits(xi, "data.frame")) {
if(is.null(cl))
cl <- oldClass(xi)
ri <- attr(xi, "row.names")
ni <- length(ri)
if(is.null(clabs))
clabs <- names(xi)
else {
if(length(xi) != length(clabs))
stop("numbers of columns of arguments do not match")
pi <- match.names(clabs, names(xi))
if( !is.null(pi) ) perm[[i]] <- pi
}
rows[[i]] <- seq.int(from = nrow + 1L, length.out = ni)
if(make.row.names) rlabs[[i]] <- Make.row.names(nmi, ri, ni, nrow)
nrow <- nrow + ni
if(is.null(value)) {
value <- unclass(xi)
nvar <- length(value)
all.levs <- vector("list", nvar)
has.dim <- facCol <- ordCol <- logical(nvar)
if(smartX) NA.lev <- ordCol
for(j in seq_len(nvar)) {
xj <- value[[j]]
facCol[j] <- fac <-
if(!is.null(lj <- levels(xj))) {
all.levs[[j]] <- lj
TRUE
} else
is.factor(xj)
if(fac) {
ordCol[j] <- is.ordered(xj)
if(smartX && !NA.lev[j])
NA.lev[j] <- anyNA(lj)
}
has.dim[j] <- length(dim(xj)) == 2L
}
}
else for(j in seq_len(nvar)) {
xij <- xi[[j]]
if(is.null(pi) || is.na(jj <- pi[[j]])) jj <- j
if(facCol[jj]) {
if(length(lij <- levels(xij))) {
all.levs[[jj]] <- unique(c(all.levs[[jj]], lij))
if(ordCol[jj])
ordCol[jj] <- is.ordered(xij)
if(smartX && !NA.lev[jj])
NA.lev[jj] <- anyNA(lij)
} else if(is.character(xij))
all.levs[[jj]] <- unique(c(all.levs[[jj]], xij))
}
}
}
else if(is.list(xi)) {
ni <- range(lengths(xi))
if(ni[1L] == ni[2L])
ni <- ni[1L]
else stop("invalid list argument: all variables should have the same length")
ri <- seq_len(ni)
rows[[i]] <- seq.int(from = nrow + 1L, length.out = ni)
if(make.row.names) rlabs[[i]] <- Make.row.names(nmi, ri, ni, nrow)
nrow <- nrow + ni
if(length(nmi <- names(xi)) > 0L) {
if(is.null(clabs))
clabs <- nmi
else {
if(length(xi) != length(clabs))
stop("numbers of columns of arguments do not match")
pi <- match.names(clabs, nmi)
if( !is.null(pi) ) perm[[i]] <- pi
}
}
}
else if(length(xi)) {
rows[[i]] <- nrow <- nrow + 1L
if(make.row.names)
rlabs[[i]] <- if(nzchar(nmi)) nmi else as.integer(nrow)
}
}
nvar <- length(clabs)
if(nvar == 0L)
nvar <- max(lengths(allargs))
if(nvar == 0L)
return(list2DF())
pseq <- seq_len(nvar)
if(is.null(value)) {
value <- list()
value[pseq] <- list(logical(nrow))
all.levs <- vector("list", nvar)
has.dim <- facCol <- ordCol <- logical(nvar)
if(smartX) NA.lev <- ordCol
}
names(value) <- clabs
for(j in pseq)
if(length(lij <- all.levs[[j]]))
value[[j]] <-
factor(as.vector(value[[j]]), levels = lij,
exclude = if(smartX) {
if(!NA.lev[j]) NA
} else factor.exclude,
ordered = ordCol[j])
if(any(has.dim)) {
jdim <- pseq[has.dim]
if(!all(df <- vapply(jdim, function(j) inherits(value[[j]],"data.frame"), NA))) {
rmax <- max(unlist(rows))
for(j in jdim[!df]) {
dn <- dimnames(vj <- value[[j]])
rn <- dn[[1L]]
if(length(rn) > 0L) length(rn) <- rmax
pj <- dim(vj)[2L]
length(vj) <- rmax * pj
value[[j]] <- array(vj, c(rmax, pj), list(rn, dn[[2L]]))
}
}
}
for(i in seq_len(n)) {
xi <- unclass(allargs[[i]])
if(!is.list(xi))
if((ni <- length(xi)) != nvar) {
if(ni && nvar %% ni != 0)
warning(gettextf(
"number of columns of result, %d, is not a multiple of vector length %d of arg %d",
nvar, ni, i), domain = NA)
xi <- rep_len(xi, nvar)
}
ri <- rows[[i]]
pi <- perm[[i]]
if(is.null(pi)) pi <- pseq
for(j in pseq) {
jj <- pi[j]
xij <- xi[[j]]
if(has.dim[jj]) {
value[[jj]][ri, ] <- xij
if(!is.null(r <- rownames(xij)) &&
!(inherits(xij, "data.frame") &&
.row_names_info(xij) <= 0))
rownames(value[[jj]])[ri] <- r
} else {
value[[jj]][ri] <- if(is.factor(xij)) as.vector(xij) else xij
if(!is.null(nm <- names(xij))) names(value[[jj]])[ri] <- nm
}
}
}
rlabs <- if(make.row.names && !autoRnms) {
rlabs <- unlist(rlabs)
if(anyDuplicated(rlabs))
make.unique(as.character(rlabs), sep = "")
else
rlabs
}
if(is.null(cl)) {
as.data.frame(value, row.names = rlabs, fix.empty.names = TRUE,
stringsAsFactors = stringsAsFactors)
} else {
structure(value, class = cl,
row.names = if(is.null(rlabs)) .set_row_names(nrow) else rlabs)
}
}
print.data.frame <-
function(x, ..., digits = NULL, quote = FALSE, right = TRUE,
row.names = TRUE, max = NULL)
{
n <- length(row.names(x))
if(length(x) == 0L) {
cat(sprintf(ngettext(n, "data frame with 0 columns and %d row",
"data frame with 0 columns and %d rows"),
n), "\n", sep = "")
} else if(n == 0L) {
print.default(names(x), quote = FALSE)
cat(gettext("<0 rows> (or 0-length row.names)\n"))
} else {
if(is.null(max)) max <- getOption("max.print", 99999L)
if(!is.finite(max)) stop("invalid 'max' / getOption(\"max.print\"): ", max)
omit <- (n0 <- max %/% length(x)) < n
m <- as.matrix(
format.data.frame(if(omit) x[seq_len(n0), , drop=FALSE] else x,
digits = digits, na.encode = FALSE))
if(!isTRUE(row.names))
dimnames(m)[[1L]] <-
if(isFALSE(row.names)) rep.int("", if(omit) n0 else n)
else row.names
print(m, ..., quote = quote, right = right, max = max)
if(omit)
cat(" [ reached 'max' / getOption(\"max.print\") -- omitted",
n - n0, "rows ]\n")
}
invisible(x)
}
as.matrix.data.frame <- function (x, rownames.force = NA, ...)
{
dm <- dim(x)
rn <- if(rownames.force %in% FALSE) NULL
else if(rownames.force %in% TRUE || .row_names_info(x) > 0L)
row.names(x)
dn <- list(rn, names(x))
if(any(dm == 0L))
return(array(NA, dim = dm, dimnames = dn))
p <- dm[2L]
pseq <- seq_len(p)
n <- dm[1L]
X <- unclass(x)
non.numeric <- non.atomic <- FALSE
all.logical <- TRUE
for (j in pseq) {
xj <- X[[j]]
if(inherits(xj, "data.frame"))
X[[j]] <- xj <- as.matrix(xj)
j.logic <- is.logical(xj)
if(all.logical && !j.logic) all.logical <- FALSE
if(length(levels(xj)) > 0L || !(j.logic || is.numeric(xj) || is.complex(xj))
|| (!is.null(cl <- attr(xj, "class")) &&
any(cl %in% c("Date", "POSIXct", "POSIXlt"))))
non.numeric <- TRUE
if(!is.atomic(xj) && !inherits(xj, "POSIXlt"))
non.atomic <- TRUE
}
if(non.atomic) {
for (j in pseq) {
xj <- X[[j]]
if(!is.recursive(xj))
X[[j]] <- as.list(as.vector(xj))
}
} else if(all.logical) {
} else if(non.numeric) {
for (j in pseq) {
if (is.character(X[[j]]))
next
else if(is.logical(xj <- X[[j]]))
xj <- as.character(xj)
else {
miss <- is.na(xj)
xj <- if(length(levels(xj))) as.vector(xj) else format(xj)
is.na(xj) <- miss
}
X[[j]] <- xj
}
}
collabs <- as.list(dn[[2L]])
for (j in pseq) {
xj <- X[[j]]
dj <- dim(xj)
if(length(dj) == 2L && dj[2L] > 0L) {
if(!length(dnj <- colnames(xj))) dnj <- seq_len(dj[2L])
collabs[[j]] <-
if(length(collabs)) {
if(dj[2L] > 1L)
paste(collabs[[j]], dnj, sep = ".")
else if(is.character(collabs[[j]])) collabs[[j]]
else dnj
}
else dnj
}
}
nc <- vapply(X, NCOL, numeric(1), USE.NAMES=FALSE)
X <- unlist(X, recursive = FALSE, use.names = FALSE)
dim(X) <- c(n, length(X)/n)
dimnames(X) <- list(dn[[1L]], unlist(collabs[nc > 0], use.names = FALSE))
X
}
Math.data.frame <- function (x, ...)
{
mode.ok <- vapply(x, function(x)
is.numeric(x) || is.logical(x) || is.complex(x), NA)
if (all(mode.ok)) {
x[] <- lapply(X = x, FUN = .Generic, ...)
return(x)
} else {
vnames <- names(x)
if (is.null(vnames)) vnames <- seq_along(x)
stop("non-numeric-alike variable(s) in data frame: ",
paste(vnames[!mode.ok], collapse = ", "))
}
}
Ops.data.frame <- function(e1, e2 = NULL)
{
unary <- nargs() == 1L
lclass <- nzchar(.Method[1L])
rclass <- !unary && (nzchar(.Method[2L]))
value <- list()
rn <- NULL
FUN <- get(.Generic, envir = parent.frame(), mode = "function")
f <- if (unary) quote(FUN(left)) else quote(FUN(left, right))
lscalar <- rscalar <- FALSE
if(lclass && rclass) {
nr <- .row_names_info(e1, 2L)
if(.row_names_info(e1) > 0L) rn <- attr(e1, "row.names")
cn <- names(e1)
if(any(dim(e2) != dim(e1)))
stop(gettextf("%s only defined for equally-sized data frames",
sQuote(.Generic)), domain = NA)
} else if(lclass) {
nr <- .row_names_info(e1, 2L)
if(.row_names_info(e1) > 0L) rn <- attr(e1, "row.names")
cn <- names(e1)
rscalar <- length(e2) <= 1L
if(is.list(e2)) {
if(rscalar) e2 <- e2[[1L]]
else if(length(e2) != ncol(e1))
stop(gettextf("list of length %d not meaningful", length(e2)),
domain = NA)
} else {
if(!rscalar)
e2 <- split(rep_len(as.vector(e2), prod(dim(e1))),
rep.int(seq_len(ncol(e1)),
rep.int(nrow(e1), ncol(e1))))
}
} else {
nr <- .row_names_info(e2, 2L)
if(.row_names_info(e2) > 0L) rn <- attr(e2, "row.names")
cn <- names(e2)
lscalar <- length(e1) <= 1L
if(is.list(e1)) {
if(lscalar) e1 <- e1[[1L]]
else if(length(e1) != ncol(e2))
stop(gettextf("list of length %d not meaningful", length(e1)),
domain = NA)
} else {
if(!lscalar)
e1 <- split(rep_len(as.vector(e1), prod(dim(e2))),
rep.int(seq_len(ncol(e2)),
rep.int(nrow(e2), ncol(e2))))
}
}
for(j in seq_along(cn)) {
left <- if(!lscalar) e1[[j]] else e1
right <- if(!rscalar) e2[[j]] else e2
value[[j]] <- eval(f)
}
if(.Generic %in% c("+","-","*","^","%%","%/%","/")) {
if(length(value)) {
names(value) <- cn
data.frame(value, row.names = rn, check.names = FALSE)
} else
data.frame( row.names = rn, check.names = FALSE)
}
else {
value <- unlist(value, recursive = FALSE, use.names = FALSE)
if(!length(value))
matrix(logical(), nrow = nr, ncol = length(cn), dimnames = list(rn,cn))
else
matrix(value, nrow = nr, dimnames = list(rn,cn))
}
}
Summary.data.frame <- function(..., na.rm)
{
args <- list(...)
args <- lapply(args, function(x) {
x <- as.matrix(x)
if(!is.numeric(x) && !is.logical(x) && !is.complex(x))
stop("only defined on a data frame with all numeric-alike variables")
x
})
do.call(.Generic, c(args, na.rm=na.rm))
}
xtfrm.data.frame <- function(x) {
if(tolower(Sys.getenv("_R_STOP_ON_XTFRM_DATA_FRAME_")) %in%
c("1", "yes", "true"))
stop("cannot xtfrm data frames")
else {
warning("cannot xtfrm data frames")
NextMethod("xtfrm")
}
}
list2DF <-
function(x = list(), nrow = 0L)
{
stopifnot(is.list(x), is.null(nrow) || nrow >= 0L)
if(n <- length(x)) {
if(length(nrow <- unique(lengths(x))) > 1L)
stop("all variables should have the same length")
} else {
if(is.null(nrow))
nrow <- 0L
}
if(is.null(names(x)))
names(x) <- character(n)
class(x) <- "data.frame"
attr(x, "row.names") <- .set_row_names(nrow)
x
} |
`vol.m3` <-
function(dbh.cm, height.m, multiplier=0.5) {
vol.m3 <- pi * (dbh.cm/200)^2 * height.m * multiplier
} |
map_gist <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
UseMethod("map_gist")
}
map_gist.SpatialPoints <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...){
check4gistr()
dat <- SpatialPointsDataFrame(input, data.frame(dat = 1:NROW(input@coords)))
gistc(dat, file, description, public, browse, ...)
}
map_gist.SpatialPointsDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialPolygons <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialPolygonsDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialLines <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...){
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialLinesDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialGrid <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialGridDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialPixels <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialPixelsDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialRings <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.SpatialRingsDataFrame <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection",
file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.numeric <- function(input, lat = "lat", lon = "long", geometry = "point", group = NULL,
type = "FeatureCollection", file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
input <- as.geo_list(num_to_geo_list(input, geometry), "numeric")
gistc(input, file, description, public, browse, ...)
}
map_gist.data.frame <- function(input, lat = "lat", lon = "long", geometry = "point", group = NULL,
type = "FeatureCollection", file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
input <- as.geo_list(df_to_geo_list(input, lat, lon, geometry, type, group), "data.frame")
gistc(input, file, description, public, browse, ...)
}
map_gist.list <- function(input, lat = "lat", lon = "long", geometry = "point", group = NULL,
type = "FeatureCollection", file = "myfile.geojson", description = "",
public = TRUE, browse = TRUE, ...) {
check4gistr()
input <- as.geo_list(list_to_geo_list(input, lat, lon, geometry, type, group = group), "list")
gistc(input, file, description, public, browse, ...)
}
map_gist.location_ <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...) {
check4gistr()
gistr::gist_create(files = file[[1]], description = description, public = public, browse = browse, ...)
}
map_gist.json <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
map_gist.geo_list <- function(input, lat = "lat", lon = "long", geometry = "point",
group = NULL, type = "FeatureCollection", file = "myfile.geojson",
description = "", public = TRUE, browse = TRUE, ...) {
check4gistr()
gistc(input, file, description, public, browse, ...)
}
gistc <- function(input, file, description, public, browse, ...){
gistr::gist_create(files = geojson_write(input, file = file)$path,
description = description,
public = public,
browse = browse, ...)
}
check4gistr <- function() {
if (!requireNamespace("gistr", quietly = TRUE)) {
stop("Please install gistr", call. = FALSE)
}
} |
dsscden <-
function (object,y,x) {
if (!("sscden"%in%class(object))) stop("gss error in dsscden: not a sscden object")
if (!all(sort(object$xnames)==sort(colnames(x))))
stop("gss error in dsscden: mismatched x variable names")
if (length(object$ynames)==1&is.vector(y)) {
y <- data.frame(y,stringsAsFactors=TRUE)
colnames(y) <- object$ynames
}
if (!all(sort(object$ynames)==sort(colnames(y))))
stop("gss error in dsscden: mismatched y variable names")
if ("sscden1"%in%class(object)) {
qd.pt <- object$rho$env$qd.pt
qd.wt <- object$rho$env$qd.wt
d.qd <- d.sscden1(object,x,qd.pt,scale=FALSE)
int <- apply(d.qd*qd.wt,2,sum)
return(t(t(d.sscden1(object,x,y,scale=FALSE))/int))
}
else {
qd.pt <- object$yquad$pt
qd.wt <- object$yquad$wt
d.qd <- d.sscden(object,x,qd.pt)
int <- apply(d.qd*qd.wt,2,sum)
return(t(t(d.sscden(object,x,y))/int))
}
}
psscden <-
function(object,q,x) {
if (!("sscden"%in%class(object))) stop("gss error in psscden: not a sscden object")
if (length(object$ynames)!=1) stop("gss error in psscden: y is not 1-D")
if (("sscden1"%in%class(object))&!is.numeric(object$mf[,object$ynames]))
stop("gss error in qssden: y is not continuous")
if ("sscden1"%in%class(object)) ydomain <- object$rho$env$ydomain
else ydomain <- object$ydomain
mn <- min(ydomain[[object$ynames]])
mx <- max(ydomain[[object$ynames]])
order.q <- rank(q)
p <- q <- sort(q)
q.dup <- duplicated(q)
p[q<=mn] <- 0
p[q>=mx] <- 1
qd.hize <- 200
qd <- gauss.quad(2*qd.hize,c(mn,mx))
y.wk <- data.frame(qd$pt)
colnames(y.wk) <- object$ynames
d.qd <- dsscden(object,y.wk,x)
gap <- diff(qd$pt)
g.wk <- gap[qd.hize]/2
for (i in 1:(qd.hize-2)) g.wk <- c(g.wk,gap[qd.hize+i]-g.wk[i])
g.wk <- 2*g.wk
g.wk <- c(g.wk,(mx-mn)/2-sum(g.wk))
gap[qd.hize:1] <- gap[qd.hize+(1:qd.hize)] <- g.wk
brk <- cumsum(c(mn,gap))
kk <- (1:length(q))[q>mn&q<mx]
z <- NULL
for (k in 1:dim(x)[1]) {
d.qd.wk <- d.qd[,k]/sum(d.qd[,k]*qd$wt)
for (i in kk) {
if (q.dup[i]) {
p[i] <- p.dup
next
}
ind <- (1:(2*qd.hize))[qd$pt<q[i]]
if (!length(ind)) {
wk <- d.qd.wk[1]*qd$wt[1]*(q[i]-mn)/gap[1]
}
else {
wk <- sum(d.qd.wk[ind]*qd$wt[ind])
id.mx <- max(ind)
if (q[i]<brk[id.mx+1])
wk <- wk-d.qd.wk[id.mx]*qd$wt[id.mx]*(brk[id.mx+1]-q[i])/gap[id.mx]
else wk <- wk+d.qd.wk[id.mx+1]*qd$wt[id.mx+1]*(q[i]-brk[id.mx+1])/gap[id.mx+1]
}
p[i] <- p.dup <- wk
}
z <- cbind(z,p[order.q])
}
z
}
qsscden <-
function(object,p,x) {
if (!("sscden"%in%class(object))) stop("gss error in qsscden: not a sscden object")
if (length(object$ynames)!=1) stop("gss error in qsscden: y is not 1-D")
if (("sscden1"%in%class(object))&!is.numeric(object$mf[,object$ynames]))
stop("gss error in qssden: y is not continuous")
if ("sscden1"%in%class(object)) ydomain <- object$rho$env$ydomain
else ydomain <- object$ydomain
mn <- min(ydomain[[object$ynames]])
mx <- max(ydomain[[object$ynames]])
order.p <- rank(p)
q <- p <- sort(p)
p.dup <- duplicated(p)
q[p<=0] <- mn
q[p>=1] <- mx
qd.hize <- 200
qd <- gauss.quad(2*qd.hize,c(mn,mx))
y.wk <- data.frame(qd$pt)
colnames(y.wk) <- object$ynames
d.qd <- dsscden(object,y.wk,x)
gap <- diff(qd$pt)
g.wk <- gap[qd.hize]/2
for (i in 1:(qd.hize-2)) g.wk <- c(g.wk,gap[qd.hize+i]-g.wk[i])
g.wk <- 2*g.wk
g.wk <- c(g.wk,(mx-mn)/2-sum(g.wk))
gap[qd.hize:1] <- gap[qd.hize+(1:qd.hize)] <- g.wk
brk <- cumsum(c(mn,gap))
kk <- (1:length(p))[p>0&p<1]
z <- NULL
for (k in 1:dim(x)[1]) {
d.qd.wk <- d.qd[,k]/sum(d.qd[,k]*qd$wt)
p.wk <- cumsum(d.qd.wk*qd$wt)
for (i in kk) {
if (p.dup[i]) {
q[i] <- q.dup
next
}
ind <- (1:(2*qd.hize))[p.wk<p[i]]
if (!length(ind)) {
wk <- mn+p[i]/(d.qd.wk[1]*qd$wt[1])*gap[1]
}
else {
id.mx <- max(ind)
wk <- brk[id.mx+1]+(p[i]-p.wk[id.mx])/(d.qd.wk[id.mx+1]*qd$wt[id.mx+1])*gap[id.mx+1]
}
q[i] <- q.dup <- wk
}
z <- cbind(z,q[order.p])
}
z
}
d.sscden <-
function (object,x,y) {
if ("sscden"!=class(object)) stop("gss error in d.sscden: not a sscden object")
if (!all(sort(object$xnames)==sort(colnames(x))))
stop("gss error in d.sscden: mismatched x variable names")
if (!all(sort(object$ynames)==sort(colnames(y))))
stop("gss error in d.sscden: mismatched y variable names")
mf <- object$mf
z <- NULL
for (k in 1:dim(x)[1]) {
xy.new <- cbind(x[rep(k,dim(y)[1]),,drop=FALSE],y)
s <- NULL
r <- 0
nu <- nq <- 0
for (label in object$terms$labels) {
vlist <- object$terms[[label]]$vlist
xy <- xy.new[,vlist]
xy.basis <- mf[object$id.basis,vlist]
nphi <- object$terms[[label]]$nphi
nrk <- object$terms[[label]]$nrk
if (nphi) {
phi <- object$terms[[label]]$phi
for (i in 1:nphi) {
nu <- nu + 1
s.wk <- phi$fun(xy,nu=i,env=phi$env)
s <- cbind(s,s.wk)
}
}
if (nrk) {
rk <- object$terms[[label]]$rk
for (i in 1:nrk) {
nq <- nq+1
r.wk <- rk$fun(xy,xy.basis,nu=i,env=rk$env,out=TRUE)
r <- r + 10^object$theta[nq]*r.wk
}
}
}
eta <- exp(cbind(s,r)%*%c(object$d,object$c))
z <- cbind(z,eta)
}
z
}
d.sscden1 <-
function (object,x,y,scale=TRUE) {
if (!("sscden1"%in%class(object))) stop("gss error in d.sscden1: not a sscden1 object")
if (!all(sort(object$xnames)==sort(colnames(x))))
stop("gss error in d.sscden1: mismatched x variable names")
if (!all(sort(object$ynames)==sort(colnames(y))))
stop("gss error in d.sscden1: mismatched y variable names")
mf <- object$mf
rho <- object$rho$fun(x,y,object$rho$env,outer=TRUE)
z <- NULL
for (k in 1:dim(x)[1]) {
xy.new <- cbind(x[rep(k,dim(y)[1]),,drop=FALSE],y)
s <- NULL
r <- 0
nu <- nq <- 0
for (label in object$terms$labels) {
vlist <- object$terms[[label]]$vlist
xy <- xy.new[,vlist]
xy.basis <- mf[object$id.basis,vlist]
nphi <- object$terms[[label]]$nphi
nrk <- object$terms[[label]]$nrk
if (nphi) {
phi <- object$terms[[label]]$phi
for (i in 1:nphi) {
nu <- nu + 1
if (!scale&!(nu%in%object$id.s)) next
s.wk <- phi$fun(xy,nu=i,env=phi$env)
s <- cbind(s,s.wk)
}
}
if (nrk) {
rk <- object$terms[[label]]$rk
for (i in 1:nrk) {
nq <- nq+1
if (!scale&!(nq%in%object$id.r)) next
r.wk <- rk$fun(xy,xy.basis,nu=i,env=rk$env,out=TRUE)
r <- r + 10^object$theta[nq]*r.wk
}
}
}
if (!scale) eta <- exp(cbind(s,r)%*%c(object$d[object$id.s],object$c))
else eta <- exp(cbind(s,r)%*%c(object$d,object$c))*object$scal
z <- cbind(z,eta*rho[k,])
}
z
} |
rank_mat <- function( x ) {
if ( class(x)[1]=="numeric" ) x <- array( x , dim=c(length(x),1) )
matrix( rank(x) , ncol=ncol(x) )
}
trankplot <- function( object , bins=30 , pars , chains , col=rethink_palette , alpha=1 , bg=col.alpha("black",0.15) , ask=TRUE , window , n_cols=3 , max_rows=5 , lwd=1.5 , lp=FALSE , axes=FALSE , off=0 , add=FALSE , stacked=FALSE , ... ) {
if ( !(class(object)[1] %in% c("map2stan","ulam","stanfit")) ) stop( "requires map2stan, ulam or stanfit object" )
if ( class(object)[1] %in% c("map2stan","ulam") ) {
object <- object@stanfit
}
if ( missing(pars) )
post <- extract(object,permuted=FALSE,inc_warmup=FALSE)
else
post <- extract(object,pars=pars,permuted=FALSE,inc_warmup=FALSE)
dimnames <- attr(post,"dimnames")
n_chains <- length(dimnames$chains)
if ( n_chains==1 ) stop( "trankplot requires more than one chain." )
if ( missing(chains) ) chains <- 1:n_chains
n_chains <- length(chains)
pars <- dimnames$parameters
chain.cols <- rep_len(col,n_chains)
wdev <- which(pars=="dev")
if ( length(wdev)>0 ) pars <- pars[-wdev]
wlp <- which(pars=="lp__")
if ( length(wlp)>0 & lp==FALSE ) pars <- pars[-wlp]
wlp <- grep( "log_lik" , pars , fixed=TRUE )
if ( length(wlp)>0 ) pars <- pars[-wlp]
n_pars <- length( pars )
ranks <- post
n_samples <- dim(post)[1]
for ( i in 1:n_pars ) {
ranks[,,i] <- rank_mat( post[,, pars[i] ] )
}
breaks <- hist( ranks[,,1] , breaks=bins , plot=FALSE )$breaks
h <- array( NA , dim=c( length(breaks)-1 , n_chains , n_pars ) )
for ( i in 1:n_pars ) {
for ( j in 1:n_chains ) {
h[,j,i] <- hist( ranks[,j,i] , breaks=breaks , plot=FALSE )$counts
}
}
n_rows=ceiling(n_pars/n_cols)
n_rows_per_page <- n_rows
paging <- FALSE
n_pages <- 1
if ( n_rows_per_page > max_rows ) {
n_rows_per_page <- max_rows
n_pages <- ceiling(n_pars/(n_cols*n_rows_per_page))
paging <- TRUE
}
n_iter <- object@sim$iter
n_warm <- object@sim$warmup
wstart <- 0
wend <- max(breaks)
if ( missing(window) ) window <- c(1,n_samples)
if ( !missing(window) ) {
wstart <- window[1]
wend <- window[2]
}
plot_make <- function( main , par , neff , ... ) {
ylim <- range(h[,,par])
if ( stacked==TRUE ) ylim[2] <- ylim[2] * ( length(chains) - 1 )
if ( axes==TRUE )
plot( NULL , xlab="" , ylab="" , bty="l" , xlim=range(breaks) , ylim=ylim , ... )
else
plot( NULL , xlab="" , ylab="" , bty="l" , xlim=range(breaks) , ylim=ylim , xaxt="n" , yaxt="n" , ... )
neff_use <- neff[ names(neff)==main ]
mtext( paste("n_eff =",round(neff_use,0)) , 3 , adj=1 , cex=0.9 )
if ( main=="lp__" ) main <- "log-probability"
mtext( main , 3 , adj=0 , cex=1 )
}
nb <- length(breaks)
plot_trank <- function( r , ... ) {
if ( stacked==FALSE ) {
for ( i in chains ) {
x <- c( breaks[1] , rep( breaks[2:(nb-1)] , each=2 ) , breaks[nb] )
y <- rep( r[ 1:(nb-1) ,i] , each=2 )
lines( x + (i-1)*off , y , col=col.alpha(chain.cols[i],alpha) , lwd=lwd )
}
} else {
ysum <- 0
for ( i in chains ) {
x <- c( breaks[1] , rep( breaks[2:(nb-1)] , each=2 ) , breaks[nb] )
y <- rep( r[ 1:(nb-1) ,i] , each=2 )
ysum <- y + ysum
print(str(ysum))
lines( x + (i-1)*off , ysum , col=col.alpha(chain.cols[i],alpha) , lwd=lwd )
}
}
}
n_eff <- summary(object)$summary[ , 'n_eff' ]
if ( add==FALSE ) {
par(mgp = c(0.5, 0.5, 0), mar = c(1.5, 1.5, 1.5, 1) + 0.1, tck = -0.02)
par(mfrow=c(n_rows_per_page,n_cols))
}
n_ppp <- n_rows_per_page * n_cols
for ( k in 1:n_pages ) {
if ( k > 1 ) message( paste("Waiting to draw page",k,"of",n_pages) )
for ( i in 1:n_ppp ) {
pi <- i + (k-1)*n_ppp
if ( pi <= n_pars ) {
if ( pi == 2 ) {
if ( ask==TRUE & add==FALSE ) {
ask_old <- devAskNewPage(ask = TRUE)
on.exit(devAskNewPage(ask = ask_old), add = TRUE)
}
}
plot_make( pars[pi] , pi , n_eff , ... )
plot_trank( h[ , , pi ] , ... )
}
}
}
} |
path_package <- function(package, ...) {
if (!is.character(package) || length(package) != 1L) {
stop(fs_error(sprintf("`package` must be a character vector of length 1")))
}
pkg_path <-
tryCatch(
find.package(package, quiet = FALSE),
error = function(error) {
is_not_found_error <- grepl(
gettextf("there is no package called %s", sQuote(package)),
conditionMessage(error), fixed = TRUE)
if (!is_not_found_error) {
stop(error)
}
msg <- sprintf(
"Can't find package `%s` in library locations:
%s",
package,
paste0(" - '", path_tidy(.libPaths()), "'", collapse = "\n"))
stop(fs_error(msg, class = "EEXIST"))
})
files_inst <- path(pkg_path, "inst", ...)
present_inst <- file_exists(files_inst)
files_top <- path(pkg_path, ...)
present_top <- file_exists(files_top)
files <- files_top
files[present_inst] <- files_inst[present_inst]
files <- files[present_inst | present_top]
if (length(files) == 0) {
msg <- sprintf(
"File(s) %s do not exist",
paste0("'", files_top, "'", collapse = ", ")
)
stop(fs_error(msg, class = "EEXIST"))
}
files
} |
whichlevel <-
function (J, filter.number = 10, family = "DaubLeAsymm")
{
BigJ <- J + 1
KeepGoing <- T
while (KeepGoing) {
n <- 2^BigJ
tmpwd <- wd(rep(0, n), filter.number = filter.number,
family = family)
ixvec <- cumsum(2^((BigJ - 1):0))
somefull <- F
for (i in 1:J) {
tmpwd$D <- rep(0, n - 1)
tmpwd$D[ixvec[i]] <- 1
vec <- wr(tmpwd)
somefull <- somefull | all(vec != 0)
if (somefull)
break
}
if (!somefull)
KeepGoing <- F
else BigJ <- BigJ + 1
}
BigJ
} |
extractCTDTClass <- function(x, aagroup1, aagroup2, aagroup3) {
if (protcheck(x) == FALSE) {
stop("x has unrecognized amino acid type")
}
if ((length(aagroup1) != length(aagroup2) |
length(aagroup1) != length(aagroup3)) |
(length(aagroup2) != length(aagroup3))) {
stop("The three groups must have the same property numbers")
}
xSplitted <- strsplit(x, split = "")[[1]]
n <- nchar(x)
propnum <- length(aagroup1)
G <- vector("list", propnum)
for (i in 1L:propnum) G[[i]] <- rep(NA, n)
for (i in 1L:propnum) {
try(G[[i]][which(xSplitted %in% aagroup1[[i]])] <- "G1")
try(G[[i]][which(xSplitted %in% aagroup2[[i]])] <- "G2")
try(G[[i]][which(xSplitted %in% aagroup3[[i]])] <- "G3")
}
for (i in 1L:propnum) G[[i]] <- paste(G[[i]][-n], G[[i]][-1], sep = "")
G <- lapply(G, as.factor)
GSummary <- lapply(G, summary)
CTDT <- vector("list", propnum)
for (i in 1L:propnum) {
CTDT[[i]][1] <- sum(GSummary[[i]][c("G1G2", "G2G1")]) / (n - 1)
CTDT[[i]][2] <- sum(GSummary[[i]][c("G1G3", "G3G1")]) / (n - 1)
CTDT[[i]][3] <- sum(GSummary[[i]][c("G2G3", "G3G2")]) / (n - 1)
}
CTDT <- unlist(CTDT)
names(CTDT) <- paste(
"prop", rep(1L:propnum, each = 3L), ".",
rep(c("Tr1221", "Tr1331", "Tr2332"), times = propnum),
sep = ""
)
CTDT
} |
get_loonWidgetsInfo.l_graph <- function(widgets, loon.grobs, ...) {
args <- list(...)
navbarMenuName <- args$navbarMenuName
loon.grob <- loon.grobs
nodes_grob <- grid::getGrob(loon.grob, "graph nodes")
nodes_children <- nodes_grob$children
x <- y <- size <- pch <- index <- c()
N <- length(nodes_children)
lapply(1:N,
function(i){
node_layer <- nodes_children[[i]]
if(is(node_layer, "null")) {
x[i] <<- NA
y[i] <<- NA
pch[i] <<- ""
size[i] <<- NA
} else {
x[i] <<- node_layer$x
y[i] <<- node_layer$y
pch[i] <<- node_layer$pch
size[i] <<- node_layer$gp$fontsize
}
index[i] <<- as.numeric(gsub("\\D", "", node_layer$name))
}
)
glyph <- pch_to_glyph(pch)
xyOriginal <- list()
newGrob <- grid::getGrob(loon.grob, "graph nodes")
graph_edges <- grid::getGrob(loon.grob, "graph edges")
lapply(1:length(newGrob$children),
function(i) {
xyOriginal[[i]] <<- list(
x = newGrob$children[[i]]$x,
y = newGrob$children[[i]]$y
)
}
)
swapAxes <- widgets['swapAxes']
viewPort <- get_viewPort(loon.grob)
dataViewport <- get_vp_from_vpStack(viewPort, "dataViewport")
xlim <- dataViewport$xscale
ylim <- dataViewport$yscale
if(swapAxes) {
ylabel <- widgets['xlabel']
xlabel <- widgets['ylabel']
} else {
xlabel <- widgets['xlabel']
ylabel <- widgets['ylabel']
}
xNoNA <- na.omit(x)
plotViewXlim <- if(length(xNoNA) == 0) {
c(-0.05, 0.05)
} else if(length(xNoNA) == 1) {
xNoNA + c(-0.05, 0.05)
} else {
grDevices::extendrange(xNoNA)
}
yNoNA <- na.omit(y)
plotViewYlim <- if(length(yNoNA) == 0) {
c(-0.05, 0.05)
} else if(length(yNoNA) == 1) {
yNoNA + c(-0.05, 0.05)
} else {
grDevices::extendrange(yNoNA)
}
worldView <- get_worldViewPort(loon.grob = loon.grob,
parentExcluded = TRUE,
recursive = TRUE)
worldViewXlim <- range(c(plotViewXlim, worldView$xlim))
worldViewYlim <- range(c(plotViewYlim, worldView$ylim))
layers <- get_layers(loon.grob, recursive = FALSE)
names(layers) <- layers
list(
itemLabel = widgets['itemLabel'],
showItemLabels = widgets['showItemLabels'],
swapInShiny = swapAxes,
swapInLoon = swapAxes,
showLabels = widgets['showLabels'],
showScales = widgets['showScales'],
showGuides = widgets['showGuides'],
showOrbit = widgets['showOrbit'],
linkingGroup = widgets['linkingGroup'],
linkingKey = widgets['linkingKey'],
loonDefaultMargins = list(
minimumMargins = pixels_2_lines(widgets['minimumMargins']),
labelMargins = pixels_2_lines(widgets['labelMargins']),
scalesMargins = pixels_2_lines(widgets['scalesMargins'])
),
labels = list(
xlabel = xlabel,
ylabel = ylabel,
title = if(is.null(args$title)) widgets['title'] else args$title
),
color = loon::hex12tohex6(widgets['color']),
active = widgets['active'],
selected = widgets['selected'],
selectByLoon = widgets['selectBy'],
xlabel = xlabel,
ylabel = ylabel,
title = widgets['title'],
N = N,
linkingStates = loon::l_getLinkedStates(widgets),
x = x,
y = y,
xlim = xlim,
ylim = ylim,
stepX = log_ceiling(diff(xlim)),
stepY = log_ceiling(diff(ylim)),
xOriginal = x,
yOriginal = y,
pch = pch,
glyph = glyph,
size = size,
index = index,
xyOriginal = xyOriginal,
graph_edges = graph_edges,
plotViewXlim = plotViewXlim,
plotViewYlim = plotViewYlim,
worldViewXlim = worldViewXlim,
worldViewYlim = worldViewYlim,
navbarMenuName = navbarMenuName,
layers = layers,
lastSelection = integer(0),
loonColor = list(
background_color = loon::hex12tohex6(widgets["background"]),
foreground_color = loon::hex12tohex6(widgets["foreground"]),
guidesbackground_color = loon::hex12tohex6(widgets["guidesBackground"]),
guideslines_color = loon::hex12tohex6(widgets["guidelines"])
),
alpha = rep(1, N)
)
} |
context("lgb.plot.importance()")
test_that("lgb.plot.importance() should run without error for well-formed inputs", {
data(agaricus.train, package = "lightgbm")
train <- agaricus.train
dtrain <- lgb.Dataset(train$data, label = train$label)
params <- list(
objective = "binary"
, learning_rate = 0.01
, num_leaves = 63L
, max_depth = -1L
, min_data_in_leaf = 1L
, min_sum_hessian_in_leaf = 1.0
)
model <- lgb.train(params, dtrain, 3L)
tree_imp <- lgb.importance(model, percentage = TRUE)
expect_null(dev.list())
args_no_cex <- list(
"tree_imp" = tree_imp
, top_n = 10L
, measure = "Gain"
)
args_cex <- args_no_cex
args_cex[["cex"]] <- 0.75
for (arg_list in list(args_no_cex, args_cex)) {
resDT <- do.call(
what = lgb.plot.importance
, args = arg_list
)
expect_true(data.table::is.data.table(resDT))
expect_named(resDT, c("Feature", "Gain", "Cover", "Frequency"))
expect_false(is.null(dev.list()))
dev.off()
expect_null(dev.list())
}
}) |
NULL
brickFromOutputSoil3DTensor <- function(x,when,layers="SoilLayerThicknesses",one.layer=FALSE,suffix="L%04dN%04d.asc",time_formatter="N%04d",suffix_one.layer="N%04d.asc",wpath=NULL,tz="A",start_date_key="InitDateDDMMYYYYhhmm",end_date_key="EndDateDDMMYYYYhhmm",timestep="OutputSoilMaps",use.read.raster.from.url=FALSE,crs=NULL,projfile="geotop.proj",start.from.zero=FALSE,secondary.suffix=NULL,only.map.filename=FALSE,...) {
out <- NULL
if (is.null(crs)) {
cond <- (!is.null(wpath)) | is.null(projfile) | is.na(projfile)
if (cond) {
projfile <- paste(wpath,projfile,sep="/")
cond <- file.exists(projfile)
crs <- getProjection(projfile,cond=cond)
}
}
start_s <- geotopbricks::get.geotop.inpts.keyword.value(start_date_key,date=TRUE,wpath=wpath,tz=tz,...)
end_s <- geotopbricks::get.geotop.inpts.keyword.value(end_date_key,date=TRUE,wpath=wpath,tz=tz,...)
if (!is.numeric(timestep)) timestep <- geotopbricks::get.geotop.inpts.keyword.value(timestep,wpath=wpath,numeric=TRUE,...)*3600
time <- seq(from=start_s,to=end_s,by=timestep)
if (is.numeric(layers)) {
if ((length(layers)==1) & (layers[1]>1)) layers <- 1:layers
if ((length(layers)==1) & (layers[1]=1)) one.layer <- TRUE
} else {
if (layers=="SoilLayerThicknesses") {
layers <- geotopbricks::get.geotop.inpts.keyword.value("SoilLayerThicknesses",numeric=TRUE,wpath=wpath,...)
if (is.null(layers)) {
layers <- "SoilParFile"
} else {
}
}
if (layers[1]=="SoilParFile") {
headerDz <- geotopbricks::get.geotop.inpts.keyword.value("HeaderSoilDz",wpath=wpath,...)[1]
if (is.null(headerDz)) headerDz <- "Dz"
layers <- geotopbricks::get.geotop.inpts.keyword.value("SoilParFile",wpath=wpath,add_wpath=TRUE,data.frame=TRUE,level=1,date_field=NULL,...)[,headerDz]
}
if (!is.numeric(layers) | (length(layers)==1)) {
nl <- geotopbricks::get.geotop.inpts.keyword.value("SoilLayerNumber",numeric=TRUE,wpath=wpath,...)[1]
if (!is.null(nl)) layers <- 1:nl
}
if (!is.numeric(layers)) {
warning("Layers Not Numeric 1:2 by Defalut!")
layers <- 1:2
}
}
map.prefix <- geotopbricks::get.geotop.inpts.keyword.value(x,numeric=FALSE,date=FALSE,wpath=wpath,add_wpath=TRUE,...)
if (!is.null(secondary.suffix)) {
map.prefix <- paste(map.prefix,secondary.suffix,sep="")
}
print(paste("Maps to import:",length(when),"from",as.character(when[1]),"to",as.character(when[length(when)]),sep=" "))
message("Important bug solved from 1.3.7.3, previous versions (<= 1.3.7.2) could return slightly different results!")
time <- time[-1]
out <- lapply(X=when,FUN=function(whenx,map.prefix,suffix,crs,layers,start.from.zero,one.layer,time,timestep) {
message(paste("Importing",as.character(whenx),sep=" "))
t_index <- abs(as.numeric((whenx-time),units="secs"))<timestep
index <- 1
n <- which(t_index)[index]
if (length(n)>0) {
n <- n[1]
}
if (!is.na(n)) {
time_formatter_n <- sprintf(time_formatter,n)
if (one.layer) {
suffix <- str_replace(suffix_one.layer,time_formatter,time_formatter_n)
} else {
suffix <- str_replace(suffix,time_formatter,time_formatter_n)
}
map.filename <- paste(map.prefix,suffix,sep="")
message(paste("As ",as.character(time[n]),sep=" "))
if (only.map.filename==TRUE) {
out <- map.filename
} else if (one.layer) {
if (use.read.raster.from.url) {
out <- read.raster.from.url(x=map.filename)
} else {
out <- raster(map.filename)
}
if (!is.null(crs)) {
projection(out) <- crs
}
} else {
out <- brick.decimal.formatter(map.filename,nlayers=length(layers),use.read.raster.from.url=use.read.raster.from.url,start.from.zero=start.from.zero,crs=crs)
if (start.from.zero) {
names(out) <- paste("L",0:length(layers),sep="")
} else {
names(out) <- paste("L",1:length(layers),sep="")
}
names(out)[1:length(layers)] <- paste(names(out)[1:length(layers)],layers,sep="_")
}
} else {
out <- NULL
}
return(out)
},map.prefix=map.prefix,suffix=suffix,crs=crs,layers=layers,start.from.zero=start.from.zero,one.layer=one.layer,time=time,timestep=timestep)
names(out) <- strftime(when,tz=tz,format="DATE-TIME %Y-%m-%d %H:%M")
if (length(out)==1) out <- out[[1]]
return(out)
}
NULL
rasterFromOutput2DMap <- function(x,when,...) {
out <- geotopbricks::brickFromOutputSoil3DTensor(x=x,when=when,layers=1,one.layer=TRUE,...)
return(out)
} |
context("recode, replace")
gmtc <- fgroup_by(mtcars, cyl)
test_that("replace_NA and replace_Inf work well", {
expect_equal(replace_NA(airquality, 0), `[<-`(airquality, is.na(airquality), value = 0))
expect_equal(replace_NA(airquality, 0, cols = 1:2), `[<-`(airquality, is.na(airquality), value = 0))
expect_equal(replace_NA(airquality, 0, cols = is.numeric), `[<-`(airquality, is.na(airquality), value = 0))
expect_equal(replace_NA(flag(EuStockMarkets), 0), `[<-`(flag(EuStockMarkets), is.na(flag(EuStockMarkets)), value = 0))
expect_equal(replace_Inf(dapply(mtcars, log)), `[<-`(dapply(mtcars, log), sapply(dapply(mtcars, log), is.infinite), value = NA))
expect_equal(replace_Inf(log(EuStockMarkets)), `[<-`(log(EuStockMarkets), is.infinite(log(EuStockMarkets)), value = NA))
expect_equal(replace_Inf(dapply(mtcars, log), replace.nan = TRUE), `[<-`(dapply(mtcars, log), sapply(dapply(mtcars, log), is.infinite), value = NA))
expect_equal(replace_Inf(log(EuStockMarkets), replace.nan = TRUE), `[<-`(log(EuStockMarkets), is.infinite(log(EuStockMarkets)), value = NA))
})
test_that("replace_outliers works well.", {
expect_equal(replace_outliers(mtcars, 2), replace(mtcars, fscale(mtcars) > 2, NA))
expect_equal(replace_outliers(gmtc, 2, single.limit = "overall_SDs"), replace(gmtc, dapply(mtcars, fscale) > 2, NA))
expect_equal(replace_outliers(mtcars, 2, single.limit = "min"), replace(mtcars, mtcars < 2, NA))
expect_equal(replace_outliers(mtcars, 2, single.limit = "max"), replace(mtcars, mtcars > 2, NA))
expect_equal(replace_outliers(EuStockMarkets, 2), replace(EuStockMarkets, fscale(EuStockMarkets) > 2, NA))
expect_equal(replace_outliers(EuStockMarkets, 2, single.limit = "overall_SDs"), replace(EuStockMarkets, dapply(EuStockMarkets, fscale) > 2, NA))
expect_equal(replace_outliers(EuStockMarkets, 2, single.limit = "min"), replace(EuStockMarkets, EuStockMarkets < 2, NA))
expect_equal(replace_outliers(EuStockMarkets, 2, single.limit = "max"), replace(EuStockMarkets, EuStockMarkets > 2, NA))
})
set.seed(101)
lmiss <- na_insert(letters)
month.miss <- na_insert(month.name)
char_dat <- na_insert(char_vars(GGDC10S))
options(warn = -1)
test_that("recode_char works well", {
expect_equal(recode_char(lmiss, a = "b"), replace(lmiss, lmiss == "a", "b"))
expect_visible(recode_char(lmiss, a = "b", missing = "a"))
expect_visible(recode_char(lmiss, a = "b", missing = "c"))
expect_visible(recode_char(lmiss, a = "b", default = "n"))
expect_visible(recode_char(lmiss, a = "b", default = "n", missing = "c"))
expect_visible(recode_char(month.miss, ber = NA, regex = TRUE))
expect_visible(recode_char(month.miss, ber = NA, missing = "c", regex = TRUE))
expect_visible(recode_char(lmiss, ber = NA, default = "n", regex = TRUE))
expect_visible(recode_char(lmiss, ber = NA, default = "n", missing = "c", regex = TRUE))
expect_visible(recode_char(lmiss, a = "b", e = "f"))
expect_visible(recode_char(lmiss, a = "b", e = "f", missing = "a"))
expect_visible(recode_char(lmiss, a = "b", e = "f", missing = "c"))
expect_visible(recode_char(lmiss, a = "b", e = "f", default = "n"))
expect_visible(recode_char(lmiss, a = "b", e = "f", default = "n", missing = "c"))
expect_visible(recode_char(month.miss, ber = NA, May = "a", regex = TRUE))
expect_visible(recode_char(month.miss, ber = NA, May = "a", missing = "c", regex = TRUE))
expect_visible(recode_char(lmiss, ber = NA, May = "a", default = "n", regex = TRUE))
expect_visible(recode_char(lmiss, ber = NA, May = "a", default = "n", missing = "c", regex = TRUE))
expect_visible(recode_char(char_dat, SGP = "SINGAPORE", VA = "Value Added"))
expect_visible(recode_char(char_dat, SGP = "SINGAPORE", VA = "Value Added", missing = "c"))
expect_visible(recode_char(char_dat, SGP = "SINGAPORE", VA = "Value Added", default = "n"))
expect_visible(recode_char(char_dat, SGP = "SINGAPORE", VA = "Value Added", default = "n", missing = "c"))
expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE))
expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE, missing = "c"))
expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE, default = "n"))
expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE, default = "n", missing = "c"))
})
set.seed(101)
vmiss <- na_insert(mtcars$cyl)
mtcNA <- na_insert(mtcars)
test_that("recode_num works well", {
expect_equal(recode_num(vmiss, `4` = 5), replace(vmiss, vmiss == 4, 5))
expect_visible(recode_num(vmiss, `4` = 5, missing = 4))
expect_visible(recode_num(vmiss, `4` = 5, missing = 7))
expect_visible(recode_num(vmiss, `4` = 5, default = 8))
expect_visible(recode_num(vmiss, `4` = 5, default = 8, missing = 7))
expect_visible(recode_num(vmiss, `4` = 5, `6` = 10))
expect_visible(recode_num(vmiss, `4` = 5, `6` = 10, missing = 6))
expect_visible(recode_num(vmiss, `4` = 5, `6` = 10, missing = 7))
expect_visible(recode_num(vmiss, `4` = 5, `6` = 10, default = 8))
expect_visible(recode_num(vmiss, `4` = 5, `6` = 10, default = 8, missing = 7))
expect_visible(recode_num(mtcNA, `4` = 5, `1` = 2))
expect_visible(recode_num(mtcNA, `4` = 5, `1` = 2, missing = 6))
expect_visible(recode_num(mtcNA, `4` = 5, `1` = 2, default = 8))
expect_visible(recode_num(mtcNA, `4` = 5, `1` = 2, default = 8, missing = 7))
})
options(warn = 1) |
GUI_ENV <- new.env()
migui <- function(tk = "RGtk2") {
options("guiToolkit" = tk)
initialize();
nextScreen();
}
initialize <- function() {
GUI_ENV$window <- gwindow("mi", visible = FALSE);
GUI_ENV$state <- "get_data";
GUI_ENV$group <- ggroup(container=GUI_ENV$window);
GUI_ENV$n.chains = 4;
GUI_ENV$n.iter = 30;
GUI_ENV$mdf_args <- list();
GUI_ENV$mdf <- NULL
GUI_ENV$user_df <- NULL
nextScreen();
addSpring(GUI_ENV$group);
visible(GUI_ENV$window) <- TRUE;
visible(GUI_ENV$group) <- TRUE;
return(invisible(NULL))
}
nextScreen <- function() {
delete(GUI_ENV$window,GUI_ENV$group);
GUI_ENV$group <- ggroup(container=GUI_ENV$window,
horizontal=FALSE,
expand=TRUE,
fill="both");
functionName <- paste("do_", GUI_ENV$state, sep = "");
do.call(functionName, args = list());
return(invisible(NULL))
}
do_get_data <- function() {
innerGroup <- setupScreen(step = "1",
title = "Get Data",
nextHandler = function(h,...) {
selected = svalue(dataSourceRadio);
if (selected == dataSourceOptions["disk"]) {
GUI_ENV$state = "get_data_from_disk";
} else if (selected == dataSourceOptions["r"]) {
GUI_ENV$state = "get_data_from_r";
} else if (selected == dataSourceOptions["mi"]) {
GUI_ENV$state = "get_data_from_mi";
}
nextScreen();
},
backHandler = NULL );
choiceLabel("Select location of data", container=innerGroup);
dataSourceOptions <- c(disk="disk drive [csv, dta, por, sav, RData]",
r="R's workspace",
mi="mi package example [built in]");
dataSourceRadio <- gradio(dataSourceOptions, selected=1,
container = indent(innerGroup));
}
do_get_data_from_mi <- function() {
innerGroup <- setupScreen(step = "1.5",
title = "Get Data from mi Package",
backHandler = navHandler("get_data"),
nextHandler = function(h,...) {
do.call("data", args = list(svalue(selector),
package = "mi"))
GUI_ENV$user_df <- get(svalue(selector),
envir= .GlobalEnv);
GUI_ENV$state <- "describe_data";
nextScreen();
});
choiceLabel("Select an example", container = innerGroup);
data.frames <- data(package = "mi")$results[,3];
selector <- gcombobox(data.frames, container=indent(innerGroup),
editable = TRUE, expand=FALSE, anchor=c(-1,-1));
}
do_get_data_from_disk <- function() {
extensions <- paste("*", c("csv", "dta", "por", "sav", "RData", "Rdata"), sep = ".");
file_name <- gfile(text="Choosing Data File for mi GUI", type="open",
filter = list("All files" = list(patterns = extensions)));
if (is.na(file_name)) {
GUI_ENV$state = "get_data";
} else {
if (grepl("\\.csv$", file_name)) {
user_df <- read.csv(file_name);
GUI_ENV$user_df <- user_df;
GUI_ENV$state = "describe_data";
} else if (grepl("\\.dta$", file_name)) {
user_df <- foreign::read.dta(file_name);
GUI_ENV$user_df <- user_df;
GUI_ENV$state = "describe_data";
} else if (grepl("\\.\\(por,sav\\)$", file_name)) {
user_df <- foreign::read.spss(file_name, to.data.frame = TRUE);
GUI_ENV$user_df <- user_df;
GUI_ENV$state = "describe_data";
} else {
dfs <- load(file_name, envir = GUI_ENV);
GUI_ENV$user_df <- GUI_ENV[[dfs[1]]]
GUI_ENV$state = "describe_data";
}
}
nextScreen();
return(invisible(NULL));
}
do_get_data_from_r <- function() {
data.frames <- sapply(ls(envir = .GlobalEnv), FUN = function(x) {
is.data.frame(get(x, envir = .GlobalEnv))
});
if(length(data.frames) == 0) {
GUI_ENV$state <- "get_data";
gmessage("No data.frames found in R's global environment, starting over",
icon = "error", parent = GUI_ENV$group);
nextScreen();
return(invisible(NULL))
}
data.frames <- data.frames[data.frames];
innerGroup <- setupScreen(step = "1.5",
title = "Get Data Frame from R's Environment",
nextHandler = function(h,...) {
user_df <- get(svalue(selector), envir= .GlobalEnv);
if(is(user_df, "missing_data.frame")) {
GUI_ENV$user_df <- as.data.frame(user_df);
GUI_ENV$mdf <- user_df;
GUI_ENV$state <- "var_options";
}
else {
GUI_ENV$user_df <- user_df
GUI_ENV$state <- "describe_data";
}
nextScreen();
},
backHandler = navHandler("get_data"));
choiceLabel("Select a data frame in R from the list", container = innerGroup);
selector <- gcombobox(names(data.frames), container=indent(innerGroup),
editable = TRUE);
}
do_describe_data <- function() {
innerGroup <- setupScreen(step = "2",
title = "Describe the Structure of Your Data",
backHandler = navHandler("get_data"),
nextHandler = function(h,...) {
subclass <- svalue(data_desc);
if(!any(grepl(paste("^", subclass, "_", sep = ""),
mi::.prune("missing_data.frame")))) subclass <- NULL
GUI_ENV$mdf_args$subclass <- subclass;
GUI_ENV$state <- "get_var_classes";
nextScreen();
});
choiceLabel("Select the best description of your data", container = innerGroup);
options <- mi::.prune("missing_data.frame")
human_options <- sapply(strsplit(options, "_"), FUN = function(x) x[1]);
human_options[1] <- "no special structure";
names(human_options) <- options;
data_desc <- gradio(human_options, container=indent(innerGroup));
}
do_get_var_classes <- function() {
innerGroup <- setupScreen(step = "3",
title = "Set Class of Variables",
backHandler = navHandler("describe_data"),
nextHandler = navHandler("var_options"));
label_group <- ggroup(horizontal=TRUE, container=innerGroup);
glabel("<b>Select default parameters for variable types:</b>",
markup=TRUE, container= label_group);
addSpring(label_group);
defaults <- formals(.guess_type);
threshold_group <- ggroup(horizontal=TRUE, container = innerGroup);
contLabel <- glabel("Continuity Threshold", container=threshold_group);
thresholdButton <- gspinbutton(from=3, to=100, by=1, value=defaults$threshold,
container=threshold_group, handler = function(h, ...) {
GUI_ENV$mdf <- NULL;
types <- sapply(colnames(GUI_ENV$user_df), FUN = function(y) {
.guess_type(GUI_ENV$user_df[,y],
favor_ordered = svalue(favor_ord),
favor_positive = svalue(favor_pos),
threshold = svalue(thresholdButton),
variable_name = y)
})
names(types) <- colnames(GUI_ENV$user_df);
GUI_ENV$mdf_args$types <- types;
for(i in seq_along(types)) {
tmp <- selectionListGroup[i+1,2]
svalue(tmp) <- types[i];
}
});
addSpace(threshold_group,15);
favor_ord <- gcheckbox("favor ordered", checked=defaults$favor_ordered, container=threshold_group,
handler = function(h, ...) {
GUI_ENV$mdf <- NULL;
types <- sapply(colnames(GUI_ENV$user_df), FUN = function(y){
.guess_type(GUI_ENV$user_df[,y],
favor_ordered = svalue(favor_ord),
favor_positive = svalue(favor_pos),
threshold = svalue(thresholdButton),
variable_name = y)
})
names(types) <- colnames(GUI_ENV$user_df);
GUI_ENV$mdf_args$types <- types;
categoricals <- c("unordered-categorical", "ordered-categorical")
for(i in seq_along(types)) if(types[i] %in% categoricals) {
tmp <- selectionListGroup[i+1,2]
svalue(tmp) <- types[i];
}
});
addSpace(threshold_group,15);
favor_pos <- gcheckbox("favor positive", checked=defaults$favor_positive, container=threshold_group,
handler = function(h, ...) {
GUI_ENV$mdf <- NULL;
types <- sapply(colnames(GUI_ENV$user_df), FUN = function(y) {
.guess_type(GUI_ENV$user_df[,y],
favor_ordered = svalue(favor_ord),
favor_positive = svalue(favor_pos),
threshold = svalue(thresholdButton),
variable_name = y)
})
names(types) <- colnames(GUI_ENV$user_df);
GUI_ENV$mdf_args$types <- types;
cons <- mi::.prune("continuous")
for(i in seq_along(types)) if(types[i] %in% cons) {
tmp <- selectionListGroup[i+1,2]
svalue(tmp) <- types[i];
}
});
gseparator(horizontal=TRUE,container=innerGroup);
addSpring(innerGroup);
glabel("<b>Variable Class Selector:</b>", markup = TRUE, container=innerGroup);
selectionGroup <- ggroup(container=innerGroup, use.scrollwindow= TRUE,
horizontal=FALSE, expand=TRUE, visible = TRUE,
width = 300, height = 300);
selectionListGroup <- glayout(container=selectionGroup, expand=TRUE);
tt <- mi::.prune("missing_variable");
names(tt) <- tt
tt_names <- names(tt)
tt[] <- "stub"
tt["irrelevant"] <- "EXCLUDE the variable from all models"
tt["count"] <- "non-negative integers"
tt["continuous"] <- "continuous but NOT special like positive-continuous, etc"
tt["fixed"] <- "one unique value"
tt["group"] <- "grouping factors for multilevel models"
tt["grouped-binary"] <- "binary variable that is grouped into strata"
tt["unordered-categorical"] <- "discrete variable with >= 3 values but WITHOUT ordering, sometimes called nominal or factor"
tt["ordered-categorical"] <- "discrete variable with >= 3 values WITH ordering by increasing value"
tt["interval"] <- "interval-censored from the left and / or right"
tt["binary"] <- "discrete variable with exactly 2 values"
tt["bounded-continuous"] <- "continuous variable with lower and / or upper bounds (but not a proportion)"
tt["positive-continuous"] <- "continuous variable with no values of 0 or negative (but not a proportion)"
tt["proportion"] <- "proportion on the (0,1) interval"
tt["semi-continuous"] <- "continuous variable with a point mass at the lower and / or upper end of the distribution"
tt["nonnegative-continuous"] <- "continuous variable with a point mass at zero and no negative values"
tt["SC_proportion"] <- "proportion on the [0,1] interval"
if(any(tt == "stub")) print(tt)
tt <- paste(names(tt), tt, sep = ": ")
names(tt) <- tt_names
types <- sapply(colnames(GUI_ENV$user_df), FUN = function(y) {
.guess_type(GUI_ENV$user_df[,y], favor_ordered = svalue(favor_ord),
favor_positive = svalue(favor_pos), threshold = svalue(thresholdButton),
variable_name = y)
})
names(types) <- colnames(GUI_ENV$user_df);
GUI_ENV$mdf_args$types <- types;
selectionListGroup[1,1] = glabel("<b>Variable</b>", container=selectionListGroup, markup=TRUE, anchor = c(1,0));
selectionListGroup[1,2] = glabel("<b>Class</b>", container=selectionListGroup, markup=TRUE);
if(!is.null(GUI_ENV$mdf_args$subclass) && GUI_ENV$mdf_args$subclass == "experiment") {
concept <- c("covariate", "outcome", "treatment")
GUI_ENV$mdf_args$concept <- factor(rep("covariate", length(types)), levels = concept)
}
for(i in seq_along(types)) {
selectionListGroup[i+1,1] = glabel(names(types)[i], container = selectionListGroup,
anchor=c(1,0));
likelyTypeTF <- mi::.possible_missing_variable(GUI_ENV$user_df[,i])
likelyTypes <- names(likelyTypeTF[likelyTypeTF])
likelyTypes <- data.frame(likelyTypes, NA, tt[likelyTypes], stringsAsFactors = FALSE)
selectedId <- which(likelyTypes == types[i]);
selectionListGroup[i+1,2] = gcombobox(items = likelyTypes, anchor=c(-1,0),
action=i, editable = TRUE,
selected = selectedId,
container = selectionListGroup,
handler = function(h, ...) {
GUI_ENV$mdf <- NULL;
GUI_ENV$mdf_args$types[h$action] <- svalue(h$obj)
});
if(!is.null(GUI_ENV$mdf_args$subclass) && GUI_ENV$mdf_args$subclass == "experiment") {
selectionListGroup[i+1,3] = gcombobox(items = concept, anchor=c(-1,0),
editable = TRUE, action = i, selected = 1,
container = selectionListGroup, handler = function(h, ...) {
GUI_ENV$mdf_args$concept[h$action] <- svalue(h$obj)
})
}
}
}
do_var_options <- function() {
if (is.null(GUI_ENV$mdf)) {
GUI_ENV$mdf_args$y <- GUI_ENV$user_df
GUI_ENV$mdf <- do.call("missing_data.frame", args = GUI_ENV$mdf_args)
GUI_ENV$imputations <- NULL
}
innerGroup <- setupScreen(step = "4",
title = "Options for Variables",
backHandler = navHandler("get_var_classes"),
nextHandler = navHandler("pre_mi"));
topGroup <- ggroup(horizontal = FALSE, container = innerGroup);
glabel("Choose a variable and then its associated options:", container = topGroup);
varnames <- colnames(GUI_ENV$mdf)
varHandler <- function(h, ...) {
mv <- GUI_ENV$mdf@variables[[svalue(h$obj)]];
varHandler2(mv);
return(invisible(NULL));
}
varHandler2 <- function(mv) {
classes <- mi::.possible_missing_variable(GUI_ENV$user_df[,mv@variable_name])
classes <- names(classes[classes])
tmp <- classCombo
if(!identical(svalue(tmp), class(mv)[1])) {
svalue(tmp) <- class(mv)[1]
tmp[] <- classes;
svalue(tmp) <- class(mv)[1]
}
tmp <- miss
svalue(tmp) <- paste("
varHandler3(mv);
codes <- unique(mv@raw_data);
codes <- codes[!is.na(codes)]
if(is(mv, "continuous")) codes <- sort(codes)
tmp <- table.group[5,2]
svalue(tmp) <- "";
tmp[] <- codes
table.group[5,4] <- gcombobox(items = c("NA", "unpossible", codes),
selected = 0, editable = TRUE,
container = table.group, action = "recode",
handler = changeHandler);
impModel <- .default_model(mv, GUI_ENV$mdf)[1]
tmp <- model
if(is.na(impModel)) {
svalue(tmp) <- "No model needed because no missing values"
}
else svalue(tmp) <- paste("Model implied by the above options:", impModel)
return(invisible(NULL));
}
varHandler3 <- function(mv) {
if (!mv@all_obs) {
for(i in 1:3) {
tmp <- table.group[i,2]
enabled(tmp) <- TRUE
}
im <- getClass(class(mv))@prototype@imputation_method
im <- im[!is.na(im)]
im <- sapply(im, rosettaStone)
tmp <- table.group[1,2]
tmp[] <- im
svalue(tmp) <- rosettaStone(mv@imputation_method)
tmp <- table.group[2,2]
svalue(tmp) <- mv@family$family
tmp[] <- getClass(class(mv))@prototype@known_families
svalue(tmp) <- mv@family$family
tmp <- table.group[3,2]
svalue(tmp) <- mv@family$link
tmp[] <- getClass(class(mv))@prototype@known_links
svalue(tmp) <- mv@family$link
}
else for(i in 1:3) {
tmp <- table.group[i,2]
svalue(tmp) <- ""
enabled(tmp) <- FALSE
}
if (is(mv, "continuous")) {
tmp <- table.group[4,2]
enabled(tmp) <- TRUE
svalue(tmp) <- .parse_trans(mv@transformation)
tmp[] <- mv@known_transformations
svalue(tmp) <- .parse_trans(mv@transformation)
}
else {
tmp <- table.group[4,2]
svalue(tmp) <- ""
enabled(tmp) <- FALSE
}
return(invisible(NULL))
}
rosettaStone <- function(im, inverse = FALSE) {
if(inverse) switch(im,
"posterior predictive distribution" = "ppd",
"predictive mean matching" = "pmm",
"conditional mean of observed" = "mean",
"conditional median of observed" = "median",
"conditional mean" = "expectation",
"highest conditional probability" = "mode",
NA_character_)
else switch(im,
ppd = "posterior predictive distribution",
pmm = "predictive mean matching",
mean = "conditional mean of observed",
median = "conditional median of observed",
expectation = "conditional mean",
mode = "highest conditional probability",
"not recognized")
}
changeHandler <- function(h, ...) {
to <- svalue(h$obj)
if(is.null(to)) return(invisible(NULL))
if(to == "") return(invisible(NULL))
what <- h$action
if(what == "imputation_method") to <- rosettaStone(to, inverse = TRUE)
mv <- GUI_ENV$mdf@variables[[svalue(selectedVar)]];
if(what == "imputation_method" && mv@imputation_method == to) return(invisible(NULL))
if(what == "family" && mv@family$family == to) return(invisible(NULL))
if(what == "link" && mv@family$link == to) return(invisible(NULL))
if(is(mv, "continuous") && what == "transformation" &&
.parse_trans(mv@transformation) == to) return(invisible(NULL))
if(what == "class" && class(mv) == to) return(invisible(NULL))
if(what == "recode") {
what <- svalue(table.group[5,2]);
if(to == "NA") to <- NA;
}
GUI_ENV$mdf <- change(data = GUI_ENV$mdf, y = svalue(selectedVar),
what = what, to = to);
GUI_ENV$imputations <- NULL;
mv <- GUI_ENV$mdf@variables[[svalue(selectedVar)]];
varHandler3(mv);
return(invisible(NULL));
}
varGroup <- ggroup(horizontal = TRUE, container = topGroup)
selectedVar <- gcombobox(items = varnames, selected = 1, container = varGroup,
editable = TRUE, handler = varHandler);
mv <- GUI_ENV$mdf@variables[[1]]
glabel(" Class: ", container = varGroup);
classes <- mi::.prune(class(mv));
classCombo <- gcombobox(classes, selected = which(class(mv) == classes),
action = "class", editable = TRUE,
container = varGroup, handler = changeHandler);
miss <- glabel(paste("
gbutton("histogram ...", container = varGroup,
handler = function(h, ...) {
mv <- GUI_ENV$mdf@variables[[svalue(selectedVar)]]
hist(mv);
title(main = paste("Observed", mv@variable_name));
});
addSpring(innerGroup)
gseparator(horizontal = TRUE, container = innerGroup);
addSpace(innerGroup, value = 30);
table.group <- glayout(container = innerGroup, expand = TRUE, fill = "both");
ims <- getClass(class(mv))@prototype@imputation_method;
ims <- ims[!is.na(ims)]
table.group[1,1] <- glabel("imputation method", container = table.group);
table.group[1,2] <- gcombobox(items = sapply(ims, rosettaStone),
selected = 1, editable = TRUE,
handler = changeHandler,
action = "imputation_method",
container = table.group);
table.group[2,1] <- glabel("family (likelihood)", container = table.group);
table.group[2,2] <- gcombobox(items = ifelse(is.na(mv@family), "none", mv@family$family),
selected = 1, editable = TRUE,
handler = changeHandler,
action = "family",
container = table.group);
table.group[3,1] <- glabel("link function", container = table.group);
table.group[3,2] <- gcombobox(items = ifelse(is.na(mv@family), "none", mv@family$link),
selected = 1, editable = TRUE,
handler = changeHandler,
action = "link",
container = table.group);
table.group[4,1] <- glabel("transformation function", container = table.group);
table.group[4,2] <- gcombobox(items = if(is(mv, "continuous")) .parse_trans(mv@transformation) else "none",
selected = 1, editable = TRUE,
handler = changeHandler,
action = "transformation",
container = table.group);
for(i in 1:4) {
tmp <- table.group[i,2]
size(tmp) <- c(250,25);
}
table.group[5,1] <- glabel("Recode", container = table.group);
codes <- unique(mv@raw_data);
codes <- codes[!is.na(codes)];
if(is(mv, "continuous")) codes <- sort(codes);
table.group[5,2] <- gcombobox(items = codes, selected = 0,
editable = TRUE, container = table.group);
table.group[5,3] <- glabel("as", container = table.group);
table.group[5,4] <- gcombobox(items = c("NA", "unpossible", codes),
selected = 0, editable = TRUE,
container = table.group, action = "recode", handler = changeHandler);
gseparator(horizontal = TRUE, container = innerGroup);
modelGroup <- ggroup(horizontal = TRUE, container = innerGroup);
model <- glabel("", container = modelGroup);
varHandler2(mv);
}
do_pre_mi <- function() {
innerGroup <- setupScreen(step = "5",
title = "Pre-imputation Diagnostics",
backHandler = navHandler("var_options"),
nextHandler = navHandler("impute"));
choiceLabel("Click one or more", container = innerGroup);
button.group <- ggroup(horizontal = TRUE, container = indent(innerGroup));
table.group <- glayout(horizontal = TRUE, container = button.group, visible = TRUE);
table.group[1,1] <- gbutton("image plot ...", container = table.group,
handler = function(h, ...) {
image(GUI_ENV$mdf, ask = FALSE);
return(invisible(NULL));
w <- gwindow(visible = FALSE);
ggraphics(container = w);
visible(w) <- TRUE
image(GUI_ENV$mdf, ask = FALSE);
});
table.group[2,1] <- gbutton("histograms ...", container = table.group,
handler = function(h, ...) hist(GUI_ENV$mdf, ask = FALSE));
table.group[3,1] <- gbutton("numerical summary ...", container = table.group,
handler = function(h, ...) print(summary(as.data.frame(GUI_ENV$mdf))));
addSpring(button.group);
}
do_impute <- function() {
innerGroup <- setupScreen(step = "6",
title = "Options for Imputation",
backHandler = navHandler("pre_mi"),
nextHandler = function(h,...) { runImputationInDialog(); });
choiceLabel("Choose options for imputation",container = innerGroup);
table.group <- glayout(horizontal = TRUE, container = indent(innerGroup), visible = TRUE);
table.group[1,1] <- glabel("Number of chains:", container=table.group);
table.group[1,2] <- gspinbutton(from = 1, to=100, by=1, value=GUI_ENV$n.chains, container=table.group,
handler= function(h,...) {
GUI_ENV$n.chains = svalue(h$obj);
});
table.group[2,1] <- glabel("Number of iterations:", container=table.group);
table.group[2,2] <- gspinbutton(from = 1, to=1000, by=1, value=GUI_ENV$n.iter, container=table.group,
handler = function(h,...) {
GUI_ENV$n.iter = svalue(h$obj);
});
}
runImputationInDialog <- function() {
exitImputationDialog <- function() {
dispose(dialogWindow);
nextScreen();
return(invisible(NULL))
}
foo <- function() {
on.exit(exitImputationDialog());
if (is.null(GUI_ENV$imputations)) {
GUI_ENV$state <- "impute"
GUI_ENV$imputations <- mi(GUI_ENV$mdf, n.chains = GUI_ENV$n.chains,
n.iter = GUI_ENV$n.iter, parallel = svalue(parallel));
}
else {
GUI_ENV$state <- "convergence_eval";
GUI_ENV$imputations <- mi(GUI_ENV$imputations, n.iter = GUI_ENV$n.iter);
}
GUI_ENV$state <- "convergence_eval";
return(invisible(NULL))
}
dialogWindow <- gwindow("Running mi");
group <- ggroup(container=dialogWindow, horizontal=FALSE, expand=TRUE);
addTitle("Step 7: Running mi", group);
addSpring(group);
optionsGroup <- ggroup(container=group, horizontal=TRUE, expand=TRUE);
parallel <- gcheckbox("Run in parallel", checked=TRUE, container=optionsGroup);
txt <- if(.Platform$OS.type == "windows") "ESC" else "<CTRL>+c"
exec <- gbutton("Run mi",container=group, handler = function(h, ...) foo())
focus(exec) <- TRUE
addSpring(group);
}
do_convergence_eval <- function() {
innerGroup <- setupScreen(step = "8",
title = "Evaluate Convergence",
backHandler=navHandler("impute"),
nextHandler=navHandler("parametric_eval"));
choiceLabel("Click to show convergence evaluations", container=innerGroup);
BUGS <- NULL;
gbutton("R-hat statistics...",
container=innerGroup,
handler = function(h,...) {
if (is.null(BUGS)) BUGS <- mi::Rhats(GUI_ENV$imputations)
print(round(BUGS, 2));
});
addSpring(innerGroup);
gseparator(horizontal=TRUE, container=innerGroup);
addSpring(innerGroup);
cont.group <- ggroup(horizontal=TRUE, expand=TRUE, container=innerGroup);
gbutton("Continue ...",
handler = function(h, ...) {
runImputationInDialog();
},
container= cont.group);
glabel("mi for", container = cont.group);
gspinbutton(from = 1, to = 1000, by = 1,
value = GUI_ENV$n.iter, container = cont.group,
handler = function(h, ...) {
GUI_ENV$n.iter = svalue(h$obj);
});
glabel("more iterations", markup = FALSE, container = cont.group);
}
do_parametric_eval <- function() {
innerGroup <- setupScreen(step = "9",
title = "Parametric Diagnostics",
backHandler = navHandler("convergence_eval"),
nextHandler = navHandler("analysis"));
choiceLabel("Run one or more of the following diagnostics", container = innerGroup);
button.group <- ggroup(horizontal = TRUE, container = indent(innerGroup));
variable_names <- colnames(GUI_ENV$mdf);
variable_names <- c("Choose variable", variable_names);
table.group <- glayout(horizontal = TRUE, container = button.group, visible = TRUE);
table.group[1,1] <- glabel("Plot model fits:", container = table.group);
table.group[1,2] <- gcombobox(items = variable_names, selected = 1,
editable = TRUE, container = table.group,
handler = function(h, ...) {
y <- svalue(h$obj)
if (y != "Choose variable") plot(x = GUI_ENV$imputations, y = y, ask = FALSE)
else dev.off();
});
table.group[2,2] <- gbutton("image plot ...", container = table.group,
handler = function(h, ...) image(GUI_ENV$imputations, ask = FALSE));
table.group[3,2] <- gbutton("histograms for chain ...", container = table.group,
handler = function(h, ...) {
m <- svalue(table.group[3,3])
hist(GUI_ENV$imputations, m = m, ask = FALSE);
title(sub = paste("Chain", m), outer = TRUE)
});
table.group[3,3] <- gspinbutton(from = 1, to = length(GUI_ENV$imputations), by = 1, value = 1,
container = table.group)
table.group[4,2] <- gbutton("numerical summary ...", container = table.group,
handler = function(h, ...)
print(summary(do.call(rbind, complete(GUI_ENV$imputations)))));
addSpring(button.group);
}
do_analysis <- function() {
innerGroup <- setupFinalScreen(step = "10",
title = "Analyze Completed Datasets",
backHandler = navHandler("parametric_eval"),
nextHandler = function(h,...) { exit_gui(h); });
gbutton("Estimate pooled model ...", container = innerGroup, handler = function(h, ...) {
runPooledAnalysisDialog();
});
gbutton("Create completed data.frames in R's environment", container = innerGroup, handler = function(h, ...) {
.GlobalEnv$dfs <- mi::complete(GUI_ENV$imputations);
msg <- "data.frames are in R's environment with object name 'dfs'"
gmessage(msg, , icon = "info")
});
gbutton("Save imputations in R binary format", container = innerGroup, handler = function(h, ...) {
file_name <- gfile(text="Choosing File Name to Save As", type="save");
if (is.na(file_name))
return();
if (!grepl("\\.R[dD]ata$", x = file_name, perl = TRUE)) {
file_name <- paste(file_name, "RData", sep = ".");
}
saveMe <- GUI_ENV$imputations
save(saveMe, file = file_name)
});
gbutton("Export imputations for Stata", container = innerGroup, handler = function(h, ...) {
file_name <- gfile(text="Choosing File Name to Save As", type="save");
if (is.na(file_name))
return();
if (!grepl("\\.dta$", x = file_name, perl = TRUE)) {
file_name <- paste(file_name, "dta", sep = ".");
}
mi::mi2stata(GUI_ENV$imputations, m = length(GUI_ENV$imputations), file = file_name)
})
addSpring(innerGroup)
}
runPooledAnalysisDialog <- function() {
dialogWindow <- gwindow("Pooled analysis");
dialog.group <- ggroup(horizontal = FALSE, container = dialogWindow, expand = TRUE);
addTitle("Step 12: Specify analysis model", dialog.group);
addSpring(dialog.group);
missing <- colnames(GUI_ENV$mdf@X);
missing <- missing[grepl("^missing_", missing)];
var.names <- c(colnames(GUI_ENV$imputations), missing);
var.group <- glabel(strwrap(paste("Variables:", paste(var.names, collapse = ", "))), container = dialog.group);
addSpring(dialog.group);
possibleFunctions <- c("bayesglm", "glm", "lm");
estimatingFunction <- possibleFunctions[1]
estimatingFormula <- NA_character_;
m <- length(GUI_ENV$imputations)
dotdotdot <- ""
table.group <- glayout(horizontal = FALSE, container = dialog.group, visible = TRUE);
table.group[1,1] <- glabel("estimating function", container = table.group);
table.group[1,2] <- gcombobox(possibleFunctions, selected = 1,
editable = TRUE, container = table.group);
table.group[2,1] <- glabel("formula", container = table.group);
table.group[2,2] <- gedit("", container = table.group, initial.msg = "formula like: y ~ x1 + x2 ...");
table.group[3,1] <- glabel("number of chains", container = table.group);
table.group[3,2] <- gspinbutton(from = 1, to = 2 * length(GUI_ENV$imputations), value = length(GUI_ENV$imputations),
by = 1, container = table.group);
table.group[4,1] <- glabel("...", container = table.group);
table.group[4,2] <- gedit("", container = table.group, width = 30,
initial.msg = "any additional arguments like: foo = bar",
handler = function(h, ...) {
dotdotdot <- svalue(h$obj);
});
gbutton("Estimate", container = dialog.group, handler = function(h, ...) {
poolCall <- paste("pool(formula = ", svalue(table.group[2,2]),
", data = GUI_ENV$imputations",
", m = ", svalue(table.group[3,2]),
", FUN = ", svalue(table.group[1,2]), sep = "")
if (svalue(table.group[4,2]) != "") poolCall <- paste(poolCall, svalue(table.group[4,2]), sep = ", ")
poolCall <- paste(poolCall, ")")
model <- eval(parse(text = poolCall))
print(model)
});
addSpring(dialog.group)
gbutton("Return to previous screen", container = dialog.group, handler = function(h, ...) {
dispose(dialogWindow);
});
}
helpHandler <- function(h,...) {
URL <- "http://www.google.com";
browseURL(URL);
};
setupScreen <- function(step, title, backHandler, nextHandler) {
setupScreenHelper(step,title,backHandler,nextHandler,"NEXT >");
}
setupFinalScreen <- function(step, title, backHandler, nextHandler) {
setupScreenHelper(step,title,backHandler,nextHandler,"FINISH >");
}
setupScreenHelper <- function(step, title, backHandler, nextHandler, nextButtonText) {
topGroup <- ggroup(horizontal=FALSE, expand=TRUE, fill="both",
container = GUI_ENV$group, visible = FALSE);
glabel(paste("<big><b>","Step ", step, ". <i>", title,"</i></b></big>",
sep = ""), markup=TRUE,
container=topGroup, anchor=c(0,-1));
addSpring(topGroup);
innerGroup <- ggroup(horizontal=FALSE, expand=TRUE, fill="both",
container = topGroup);
addSpring(topGroup);
gseparator(horizontal=TRUE, container = topGroup);
button.group <- ggroup(container = topGroup, horizontal=TRUE);
gbutton(" QUIT! ", container=button.group,
handler = function(h,...) { exit_gui(h) });
addSpring(button.group);
if (!is.null(backHandler)) {
gbutton(" < BACK ", container=button.group, handler=backHandler);
addSpace(button.group,10);
}
gbutton(" HELP... ", container=button.group, handler=helpHandler);
addSpace(button.group,10);
nextButton <- gbutton(nextButtonText, container=button.group, handler=nextHandler);
return(innerGroup);
}
navHandler <- function(stateName) {
return(function(h, ...) {
GUI_ENV$state = stateName;
nextScreen();
})
}
choiceLabel <- function(title, container) {
glabel(paste("<b>",title,":</b>"), markup=TRUE,
expand=FALSE, fill="x", anchor=c(-1,0),
container=container);
addSpace(container,3);
}
indent <- function(container) {
group <- ggroup(horizontal=TRUE, container=container, fill=FALSE);
addSpace(group,5);
return(group);
}
exit_gui <- function(h) {
reallyQuit <- gconfirm(paste("Do you really want to quit?\nCancel means 'no' while 'OK' means 'yes'"), icon = "warning")
if(reallyQuit) dispose(GUI_ENV$window);
return(invisible(NULL));
}
addTitle <- function(title,container) {
title_group <- ggroup(horizontal=TRUE, expand=TRUE, fill="both",
container=container);
glabel(paste("<b>",title,"</b>"),
container=title_group,
markup=TRUE);
}
.default_model <-
function(y, data) {
if(is(data, "allcategorical_missing_data.frame")) return("Gibbs")
if(y@all_obs) {
if(is(y, "semi-continuous")) return(rep(NA_character_, 2))
else return(NA_character_)
}
if(is(y, "irrelevant")) return(NA_character_)
if(y@imputation_method == "mcar") return(NA_character_)
if(!is.method_in_mi("fit_model", y = class(y), data = class(data))) {
if(is(y, "semi-continuous")) return(rep("user-defined", 2))
else return("user-defined")
}
fam <- y@family$family
link <- y@family$link
if(is(y, "count")) {
if(fam == "quasipoisson" && link == "log") return("qpoisson")
else if(fam == "poisson" && link == "log") return("poisson")
else return("****")
}
else if(is(y, "binary")) {
if(is(y, "grouped-binary")) return("clogit")
if(fam == "quasibinomial") return(paste("q", link, sep = ""))
else if(fam == "binomial") return(link)
else return("****")
}
else if(is(y, "interval")) return("survreg")
else if(is(y, "ordered-categorical")) return(paste("o", link, sep = ""))
else if(is(y, "unordered-categorical")) {
if(fam == "binomial") out <- "RN"
else out <- "m"
return(paste(out, link, sep = ""))
}
else if(is(y, "proportion")) return(if(fam == "gaussian") "linear" else "betareg")
else if(is(y, "SC_proportion")) {
out <- .default_model(y@indicator, data)
return(c("betareg", out))
}
else if(is(y, "semi-continuous")) {
out <- .default_model(y@indicator, data)
if(fam == "gaussian") {
if(link == "identity") return(c("linear", out))
else if(link == "log") return(c("loglinear", out))
else if(link == "inverse") return(c("inverselinear", out))
else return(c("****", out))
}
else if(fam == "Gamma") return(c("****", out))
else if(fam == "inverse.gaussian") return(c("****", out))
else if(fam == "quasi") return(c("quasi", out))
else return(c("****", out))
}
else if(is(y, "continuous")) {
if(fam == "gaussian") {
if(link == "identity") return("linear")
else if(link == "log") return("loglinear")
else if(link == "inverse") return("inverselinear")
else return("****")
}
else if(fam == "Gamma") return("****")
else if(fam == "inverse.gaussian") return("****")
else if(fam == "quasi") return("quasi")
else return("****")
}
else return("user-defined")
}
.guess_type <-
function(y, favor_ordered = TRUE, favor_positive = FALSE, threshold = 5,
variable_name = deparse(substitute(y))) {
if(!is.null(dim(y))) stop(paste(variable_name, ": must be a vector"))
if(is.factor(y)) y <- factor(y)
values <- unique(y)
values <- sort(values[!is.na(values)])
len <- length(values)
if(len == 0) {
warning(paste(variable_name, ": cannot infer variable type when all values are NA, guessing 'irrelevant'"))
type <- "irrelevant"
}
else if(len == 1) type <- "fixed"
else if(grepl("^[[:punct:]]",
variable_name)) type <- "irrelevant"
else if(identical("id",
tolower(variable_name))) type <- "irrelevant"
else if(len == 2) {
if(!is.numeric(values)) type <- "binary"
else if(all(values ==
as.integer(values))) type <- "binary"
else if(favor_positive) {
if(all(values > 0)) type <- "positive-continuous"
else if(all(values >= 0)) type <- "nonnegative-continuous"
else type <- "continuous"
}
else type <- "continuous"
}
else if(is.ts(y)) {
if(favor_positive) {
if(all(values > 0)) type <- "positive-continuous"
else if(all(values >= 0)) type <- "nonnegative-continuous"
else type <- "continuous"
}
else type <- "continuous"
}
else if(is.ordered(y)) type <- "ordered-categorical"
else if(is.factor(y)) type <- "unordered-categorical"
else if(is.character(y)) type <- "unordered-categorical"
else if(is.numeric(y)) {
if(all(values >= 0) &&
all(values <= 1)) {
if(any(values %in% 0:1)) type <- "SC_proportion"
else type <- "proportion"
}
else if(len <= threshold &&
all(values == as.integer(values)))
type <- if(favor_ordered) "ordered-categorical" else "unordered-categorical"
else if(favor_positive) {
if(all(values > 0)) type <- "positive-continuous"
else if(all(values >= 0)) type <- "nonnegative-continuous"
else type <- "continuous"
}
else type <- "continuous"
}
else stop(paste("cannot infer variable type for", variable_name))
return(type)
}
.parse_trans <-
function(trans) {
if(identical(names(formals(trans)), c("y", "mean", "sd", "inverse"))) return("standardize")
if(identical(names(formals(trans)), c("y", "a", "inverse"))) return("logshift")
if(identical(body(trans), body(.squeeze_transform))) return("squeeze")
if(identical(body(trans), body(.identity_transform))) return("identity")
if(identical(body(trans), body(log))) return("log")
if(identical(body(trans), body(sqrt))) return("sqrt")
if(identical(body(trans), body(.cuberoot))) return("cuberoot")
if(identical(body(trans), body(qnorm))) return("qnorm")
return("user-defined")
}
.squeeze_transform <- function(y, inverse = FALSE) {
n <- length(y)
if(inverse) (y * n - .5) / (n - 1)
else (y * (n - 1) + .5) / n
}
.cuberoot <-
function(y, inverse = FALSE) {
if(inverse) y^3
else y^(1/3)
}
.identity_transform <- function(y, ...) return(y)
is.method_in_mi <-
function(generic, ...) {
method <- selectMethod(generic, signature(...))
return(environmentName(environment([email protected])) == "mi")
} |
library(xts)
library(qrmdata)
library(qrmtools)
data(fire)
plot.zoo(fire, ylab = "Danish fire insurance claim losses in 1M DKK")
mean_excess_plot(fire)
u10 <- 10
u20 <- 20
abline(v = c(u10, u20))
GPD_shape_plot(fire)
abline(v = c(u10, u20))
abline(h = 0.5, lty = 3)
exceed.u10 <- fire[fire > u10]
excess.u10 <- exceed.u10 - u10
(fit.u10 <- fit_GPD_MLE(excess.u10))
shape.u10 <- fit.u10$par[["shape"]]
scale.u10 <- fit.u10$par[["scale"]]
exceed.u20 <- fire[fire > u20]
excess.u20 <- exceed.u20 - u20
(fit.u20 <- fit_GPD_MLE(excess.u20))
shape.u20 <- fit.u20$par[["shape"]]
scale.u20 <- fit.u20$par[["scale"]]
res <- edf_plot(excess.u10)
z <- tail(res$t, n = -1)
lines(z, pGPD(z, shape = shape.u10, scale = scale.u10))
res <- edf_plot(excess.u20)
z <- tail(res$t, n = -1)
lines(z, pGPD(z, shape = shape.u20, scale = scale.u20))
res <- edf_plot(exceed.u10)
z <- tail(res$t, n = -1)
lines(z, pGPD(z-u10, shape = shape.u10, scale = scale.u10))
res <- edf_plot(exceed.u20)
z <- tail(res$t, n = -1)
lines(z, pGPD(z-u20, shape = shape.u20, scale = scale.u20))
qf.u10 <- function(p)
qGPD(p, shape = shape.u10, scale = scale.u10)
qq_plot(excess.u10, FUN = qf.u10)
qq_plot(exceed.u10, FUN = function(p) u10 + qf.u10(p))
qf.u20 <- function(p)
qGPD(p, shape = shape.u20, scale = scale.u20)
qq_plot(excess.u20, FUN = qf.u20)
qq_plot(exceed.u20, FUN = function(p) u20 + qf.u20(p))
alpha <- c(0.99, 0.995)
(VaR.u10 <- VaR_GPDtail(alpha, threshold = u10, p.exceed = mean(fire > u10),
shape = shape.u10, scale = scale.u10))
(VaR.u20 <- VaR_GPDtail(alpha, threshold = u20, p.exceed = mean(fire > u20),
shape = shape.u20, scale = scale.u20))
(ES.u10 <- ES_GPDtail(alpha, threshold = u10, p.exceed = mean(fire > u10),
shape = shape.u10, scale = scale.u10))
(ES.u20 <- ES_GPDtail(alpha, threshold = u20, p.exceed = mean(fire > u20),
shape = shape.u20, scale = scale.u20))
tail_plot(fire, threshold = u10, shape = shape.u10, scale = scale.u10)
abline(h = 1-alpha[1], v = VaR.u10[1], lty = 2)
abline(h = 1-alpha[1], v = ES.u10[1], lty = 2)
tail_plot(fire, threshold = u20, shape = shape.u20, scale = scale.u20)
abline(h = 1-alpha[1], v = VaR.u20[1], lty = 2)
abline(h = 1-alpha[1], v = ES.u20[1], lty = 2)
opar <- par(mar = c(5, 4, 4, 2) + c(0, 1, 0, 0))
fit.u10. <- QRM::fit.GPD(fire, u10)
QRM::showRM(fit.u10., alpha = 0.99, RM = "VaR", method = "BFGS")
QRM::showRM(fit.u10., alpha = 0.99, RM = "ES", method = "BFGS")
par(opar)
opar <- par(mar = c(5, 4, 4, 2) + c(0, 1, 0, 0))
fit.u20. <- QRM::fit.GPD(fire, u20)
QRM::showRM(fit.u20., alpha = 0.99, RM = "VaR", method = "BFGS")
QRM::showRM(fit.u20., alpha = 0.99, RM = "ES", method = "BFGS")
par(opar) |
Srivastava2014 <- function(x, ...){
ls <- list2(...)
matrix_ls <- x
statistic <- Srivastava2014Stat(matrix_ls)
xmin <- names(matrix_ls[1])
xmax <- names(matrix_ls[length(matrix_ls)])
xother <- names(matrix_ls[-c(1, length(matrix_ls))])
data.name <- Reduce(paste0, past(xmin = xmin, xother, xmax = xmax))
names(statistic) <- "Chi-Squared"
parameter <- 1
names(parameter) <- "df"
null.value <- 0
names(null.value) <- "difference in covariance matrices"
p.value <- 1 - pchisq(statistic, parameter)
obj <- list(statistic = statistic,
parameter = parameter,
p.value = p.value,
estimate = NULL,
null.value = null.value,
alternative = "two.sided",
method = "Srivastava et al. 2014 Homogeneity of Covariance Matrices Test",
data.name = data.name)
class(obj) <- "htest"
obj
} |
Dataset <- R6::R6Class(
classname = "gpb.Dataset",
cloneable = FALSE,
public = list(
finalize = function() {
.Call(
LGBM_DatasetFree_R
, private$handle
)
private$handle <- NULL
return(invisible(NULL))
},
initialize = function(data,
params = list(),
reference = NULL,
colnames = NULL,
categorical_feature = NULL,
predictor = NULL,
free_raw_data = FALSE,
used_indices = NULL,
info = list(),
...) {
if (!(is.null(reference) || gpb.check.r6.class(object = reference, name = "gpb.Dataset"))) {
stop("gpb.Dataset: If provided, reference must be a ", sQuote("gpb.Dataset"))
}
if (!(is.null(predictor) || gpb.check.r6.class(object = predictor, name = "gpb.Predictor"))) {
stop("gpb.Dataset: If provided, predictor must be a ", sQuote("gpb.Predictor"))
}
additional_params <- list(...)
INFO_KEYS <- c("label", "weight", "init_score", "group")
for (key in names(additional_params)) {
if (key %in% INFO_KEYS) {
info[[key]] <- additional_params[[key]]
} else {
params[[key]] <- additional_params[[key]]
}
}
if (is.matrix(data)) {
if (storage.mode(data) != "double") {
storage.mode(data) <- "double"
}
data <- matrix(as.vector(data), ncol=ncol(data), dimnames=dimnames(data))
}
private$raw_data <- data
private$params <- params
private$reference <- reference
private$colnames <- colnames
private$categorical_feature <- categorical_feature
private$predictor <- predictor
private$free_raw_data <- free_raw_data
private$used_indices <- sort(used_indices, decreasing = FALSE)
private$info <- info
private$version <- 0L
return(invisible(NULL))
},
create_valid = function(data,
info = list(),
...) {
ret <- Dataset$new(
data = data
, params = private$params
, reference = self
, colnames = private$colnames
, categorical_feature = private$categorical_feature
, predictor = private$predictor
, free_raw_data = private$free_raw_data
, used_indices = NULL
, info = info
, ...
)
return(invisible(ret))
},
construct = function() {
if (!gpb.is.null.handle(x = private$handle)) {
return(invisible(self))
}
cnames <- NULL
if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
cnames <- colnames(private$raw_data)
}
if (is.null(private$colnames) && !is.null(cnames)) {
private$colnames <- as.character(cnames)
}
if (!is.null(private$categorical_feature)) {
if (is.character(private$categorical_feature)) {
cate_indices <- as.list(match(private$categorical_feature, private$colnames) - 1L)
if (sum(is.na(cate_indices)) > 0L) {
stop(
"gpb.self.get.handle: supplied an unknown feature in categorical_feature: "
, sQuote(private$categorical_feature[is.na(cate_indices)])
)
}
} else {
if (max(private$categorical_feature) > length(private$colnames)) {
stop(
"gpb.self.get.handle: supplied a too large value in categorical_feature: "
, max(private$categorical_feature)
, " but only "
, length(private$colnames)
, " features"
)
}
cate_indices <- as.list(private$categorical_feature - 1L)
}
private$params$categorical_feature <- cate_indices
}
has_header <- FALSE
if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
params_has_header <- tolower(as.character(private$params$has_header)) == "true"
params_header <- tolower(as.character(private$params$header)) == "true"
if (params_has_header || params_header) {
has_header <- TRUE
}
}
params_str <- gpb.params2str(params = private$params)
ref_handle <- NULL
if (!is.null(private$reference)) {
ref_handle <- private$reference$.__enclos_env__$private$get_handle()
}
handle <- NULL
if (is.null(private$used_indices)) {
if (is.character(private$raw_data)) {
handle <- .Call(
LGBM_DatasetCreateFromFile_R
, private$raw_data
, params_str
, ref_handle
)
private$free_raw_data <- TRUE
} else if (is.matrix(private$raw_data)) {
handle <- .Call(
LGBM_DatasetCreateFromMat_R
, private$raw_data
, nrow(private$raw_data)
, ncol(private$raw_data)
, params_str
, ref_handle
)
} else if (methods::is(private$raw_data, "dgCMatrix")) {
if (length(private$raw_data@p) > 2147483647L) {
stop("Cannot support large CSC matrix")
}
handle <- .Call(
LGBM_DatasetCreateFromCSC_R
, private$raw_data@p
, private$raw_data@i
, private$raw_data@x
, length(private$raw_data@p)
, length(private$raw_data@x)
, nrow(private$raw_data)
, params_str
, ref_handle
)
} else {
stop(
"gpb.Dataset.construct: does not support constructing from "
, sQuote(class(private$raw_data))
)
}
} else {
if (is.null(private$reference)) {
stop("gpb.Dataset.construct: reference cannot be NULL for constructing data subset")
}
handle <- .Call(
LGBM_DatasetGetSubset_R
, ref_handle
, c(private$used_indices)
, length(private$used_indices)
, params_str
)
}
if (gpb.is.null.handle(x = handle)) {
stop("gpb.Dataset.construct: cannot create Dataset handle")
}
class(handle) <- "gpb.Dataset.handle"
private$handle <- handle
if (!is.null(private$colnames)) {
self$set_colnames(colnames = private$colnames)
}
if (!is.null(private$predictor) && is.null(private$used_indices)) {
init_score <- private$predictor$predict(
data = private$raw_data
, rawscore = TRUE
, reshape = TRUE
)
init_score <- as.vector(init_score)
private$info$init_score <- init_score
}
if (isTRUE(private$free_raw_data)) {
private$raw_data <- NULL
}
if (length(private$info) > 0L) {
for (i in seq_along(private$info)) {
p <- private$info[i]
self$setinfo(name = names(p), info = p[[1L]])
}
}
if (is.null(self$getinfo(name = "label"))) {
stop("gpb.Dataset.construct: label should be set")
}
return(invisible(self))
},
dim = function() {
if (!gpb.is.null.handle(x = private$handle)) {
num_row <- 0L
num_col <- 0L
.Call(
LGBM_DatasetGetNumData_R
, private$handle
, num_row
)
.Call(
LGBM_DatasetGetNumFeature_R
, private$handle
, num_col
)
return(c(num_row, num_col))
} else if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
return(dim(private$raw_data))
} else {
stop(
"dim: cannot get dimensions before dataset has been constructed, "
, "please call gpb.Dataset.construct explicitly"
)
}
},
get_colnames = function() {
if (!gpb.is.null.handle(x = private$handle)) {
private$colnames <- .Call(
LGBM_DatasetGetFeatureNames_R
, private$handle
)
return(private$colnames)
} else if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
return(colnames(private$raw_data))
} else {
stop(
"dim: cannot get colnames before dataset has been constructed, please call "
, "gpb.Dataset.construct explicitly"
)
}
},
set_colnames = function(colnames) {
if (is.null(colnames)) {
return(invisible(self))
}
colnames <- as.character(colnames)
if (length(colnames) == 0L) {
return(invisible(self))
}
private$colnames <- colnames
if (!gpb.is.null.handle(x = private$handle)) {
merged_name <- paste0(as.list(private$colnames), collapse = "\t")
.Call(
LGBM_DatasetSetFeatureNames_R
, private$handle
, merged_name
)
}
return(invisible(self))
},
getinfo = function(name) {
INFONAMES <- c("label", "weight", "init_score", "group")
if (!is.character(name) || length(name) != 1L || !name %in% INFONAMES) {
stop("getinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
}
if (is.null(private$info[[name]])) {
if (gpb.is.null.handle(x = private$handle)) {
stop("Cannot perform getinfo before constructing Dataset.")
}
info_len <- 0L
.Call(
LGBM_DatasetGetFieldSize_R
, private$handle
, name
, info_len
)
if (info_len > 0L) {
ret <- NULL
ret <- if (name == "group") {
integer(info_len)
} else {
numeric(info_len)
}
.Call(
LGBM_DatasetGetField_R
, private$handle
, name
, ret
)
private$info[[name]] <- ret
}
}
return(private$info[[name]])
},
setinfo = function(name, info) {
INFONAMES <- c("label", "weight", "init_score", "group")
if (!is.character(name) || length(name) != 1L || !name %in% INFONAMES) {
stop("setinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
}
info <- if (name == "group") {
as.integer(info)
} else {
as.numeric(info)
}
private$info[[name]] <- info
if (!gpb.is.null.handle(x = private$handle) && !is.null(info)) {
if (length(info) > 0L) {
.Call(
LGBM_DatasetSetField_R
, private$handle
, name
, info
, length(info)
)
private$version <- private$version + 1L
}
}
return(invisible(self))
},
slice = function(idxset, ...) {
return(
Dataset$new(
data = NULL
, params = private$params
, reference = self
, colnames = private$colnames
, categorical_feature = private$categorical_feature
, predictor = private$predictor
, free_raw_data = private$free_raw_data
, used_indices = sort(idxset, decreasing = FALSE)
, info = NULL
, ...
)
)
},
update_params = function(params) {
if (length(params) == 0L) {
return(invisible(self))
}
if (gpb.is.null.handle(x = private$handle)) {
private$params <- modifyList(private$params, params)
} else {
tryCatch({
.Call(
LGBM_DatasetUpdateParamChecking_R
, gpb.params2str(params = private$params)
, gpb.params2str(params = params)
)
}, error = function(e) {
if (is.null(private$raw_data)) {
stop(e)
}
private$params <- modifyList(private$params, params)
self$finalize()
})
}
return(invisible(self))
},
get_params = function() {
dataset_params <- unname(unlist(.DATASET_PARAMETERS()))
ret <- list()
for (param_key in names(private$params)) {
if (param_key %in% dataset_params) {
ret[[param_key]] <- private$params[[param_key]]
}
}
return(ret)
},
set_categorical_feature = function(categorical_feature) {
if (identical(private$categorical_feature, categorical_feature)) {
return(invisible(self))
}
if (is.null(private$raw_data)) {
stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
please set ", sQuote("free_raw_data = FALSE"), " when you construct gpb.Dataset")
}
private$categorical_feature <- categorical_feature
self$finalize()
return(invisible(self))
},
set_reference = function(reference) {
self$set_categorical_feature(categorical_feature = reference$.__enclos_env__$private$categorical_feature)
self$set_colnames(colnames = reference$get_colnames())
private$set_predictor(predictor = reference$.__enclos_env__$private$predictor)
if (identical(private$reference, reference)) {
return(invisible(self))
}
if (is.null(private$raw_data)) {
stop("set_reference: cannot set reference after freeing raw data,
please set ", sQuote("free_raw_data = FALSE"), " when you construct gpb.Dataset")
}
if (!is.null(reference)) {
if (!gpb.check.r6.class(object = reference, name = "gpb.Dataset")) {
stop("set_reference: Can only use gpb.Dataset as a reference")
}
}
private$reference <- reference
self$finalize()
return(invisible(self))
},
save_binary = function(fname) {
self$construct()
.Call(
LGBM_DatasetSaveBinary_R
, private$handle
, fname
)
return(invisible(self))
}
),
private = list(
handle = NULL,
raw_data = NULL,
params = list(),
reference = NULL,
colnames = NULL,
categorical_feature = NULL,
predictor = NULL,
free_raw_data = FALSE,
used_indices = NULL,
info = NULL,
version = 0L,
get_handle = function() {
if (gpb.is.null.handle(x = private$handle)) {
self$construct()
}
return(private$handle)
},
set_predictor = function(predictor) {
if (identical(private$predictor, predictor)) {
return(invisible(self))
}
if (is.null(private$raw_data)) {
stop("set_predictor: cannot set predictor after free raw data,
please set ", sQuote("free_raw_data = FALSE"), " when you construct gpb.Dataset")
}
if (!is.null(predictor)) {
if (!gpb.check.r6.class(object = predictor, name = "gpb.Predictor")) {
stop("set_predictor: Can only use gpb.Predictor as predictor")
}
}
private$predictor <- predictor
self$finalize()
return(invisible(self))
}
)
)
gpb.Dataset <- function(data,
params = list(),
reference = NULL,
colnames = NULL,
categorical_feature = NULL,
free_raw_data = FALSE,
info = list(),
...) {
return(
invisible(Dataset$new(
data = data
, params = params
, reference = reference
, colnames = colnames
, categorical_feature = categorical_feature
, predictor = NULL
, free_raw_data = free_raw_data
, used_indices = NULL
, info = info
, ...
))
)
}
gpb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
if (!gpb.is.Dataset(x = dataset)) {
stop("gpb.Dataset.create.valid: input data should be an gpb.Dataset object")
}
return(invisible(dataset$create_valid(data = data, info = info, ...)))
}
gpb.Dataset.construct <- function(dataset) {
if (!gpb.is.Dataset(x = dataset)) {
stop("gpb.Dataset.construct: input data should be an gpb.Dataset object")
}
return(invisible(dataset$construct()))
}
dim.gpb.Dataset <- function(x, ...) {
if (!gpb.is.Dataset(x = x)) {
stop("dim.gpb.Dataset: input data should be an gpb.Dataset object")
}
return(x$dim())
}
dimnames.gpb.Dataset <- function(x) {
if (!gpb.is.Dataset(x = x)) {
stop("dimnames.gpb.Dataset: input data should be an gpb.Dataset object")
}
return(list(NULL, x$get_colnames()))
}
`dimnames<-.gpb.Dataset` <- function(x, value) {
if (!identical(class(value), "list") || length(value) != 2L) {
stop("invalid ", sQuote("value"), " given: must be a list of two elements")
}
if (!is.null(value[[1L]])) {
stop("gpb.Dataset does not have rownames")
}
if (is.null(value[[2L]])) {
x$set_colnames(colnames = NULL)
return(x)
}
if (ncol(x) != length(value[[2L]])) {
stop(
"can't assign "
, sQuote(length(value[[2L]]))
, " colnames to an gpb.Dataset with "
, sQuote(ncol(x))
, " columns"
)
}
x$set_colnames(colnames = value[[2L]])
return(x)
}
slice <- function(dataset, ...) {
UseMethod("slice")
}
slice.gpb.Dataset <- function(dataset, idxset, ...) {
if (!gpb.is.Dataset(x = dataset)) {
stop("slice.gpb.Dataset: input dataset should be an gpb.Dataset object")
}
return(invisible(dataset$slice(idxset = idxset, ...)))
}
getinfo <- function(dataset, ...) {
UseMethod("getinfo")
}
getinfo.gpb.Dataset <- function(dataset, name, ...) {
if (!gpb.is.Dataset(x = dataset)) {
stop("getinfo.gpb.Dataset: input dataset should be an gpb.Dataset object")
}
return(dataset$getinfo(name = name))
}
setinfo <- function(dataset, ...) {
UseMethod("setinfo")
}
setinfo.gpb.Dataset <- function(dataset, name, info, ...) {
if (!gpb.is.Dataset(x = dataset)) {
stop("setinfo.gpb.Dataset: input dataset should be an gpb.Dataset object")
}
return(invisible(dataset$setinfo(name = name, info = info)))
}
gpb.Dataset.set.categorical <- function(dataset, categorical_feature) {
if (!gpb.is.Dataset(x = dataset)) {
stop("gpb.Dataset.set.categorical: input dataset should be an gpb.Dataset object")
}
return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
}
gpb.Dataset.set.reference <- function(dataset, reference) {
if (!gpb.is.Dataset(x = dataset)) {
stop("gpb.Dataset.set.reference: input dataset should be an gpb.Dataset object")
}
return(invisible(dataset$set_reference(reference = reference)))
}
gpb.Dataset.save <- function(dataset, fname) {
if (!gpb.is.Dataset(x = dataset)) {
stop("gpb.Dataset.set: input dataset should be an gpb.Dataset object")
}
if (!is.character(fname)) {
stop("gpb.Dataset.set: fname should be a character or a file connection")
}
return(invisible(dataset$save_binary(fname = fname)))
} |
expected <- eval(parse(text="c(NA, -3L)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(x = 1:3, y = structure(1:3, .Label = c(\"A\", \"D\", \"E\"), class = \"factor\"), z = c(6, 9, 10)), .Names = c(\"x\", \"y\", \"z\"), row.names = c(NA, -3L), class = \"data.frame\"), 0L)"));
.Internal(`shortRowNames`(argv[[1]], argv[[2]]));
}, o=expected); |
matrix_column_names <- function( X, X_sigma, intercept_mu = TRUE, intercept_sigma = TRUE){
i_first = 1
if (intercept_mu){
colnames(X)[1] = "(Intercept)"
i_first = 2
}
l = ncol(X)
if (l >= i_first){
if (all(colnames(X)[i_first:l] == "")){
colnames(X)[i_first:l] = sapply(1:(l-i_first+1), function(x){paste('v', as.character(x), sep="")})
}
}
i_first = 1
if (intercept_sigma){
colnames(X_sigma)[1] = "(Intercept_s)"
i_first = 2
}
l = ncol(X_sigma)
if (l >= i_first){
if (all(colnames(X_sigma)[i_first:l] == "")){
colnames(X_sigma)[i_first:l] = sapply(1:(l-i_first+1), function(x){paste('v', as.character(x), "_s", sep="")})
}
}
return( list( colnames_X = colnames(X),
colnames_X_sigma = colnames(X_sigma)))
} |
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(lodown)
in_path <- paste0(importdir, "0003_scf_data")
download_data <- 0
if(download_data == 1){
lodown( "scf" , output_dir = file.path(in_path , "SCF" ) )
} |
Soddy <- function(A, r1, B, r2, C, r3){
x1=A[1]
y1=A[2]
x2=B[1]
y2=B[2]
x3=C[1]
y3=C[2]
s1=-1
s2=-1
s3=-1
xmax=max(c(A[1]+r1,B[1]+r2,C[1]+r3))
xmin=min(c(A[1]-r1,B[1]-r2,C[1]-r3))
ymax=max(c(A[2]+r1,B[2]+r2,C[2]+r3))
ymin=min(c(A[2]-r1,B[2]-r2,C[2]-r3))
x=runif(1,xmin,xmax)
y=runif(1,ymin,ymax)
r=runif(1,mean(r1,r2,r3),mean(r1,r2,r3)+1)
f1=function(x,y,r) (x-x1)^2+(y-y1)^2-(r-s1*r1)^2
f2=function(x,y,r) (x-x2)^2+(y-y2)^2-(r-s2*r2)^2
f3=function(x,y,r) (x-x3)^2+(y-y3)^2-(r-s3*r3)^2
J11=function(x,y,r) 2*(x-x1)
J12=function(x,y,r) 2*(y-y1)
J13=function(x,y,r) -2*(r-s1*r1)
J21=function(x,y,r) 2*(x-x2)
J22=function(x,y,r) 2*(y-y2)
J23=function(x,y,r) -2*(r-s2*r2)
J31=function(x,y,r) 2*(x-x3)
J32=function(x,y,r) 2*(y-y3)
J33=function(x,y,r) -2*(r-s3*r3)
it=1000
for (i in c(1:it)){
Fx=c(f1(x,y,r),f2(x,y,r),f3(x,y,r))
J=matrix(data = c(J11(x,y,r),J12(x,y,r),J13(x,y,r),
J21(x,y,r),J22(x,y,r),J23(x,y,r),
J31(x,y,r),J32(x,y,r),J33(x,y,r)),
nrow = 3,ncol = 3)
J=t(J)
Y=solve(J)%*%(-Fx)
x=x+Y[1]
y=y+Y[2]
r=r+Y[3]
}
inner_ratius=r1*r2*r3/(r1*r2+r1*r3+r2*r3+2*sqrt(r1*r2*r3*(r1+r2+r3)))
outer_ratius=-r1*r2*r3/(r1*r2+r1*r3+r2*r3-2*sqrt(r1*r2*r3*(r1+r2+r3)))
result=list(c(x,y),inner_ratius,outer_ratius)
return(result)
} |
computeQuickKrigcov <- function(model,
integration.points,
X.new,
precalc.data,
F.newdata,
c.newdata){
integration.points <- t(as.matrix(integration.points))
colnames(integration.points) <- colnames(model@X)
c.xnew.integpoints <- DiceKriging::covMat1Mat2(X1=integration.points,X2=X.new, object=model@covariance, nugget.flag=model@[email protected])
second.member <- t(F.newdata - crossprod(c.newdata,precalc.data$Kinv.F))
cov.F <- precalc.data$first.member%*%second.member
kn <- c.xnew.integpoints - crossprod(precalc.data$Kinv.c.olddata,c.newdata) + cov.F
return(kn)
} |
NULL
popkin_A <- function(
X,
n = NA,
loci_on_cols = FALSE,
mem_factor = 0.7,
mem_lim = NA,
m_chunk_max = 1000
) {
if ( missing( X ) )
stop( 'Genotype matrix `X` is required!' )
n_ind <- n
mem_debugging <- FALSE
isFn <- FALSE
if (is.function(X)) {
isFn <- TRUE
if ( is.na( n_ind ) )
stop('missing number of individuals "n", which is required when X is a function.')
} else if ('BEDMatrix' %in% class(X)) {
loci_on_cols <- TRUE
} else if (!is.matrix(X)) {
stop('X has unsupported class: ', toString( class(X) ) )
}
names_X <- NULL
if (isFn) {
m_loci <- NA
} else {
if (loci_on_cols) {
if ( !is.na( n_ind ) && n != nrow( X ) )
warning('User set number of samples that does not match X dimensions (will go with latter): ', n_ind, ' != ', nrow(X))
n_ind <- nrow(X)
m_loci <- ncol(X)
names_X <- rownames(X)
} else {
if (!is.na(n_ind) && n_ind != ncol(X))
warning('User set number of samples that does not match X dimensions (will go with latter): ', n_ind, ' != ', ncol(X))
n_ind <- ncol(X)
m_loci <- nrow(X)
names_X <- colnames(X)
}
}
A <- matrix(0, nrow = n_ind, ncol = n_ind)
M <- matrix(0, nrow = n_ind, ncol = n_ind)
if (!is.null(names_X)) {
colnames(A) <- names_X
rownames(A) <- names_X
}
data <- solve_m_mem_lim(
n = n_ind,
m = m_loci,
mat_m_n = 1.5,
mat_n_n = 1,
mem = mem_lim,
mem_factor = mem_factor
)
m_chunk <- data$m_chunk
if ( m_chunk > m_chunk_max )
m_chunk <- m_chunk_max
if (mem_debugging) {
message('mem_lim: ', round(data$mem_lim / GB, 1), ' GB')
message('mem_chunk: ', round(data$mem_chunk / GB, 1), ' GB')
message('m_chunk: ', m_chunk)
}
i_chunk <- 1
while (TRUE) {
if (isFn) {
Xi <- X( m_chunk )
if (is.null(Xi)) break
} else {
if (mem_debugging)
message('chunk started!')
if (i_chunk > m_loci)
break
indexes_loci_chunk <- i_chunk : min(i_chunk + m_chunk - 1, m_loci)
if (loci_on_cols) {
Xi <- t(X[, indexes_loci_chunk, drop = FALSE])
} else {
Xi <- X[indexes_loci_chunk, , drop = FALSE]
}
i_chunk <- i_chunk + m_chunk
}
if (storage.mode(Xi) != 'integer')
storage.mode(Xi) <- 'integer'
obj <- getMAInt(Xi)
A <- A + obj$SA
M <- M + obj$M
}
A <- A / M - 1
return(
list(
A = A,
M = M
)
)
} |
golden.section.search <- function(ax, bx, cx, f, niter = 25,
f.extra = NA, tol = 1e-05, gridx = NA) {
gridx <- sort(gridx)
NG <- length(gridx)
fgrid <- rep(NA, NG)
if (!is.na(gridx[1])) {
gridx <- sort(gridx)
NG <- length(gridx)
fgrid <- rep(NA, NG)
for (k in 1:NG) {
fgrid[k] <- f(gridx[k], f.extra)
}
if (any(is.na(fgrid))) {
warning("grid search has found some missing values in objective function")
return(list(x = NA, fmin = NA, iter = 0, tol = tol,
coarse.search = cbind(gridx, fgrid, deparse.level = 1)))
}
ind.bx <- which.min(fgrid)
if ((ind.bx == 1) | ind.bx == NG) {
warning("grid search gives minimun at boundary")
return(list(x = gridx[ind.bx], fmin = fgrid[ind.bx],
iter = 0, tol = tol, coarse.search = cbind(gridx,
fgrid, deparse.level = 1)))
}
ax <- gridx[ind.bx - 1]
bx <- gridx[ind.bx]
cx <- gridx[ind.bx + 1]
}
else {
f1 <- f(ax, f.extra)
f2 <- f(bx, f.extra)
f3 <- f(cx, f.extra)
if ((f2 > f1) | (f2 > f3))
stop("starting values not convex")
}
r <- 0.61803399
con <- 1 - r
x0 <- ax
x3 <- cx
if (abs(cx - bx) > abs(bx - ax)) {
x1 <- bx
x2 <- bx + con * (bx - ax)
}
else {
x2 <- bx
x1 <- bx - con * (bx - ax)
}
f1 <- f(x1, f.extra)
f2 <- f(x2, f.extra)
iter <- niter
for (k in 1:niter) {
if (f2 < f1) {
x0 <- x1
x1 <- x2
x2 <- r * x1 + con * x3
f0 <- f1
f1 <- f2
f2 <- f(x2, f.extra)
}
else {
x3 <- x2
x2 <- x1
x1 <- r * x2 + con * x0
f3 <- f2
f2 <- f1
f1 <- f(x1, f.extra)
}
if (abs(f2 - f1) < tol) {
iter <- k
break
}
}
if (f1 < f2) {
golden <- f1
xmin <- x1
}
else {
golden <- f2
xmin <- x2
}
if (iter == niter) {
warning("Maximum iterations reached")
}
list(x = xmin, fmin = golden, iter = iter, tol = tol, coarse.search = cbind(gridx,
fgrid, deparse.level = 1))
} |
irwls.cov <-
function(y,
x,
var.type,
lambda1,
lambda2,
maxit = 100,
alpha0 = NULL,
theta0 = NULL,
thresh = 1e-5,
trace.it = F,
max.rank = NULL,
nu = 1e-2) {
d <- dim(y)
n <- d[1]
p <- d[2]
if (is.null(max.rank))
max.rank <- min(n, p) - 1
else
max.rank <- min(max.rank, min(n, p) - 1)
y <- as.matrix(y)
y <- matrix(as.numeric(y), nrow = n)
y0 <- y
q <- ncol(x)
x <- as.matrix(x)
x <- matrix(as.numeric(x), nrow = nrow(x))
omega <- !is.na(y)
if (is.null(alpha0))
alpha0 <- rep(0, q)
if (is.null(theta0))
theta0 <- matrix(rep(0, n * p), nrow = n)
alpha <- alpha0
alpha.mat <-
matrix(matrix(as.numeric(x), nrow = n * p) %*% alpha, nrow = n)
theta <- theta0
param <- alpha.mat + theta
gaus <- (1 / 2) * sum(y0[, var.type == "gaussian"] ^ 2, na.rm = T)
pois <- n * p
binom <- binom <- -log(2) * n * p
objective <- gaus + pois + binom
y0 <- y
error <- 1
iter <- 0
stepalpha <- 1
steptheta <- 1
while (((error > thresh) && (iter < maxit))) {
iter <- iter + 1
alpha.tmp <- alpha
theta.tmp <- theta
yv <- quad_approx(y0, param, var.type)
ytilde <- yv$ytilde
vtilde2 <- yv$vtilde2
ytilde[omega == 0] <- 0
alpha <-
glmnet::glmnet(
x,
c((ytilde - omega * theta.tmp) * vtilde2 / (omega * vtilde2 + (1 -
omega) * nu)),
family = "gaussian",
lambda = lambda2,
intercept = FALSE,
weights = c(omega * vtilde2 + (1 - omega) * nu)
)
alpha <- as.numeric(alpha$beta)
resalpha <-
armijo.alpha(
y,
x,
alpha,
theta.tmp,
alpha.tmp,
theta.tmp,
z = ytilde - omega * param,
w = vtilde2,
lambda2 = lambda2,
var.type = var.type,
nu = nu,
zeta = 0.1,
th = 0,
step = stepalpha
)
alpha <- resalpha$alpha
stepalpha <- resalpha$step
alpha.mat <-
matrix(matrix(as.numeric(x), nrow = n * p) %*% alpha, nrow = n)
alpha.tmp <- alpha
param <- alpha.mat + theta.tmp
yv <- quad_approx(y0, param, var.type)
ytilde <- yv$ytilde
vtilde2 <- yv$vtilde2
ytilde[omega == 0] <- 0
w <- omega * vtilde2 + (1 - omega) * nu
lambda1w <- lambda1 / max(w)
w <- w / max(w)
svd_theta <-
wlra(vtilde2 / (omega * vtilde2 + (1 - omega) * nu) * (ytilde - omega * alpha.mat),
w,
lambda1w)
u <- svd_theta$u
d <- svd_theta$d
v <- svd_theta$v
if (is.null(dim(u))) {
theta <- d * u %*% t(v)
} else {
theta <- u %*% diag(d) %*% t(v)
}
restheta <-
armijo.lr(
y0 = y,
theta = theta,
theta.tmp = theta.tmp,
alpha.mat = alpha.mat,
w = vtilde2,
z = ytilde - omega * param,
lambda1 = lambda1,
var.type = var.type,
b = 0.5,
nu = nu,
zeta = 0.1,
th = 0,
step = steptheta
)
theta <- restheta$theta
steptheta <- restheta$step
param <- alpha.mat + theta
gaus <-
(1 / 2) * sum((y[, var.type == "gaussian"] - param[, var.type == "gaussian"]) ^
2,
na.rm = T)
pois <-
sum((-(y[, var.type == "poisson"] * param[, var.type == "poisson"]) +
exp(param[, var.type == "poisson"])), na.rm = T)
binom <-
sum((-(y[, var.type == "binomial"] * param[, var.type == "binomial"]) +
log(1 + exp(param[, var.type == "binomial"]))), na.rm = T)
d <- svd(theta)$d
objective <- c(objective, min(
.Machine$double.xmax,
(pois + gaus + binom + lambda1 * sum(d) + lambda2 * sum(abs(alpha)))
))
if (iter == 1) {
error <- 1
} else if ((stepalpha <= 1e-30) && (steptheta <= 1e-30)) {
error <- 0
} else{
if (objective[iter] == .Machine$double.xmax) {
error <- 1
} else
error <-
abs(objective[iter] - objective[iter - 1]) / abs(objective[iter - 1])
}
if (trace.it) {
print(paste("iter ", iter, ": error ", error, " - objective: ", objective[iter]))
}
}
if (error < thresh)
cvg = T
else
cvg = F
estim <- param
estim[, var.type == "poisson"] <-
matrix(stats::rpois(n * sum(var.type == "poisson"), lambda = c(exp(estim[, var.type == "poisson"]))), nrow =
n)
estim[, var.type == "binomial"] <-
round(exp(estim[, var.type == "binomial"]) / (1 + exp(estim[, var.type == "binomial"])))
y.imputed <- y0
y.imputed[omega == 0] <- estim[omega == 0]
return(list(
y.imputed = y.imputed,
param = alpha.mat + theta,
alpha = alpha,
theta = theta
))
} |
RF_predictor <- function(forest, xn){
m <- length(forest)
y_result <- rep(list(list()), m)
for(tree in 1:m){
y_result[[tree]] <- predictor(forest[[tree]], xn)
}
y_result <- as.data.frame(matrix(unlist(y_result), nrow = length(unlist(y_result[1]))))
y_result <- apply(y_result, 1, "mean")
return(y_result)
} |
data(worldmap)
data(ETOPO5)
data(USAmap)
data(usacity)
data(worldcity)
plotworldmap(worldmap, add = FALSE, col = 2)
shiftlon = 180
readline("Hit Return>")
plotworldmap(worldmap, shiftlon = shiftlon, add = FALSE, col = 2)
readline("Hit Return>")
shiftlon = 60
plotworldmap(worldmap, shiftlon = shiftlon, add = FALSE, col = 2)
A = locworld(shiftlon)
A = list(lon=c(281.9203, 291.9571), lat=c(35.58868, 44.55468),
LON=c(281.9203, 291.9571), LAT=c(35.58868, 44.55468),
utmbox=list(x=17, y="S", lon=-84, lat=32),
UTM0 =list(lam=-81 , phi=36 ),
shiftlon=60)
PROJ = setPROJ(type=2, LAT0=mean(A$LAT) , LON0=mean(A$LON) )
NYLIM = c(A$LON[1], A$LAT[1],A$LON[2], A$LAT[2] )
readline("Hit Return>")
plotGEOmapXY(worldmap, PROJ=PROJ, LIM=NYLIM , add=FALSE)
readline("Hit Return>")
plotGEOmapXY(USAmap, PROJ=PROJ, LIM=NYLIM , add=FALSE)
LMAP = SETPOLIMAP()
P = list(lat=mean(A$LAT), lon=mean(A$LON))
J = LOCPOLIMAP(P, LMAP)
pmap2 = selectPOLImap(which(J==1), 2)
pmap2$STROKES$col[pmap2$STROKES$code=="2"]='green'
pmap2$STROKES$col[pmap2$STROKES$code=="3"]='purple'
pmap2$STROKES$col[pmap2$STROKES$code=="4"]='red'
library(maps)
zz = map('county', 'new york', plot = FALSE)
cntyNY.xy = GLOB.XY(zz$y, zz$x, PROJ)
lines(cntyNY.xy$x, cntyNY.xy$y, col='red' )
plotGEOmapXY(pmap2, PROJ=PROJ , LIM=NYLIM, add=TRUE)
readline("Hit Return>")
DOTOPOMAPI(TOPO=ETOPO5, themap=worldmap, shiftlon=180)
readline("Hit Return>")
DOTOPOMAPI(TOPO=ETOPO5, themap=worldmap, shiftlon=180, DOCONT=TRUE, DOIMG=TRUE,
PNTS=NULL, PCOL='red', PCH=1, PCEX=1, PS=FALSE, MAPPATH=NULL,
polybase = NULL,
USAmap= USAmap,
usacity=usacity,
worldcity=worldcity) |
"cdens" <-
function(distn, H)
{
if (!is.function(try(get(distn), silent = TRUE)))
stop("'distn' must be a character of a distribution function")
pdens <- distn
ddens <- paste("d", substring(distn, 2), sep = "")
nd <- formals(get(ddens))
np <- formals(get(pdens))
mn <- match(names(nd), names(np))
args <- c(np[!is.na(mn)], nd[which("log" == names(nd))])
argd <- paste(names(args), collapse = ", ")
argp <- paste(head(names(args),length(args)-1), collapse = ", ")
f <- function(){}
formals(f) <- c(alist(x=), args, list(H = H))
if(substring(distn, 2)=="gamma"){
body(f) <- parse(text = "
{i <- which(x <= H);
logarg <- \"log\" %in% names(as.list(match.call()));
if(!missing(rate)){
den <- 1 - pgamma(H, shape, rate)
if (logarg && log)
res <- dgamma(x, shape, rate, log=log) - log(den)
else res <- dgamma(x, shape, rate, log=log)/den
res[i] <- 0
}else{
den <- 1 - pgamma(H, shape, scale)
if (logarg && log)
res <- dgamma(x, shape, scale, log=log) - log(den)
else res <- dgamma(x, shape, scale, log=log)/den
res[i] <- 0
};
return(res)}")
}else{
body(f) <- parse(text = paste(
"{i <- which(x <= H);
logarg <- \"log\" %in% names(as.list(match.call()));
den <- 1 -", pdens, "(H, ", argp, ");
if (logarg && log) res <-", ddens, "(x, ", argd, ") - log(den)
else res <-", ddens, "(x, ", argd, ")/den;
res[i] <- 0; return(res)}"))
}
return(f)
} |
randomizer <- function(
dataset, vars,
conditions = c("A", "B"),
blocks = NULL, probs = NULL,
label = ".conditions",
seed = 1234, data_filter = "",
na.rm = FALSE,
envir = parent.frame()
) {
df_name <- if (is_string(dataset)) dataset else deparse(substitute(dataset))
if (!radiant.data::is_empty(blocks)) {
vars <- c(vars, blocks)
}
dataset <- get_data(dataset, vars, filt = data_filter, na.rm = na.rm, envir = envir)
seed <- gsub("[^0-9]", "", seed)
if (!radiant.data::is_empty(seed)) set.seed(seed)
if (radiant.data::is_empty(probs)) {
probs <- length(conditions) %>% {rep(1/., .)}
} else if (length(probs) == 1) {
probs <- rep(probs, length(conditions))
} else if (length(probs) != length(conditions)) {
probs <- NULL
}
if (length(blocks) > 0) {
blocks_vct <- do.call(paste, c(select_at(dataset, .vars = blocks), sep = "-"))
cond <- randomizr::block_ra(blocks = blocks_vct, conditions = conditions, prob_each = probs) %>%
as.data.frame() %>%
set_colnames(label)
} else {
cond <- randomizr::complete_ra(N = nrow(dataset), conditions = conditions, prob_each = probs) %>%
as.data.frame() %>%
set_colnames(label)
}
dataset <- bind_cols(cond, dataset)
rm(cond, envir)
as.list(environment()) %>% add_class("randomizer")
}
summary.randomizer <- function(object, dec = 3, ...) {
if (radiant.data::is_empty(object$blocks)) {
cat("Random assignment (simple random)\n")
} else {
cat("Random assignment (blocking)\n")
}
cat("Data :", object$df_name, "\n")
if (!radiant.data::is_empty(object$data_filter)) {
cat("Filter :", gsub("\\n", "", object$data_filter), "\n")
}
if (!radiant.data::is_empty(object$blocks)) {
cat("Variables :", setdiff(object$vars, object$blocks), "\n")
cat("Blocks :", object$blocks, "\n")
} else {
cat("Variables :", object$vars, "\n")
}
cat("Conditions :", object$conditions, "\n")
cat("Probabilities:", round(object$probs, dec), "\n")
if (!radiant.data::is_empty(object$seed)) {
cat("Random seed :", object$seed, "\n")
}
is_unique <- object$dataset[, -1, drop = FALSE] %>%
{ifelse(nrow(.) > nrow(distinct(.)), "Based on selected variables some duplicate rows exist", "Based on selected variables, no duplicate rows exist")}
cat("Duplicates :", is_unique, "\n\n")
cat("Assigment frequencies:\n")
if (radiant.data::is_empty(object$blocks_vct)) {
tab <- table(object$dataset[[object$label]])
} else {
tab <- table(object$blocks_vct, object$dataset[[object$label]])
}
tab %>% addmargins() %>% print()
cat("\nAssigment proportions:\n")
tab %>% prop.table() %>% round(dec) %>% print()
} |
library(shiny.fluent)
if (interactive()) {
items <- list(
list(text = "Files", key = "Files", href = "
list(text = "Folder 1", key = "f1", href = "
list(text = "Folder 2", key = "f2", href = "
list(text = "Folder 3", key = "f3", href = "
list(text = "Folder 4 (non-clickable)", key = "f4"),
list(text = "Folder 5", key = "f5", href = "
)
shinyApp(
ui = Breadcrumb(
items = items,
maxDisplayedItems = 3,
ariaLabel = "Breadcrumb with items rendered as links",
overflowAriaLabel = "More links"
),
server = function(input, output) {}
)
} |
decimal_date <- function(date)
UseMethod("decimal_date")
decimal_date.default <- function(date) {
if (any(!inherits(date, c("POSIXt", "POSIXct", "POSIXlt", "Date"))))
stop("date(s) not in POSIXt or Date format")
Y <- year(date)
start <- make_datetime(Y, 1L, 1L, tz = tz(date))
end <- make_datetime(Y + 1L, 1L, 1L, tz = tz(date))
sofar <- as.numeric(difftime(date, start, units = "secs"))
total <- as.numeric(difftime(end, start, units = "secs"))
Y + sofar/total
}
decimal_date.zoo <- function(date)
decimal_date(zoo::index(date))
date_decimal <- function(decimal, tz = "UTC") {
Y <- trunc(decimal)
start <- make_datetime(Y, 1L, 1L, tz = tz)
end <- make_datetime(Y + 1L, 1L, 1L, tz = tz)
seconds <- as.numeric(difftime(end, start, units = "secs"))
frac <- decimal - Y
end <- start + seconds*frac
return(end)
} |
readmulti.tps <- function(filelist, ... ){
tps.list <- filelist
readland.args <- list(...)
if(is.null(readland.args$specID)) readland.args$specID <- "None"
file.ext <- substr(tps.list, nchar(tps.list)-3, nchar(tps.list))
if(!all(file.ext%in%c(".tps", ".TPS")))
stop("File list includes files in a format other than tps, please ammend")
dt.dims <- sapply(1:length(tps.list), function(x){
dim(readland.tps(tps.list[x], warnmsg = F, ...))
}, simplify = T)
p1 <- dt.dims[1, 1]; k1 <- dt.dims[2, 1]; n1 <- dt.dims[3, 1]
if(any(dt.dims[1,]!=p1)) stop("Input tps files include different numbers of landmarks, please correct")
if(any(dt.dims[2,]!=k1)) stop("Input tps files include landmarks in different dimensions (2D and 3D), please correct")
all.lms <- NULL
for(f in 1:length(tps.list)){
lms <- two.d.array(readland.tps(tps.list[f], ...))
all.lms <- rbind(all.lms, lms)
}
all.lms <- arrayspecs(all.lms, p1, k1)
if(any(table(dimnames(all.lms)[3])!=1)) {
if(readland.args$specID != "imageID") {
dimnames(all.lms)[[3]] <- 1:dim(all.lms)[3]
} else {
warning("Input files seem to include repeated specimen names")
}
}
return(all.lms)
} |
pooling_ct <- function(table){
expvaltable = expval_table(table)
ind1 = apply(expvaltable,2,min)
ind2 = apply(expvaltable,2,which.min)
ncol = which.min(ind1)
nline = ind2[ncol]
vec_direction = c(ncol,nline)
while (expvaltable[nline,ncol]<2){
if (sum(table[nline,])/ncol(table) > sum(table[,ncol])/nrow(table)){
pooldim = 1
} else {
pooldim = 2
}
flag = which(dim(table)==2)
if (length(flag)==1){
pooldim = flag
} else if (length(flag)==2){
fisheroupas = 1
break
}
marge = apply(t(table),pooldim,sum)
marge[vec_direction[pooldim]] = max(marge) + 1
ind1 = min(marge)
ind2 = which.min(marge)
if (pooldim==1){
table[,ncol] = table[,ncol] + table[,ind2]
table = table[,-ind2]
} else {
table[nline,] = table[nline,] + table[ind2,]
table = table[-ind2,]
}
expvaltable = expval_table(table)
ind1 = apply(expvaltable,2,min)
ind2 = apply(expvaltable,2,which.min)
ncol = which.min(ind1)
nline = ind2[ncol]
vec_direction = c(ncol,nline)
}
table = as.matrix(table)
table
} |
yline <- 2.00
ymin <- -1.0
ymax <- 3.00
yfix <- FALSE
title <- "Chromosome 1"
ylabel <- "LOD Score"
cex.legend <- 0.7000
cex.axis <- 0.9000
tcl <- -0.3000
bw <- FALSE
na.rm <- TRUE
lgndtxt <- c("Trait1", "Trait2", "Trait3")
ltypes <- c(1,2,3)
my.colors <- c("black", "black", "black")
ptypes <- c(0, 0, 0) |
lsm_c_area_mn <- function(landscape, directions = 8) {
landscape <- landscape_as_list(landscape)
result <- lapply(X = landscape,
FUN = lsm_c_area_mn_calc,
directions = directions)
layer <- rep(seq_along(result),
vapply(result, nrow, FUN.VALUE = integer(1)))
result <- do.call(rbind, result)
tibble::add_column(result, layer, .before = TRUE)
}
lsm_c_area_mn_calc <- function(landscape, directions, resolution = NULL){
area <- lsm_p_area_calc(landscape,
directions = directions,
resolution = resolution)
if (all(is.na(area$value))) {
return(tibble::tibble(level = "class",
class = as.integer(NA),
id = as.integer(NA),
metric = "area_mn",
value = as.double(NA)))
}
area_mean <- stats::aggregate(area[, 5], by = area[, 2], FUN = mean)
return(tibble::tibble(level = "class",
class = as.integer(area_mean$class),
id = as.integer(NA),
metric = "area_mn",
value = as.double(area_mean$value)))
} |
cum.residuals<-function(object,data=parent.frame(),modelmatrix=0,cum.resid=1,n.sim=500,
weighted.test=0,max.point.func=50,weights=NULL)
{
start.design<-1; silent <- 1; offsets <- NULL;
if (!(class(object)!="aalen" | class(object)!="timecox" | class(object)!="cox.aalen" ))
stop ("Must be output from aalen() timecox() or cox.aalen() functions\n")
if (class(object)=="timecox") if (object$method!="basic")
stop("Residuals available only for method=basic\n")
if (class(object)=="timecox") if (is.null(object$gamma)==FALSE)
stop("Residuals available only for timecox model with no const terms\n")
if (class(object)=="aalen") if (is.null(object$gamma)==FALSE)
stop("Residuals available only for Aalen model with no const terms\n")
if (is.null(object$residuals$dM)==TRUE) stop("Residuals not computed, add option residuals=1\n");
if (sum(modelmatrix)==0 && cum.resid==0)
stop("No modelmatrix or continous covariates given to cumulate residuals\n");
stratum <- attr(object,"stratum");
rate.sim <- 1;
weights1 <- NULL
if (class(object)=="cox.aalen") {
dcum<-apply(as.matrix(object$cum[,-1]),2,diff);
beta<-object$gamma;
coxaalen<-1;
weights1 <- attr(object,"weights")
offsets <- attr(object,"offsets");
rate.sim <- attr(object,"rate.sim");
} else { dcum<-0; beta<-0; coxaalen<-0; pg<-0;Z<-0; }
id<-attr(object,"id");
cluster<-attr(object,"cluster");
formula<-attr(object,"Formula");
start.time<-attr(object,"start.time");
pers<-unique(id);
antpers<-length(pers);
clust<-unique(cluster);
antclust<-length(clust);
if (class(object)=="cox.aalen")
ldata<-aalen.des(formula,data,model="cox.aalen") else ldata<-aalen.des(formula,data)
X<-ldata$X; covar<-X; px<-ldata$px;
time<-attr(object,"start");
time2<-attr(object,"stop");
if (sum(time)==0) type <- "right" else type <- "counting"
status<-attr(object,"status");
if (is.null(weights)) weights <- rep(1,nrow(X));
if (is.null(weights1)) weights1 <- rep(1,nrow(X));
if (is.null(offsets)) offsets <- rep(0,nrow(X));
if (length(weights)!=nrow(X)) stop("Lengths of weights and data do not match\n");
if (length(weights1)!=nrow(X)) stop("Lengths of weights from aalen/cox.aalen and data do not match\n");
if (coxaalen==1) {
Z<-ldata$Z;
covnamesZ<-ldata$covnamesZ;
pg<-ncol(Z);
} else Z <- 0
Ntimes <- sum(status);
if (sum(modelmatrix)==0) {modelmatrix<-0;model<-0;pm<-1;} else
{model<-1; modelmatrix<-as.matrix(modelmatrix); pm<-ncol(modelmatrix);
test<-matrix(0,n.sim,3*pm); testOBS<-rep(0,2*pm);
covnames<-colnames(modelmatrix);
}
times<-c(start.time,time2[status==1]);
times<-sort(times);
antpers=length(unique(id));
ntot<-nrow(X);
lmgresids<-length(object$residuals$time);
ot<-order(-time2,status==1);
time2<-time2[ot];
status<-status[ot];
X<-as.matrix(X[ot,])
if (coxaalen==1) Z<-as.matrix(Z[ot,])
if (model==1) modelmatrix<-as.matrix(modelmatrix[ot,])
start <- time[ot]
stop<-time2;
cluster<-cluster[ot]
id<-id[ot];
weightsmg <- weights[ot]
weights <- weights1[ot]
offsets <- offsets[ot]
entry=rep(-1,ntot);
ntot <- nrow(X);
if (coxaalen==1) { gamma.iid<-object$gamma.iid
covar<-cbind(X,Z);
cnames<- c(ldata$covnamesX,ldata$covnamesZ)
if (ncol(covar)==length(cnames)) colnames(covar)<-cnames
ptot<-px+pg;
} else { covar<-covar; ptot<-px; gamma.iid<-0; }
covnames0<-colnames(covar);
if (is.null(covnames0)) covnames0 <- rep("",ptot);
antal<-0; maxval<-0; intercept<-0; antal2<-0; maxval2<-0;
xvals<-list(); ant<-rep(0,ptot);
for (i in 1:ptot) xvals[[i]]<-c();
rani<-round(runif(1)*10000);
keepcumz<-c(); k<-0
for (j in 1:ptot) {
z<-unique(covar[,j]); z<-sort(z);
if (length(z)> max.point.func) z <- quantile(z,probs=seq(0,1,length=max.point.func))
antal<-antal+1; ant[j]<-length(z);
if (ant[j]>2) { k<-k+1; keepcumz<-c(keepcumz,j); xvals[[k]]<-z;
maxval<-max(maxval,length(z)); }
}
if (sum(keepcumz)==0 && cum.resid==1)
stop(" No continous covariates given to cumulate residuals \n");
pcumz<-length(keepcumz);
uni.test<-matrix(0,n.sim,pcumz);
univar.proc<-matrix(0,maxval,pcumz);
robvarcumz<-matrix(0,maxval,pcumz);
sim.univar.proc<-matrix(0,maxval,50*pcumz);
time.proc<-matrix(0,lmgresids,2);
sim.time.proc<-matrix(0,lmgresids,50);
simcumz<-matrix(0,n.sim,pcumz);
xval<-matrix(0,maxval,pcumz);
k<-1;
for (i in keepcumz) {xval[1:ant[i],k]<-xvals[[k]]; k<-k+1;}
unitime.test<-time.test<-mult.test<-multtime.test<- matrix(0,n.sim,2*pcumz);
unitime.testOBS<-uni.testOBS<-time.testOBS<-mult.testOBS<-
multtime.testOBS<-rep(0,pcumz);
inXorZ<-rep(0,pcumz);
if (pcumz>0) {
antX<-(sum(ant[1:px]>2))
if (antX>0) {inX<-(1:px)[(ant[1:px]>2)]; inXorZ[1:antX]<-1} else {inX<-c();}
if (coxaalen==1) {inZ<-(1:pg)[(ant[(px+1):(px+pg)]>2)]; } else inZ<-c()
inXZ<-c(inX,inZ);
inXZ<-inXZ-1
} else {inXZ<-0; inXorZ<-0}
ant<-ant[keepcumz];
Ut<- cummgt<- robvarcum <- matrix(0,lmgresids,pm+1);
simUt<-matrix(0,lmgresids,pm*50); test<-matrix(0,n.sim,3*pm);
testOBS <- rep(0,3*pm);
dNit <- 0
if (coxaalen==1) dNit <- object$residuals$dNit
mgout<- .C("mgresid",
as.double(X),as.integer(ntot),as.integer(px),
as.integer(antpers),as.double(start),as.double(stop),
as.integer(status),as.integer(id),as.double(object$residuals$time),
as.integer(lmgresids),as.double(object$residuals$dM),as.integer(n.sim),
as.double(xval), as.integer(ant), as.double(univar.proc),
as.double(time.proc),as.double(sim.univar.proc), as.double(sim.time.proc),
as.double(uni.test),as.double(uni.testOBS), as.double(time.test),
as.double(time.testOBS),as.double(unitime.test), as.double(unitime.testOBS),
as.double(modelmatrix),as.integer(model), as.integer(pm),
as.double(cummgt),as.double(dNit), as.double(robvarcum),
as.double(testOBS),as.double(test), as.double(simUt),
as.double(Ut),as.integer(cum.resid), as.integer(maxval),
as.integer(start.design),as.integer(coxaalen), as.double(dcum),
as.double(beta),as.double(Z), as.integer(pg),
as.double(gamma.iid),as.integer(cluster), as.integer(antclust),
as.double(robvarcumz), as.double(simcumz), as.integer(inXZ),
as.integer(inXorZ),as.integer(pcumz), as.integer(entry),
as.integer(stratum),as.integer(silent),as.double(weights1),
as.double(offsets),as.integer(rate.sim),as.double(weights),
as.integer(weighted.test))
if (model==1) {
cum<-matrix(mgout[[28]],lmgresids,pm+1);
robvar.cum<-matrix(mgout[[30]],lmgresids,pm+1);
var.cum<-robvar.cum; Ut<-matrix(mgout[[34]],lmgresids,pm+1);
colnames(Ut)<-colnames(cum)<-colnames(var.cum)<- colnames(robvar.cum)<- c("time",covnames)
test.procBeq0<-Ut;
simUt<-matrix(mgout[[33]],lmgresids,50*pm);
UIt<-list();
for (i in (0:49)*pm) {
UIt[[i/pm+1]]<-as.matrix(simUt[,i+(1:pm)]);
}
testOBS<-mgout[[31]];
test<-matrix(mgout[[32]],n.sim,3*pm);
testval<-c(); unifCI<-c();
for (i in 1:(2*pm)) testval<-c(testval,pval(test[,i],testOBS[i]))
for (i in 1:pm) unifCI<-as.vector(c(unifCI,percen(test[,2*pm+i],0.95)));
obs.testBeq0<-as.vector(testOBS[1:pm]);
obs.testBeq0.is<-as.vector(testOBS[(pm+1):(2*pm)]);
pval.testBeq0<-as.vector(testval[1:pm]);
pval.testBeq0.is<-as.vector(testval[(pm+1):(2*pm)]);
sim.testBeq0<-test[,(2*pm+1):(3*pm)];
sim.test.procBeq0<-UIt;
names(unifCI)<- names(pval.testBeq0)<- names(obs.testBeq0)<-
names(pval.testBeq0.is)<- names(obs.testBeq0.is)<- covnames
} else {
cum<-robvar.cum<-test<-unifCI<-Ut<-UIt<-pval.testBeq0<-
pval.testBeq0.is<-obs.testBeq0<-obs.testBeq0.is<-sim.testBeq0<-NULL;
}
if (cum.resid>=1) {
univar.p<-matrix(mgout[[15]],maxval,pcumz)
robvarcumz<-matrix(mgout[[46]],maxval,pcumz)
simcumz<-matrix(mgout[[47]],n.sim,pcumz)
univar.proc<-list();
for (i in 1:pcumz) {
univar.proc[[i]]<-cbind(xvals[[i]],univar.p[1:ant[i],i]);
colnames(univar.proc[[i]])<-c(covnames0[keepcumz[i]],"cum. martingale residual");
}
Uiz<-matrix(mgout[[17]],maxval,50*pcumz);
UIz<-list();
k<-1;
for (i in 1:pcumz) { UIz[[i]]<-matrix(Uiz[1:ant[i],i+(0:49)*pcumz],ncol=50); k<-k+1;}
uni.test<-matrix(mgout[[19]],n.sim,pcumz)
uni.test<-as.matrix(uni.test);
uni.testOBS<-mgout[[24]][1:pcumz];
testval<-c();
for (i in 1:pcumz) testval<-c(testval,pval(uni.test[,i],uni.testOBS[i]))
unifCIz<-c()
for (i in 1:pcumz) unifCIz<-c(unifCIz,percen(simcumz[,i],0.95))
uni.pval<-testval
names(uni.testOBS)<-names(uni.pval)<-colnames(uni.test)<-covnames0[keepcumz];
} else { unifCIz<-uni.testOBS<-uni.pval<-proc.cumz<-UIz<-
unitime.pval<-unitime.testOBS<-NULL;}
ud<-list(cum=cum,robvar.cum=robvar.cum,robvar.cumz=robvarcumz,
pval.testBeq0=pval.testBeq0, obs.testBeq0=obs.testBeq0,
pval.testBeq0.is=pval.testBeq0.is, obs.testBeq0.is=obs.testBeq0.is,
sim.testBeq0=sim.testBeq0, procBeq0=Ut,sim.test.procBeq0=UIt,
conf.band=unifCI, conf.band.cumz=unifCIz,
obs.test=uni.testOBS,pval.test=uni.pval, sim.test=uni.test,
proc.cumz=univar.proc,sim.test.proccumz=UIz)
attr(ud,"Call")<-call;
class(ud)<-"cum.residuals"
return(ud);
}
"print.cum.residuals"<- function (x,...)
{
object <- x; rm(x);
if (!inherits(object, 'cum.residuals')) stop ("Must be an MG resid object")
cat(" Call: \n")
dput(attr(object, "Call"))
cat("\n")
}
"plot.cum.residuals" <- function (x,pointwise.ci=1,hw.ci=0,sim.ci=0,
robust=1, specific.comps=FALSE,level=0.05, start.time = 0,
stop.time = 0, add.to.plot=FALSE, mains=TRUE, main=NULL,
xlab=NULL,ylab ="Cumulative MG-residuals",ylim=NULL,
score=0,conf.band=FALSE,...)
{
object <- x; rm(x);
if (!inherits(object,'cum.residuals') ) stop ("Must be output from cum.residuals()")
if (score <2) {
B<-object$cum;
if (sum(B)==0) {
stop("To compute cumulative residuals provide model matrix \n");
}
}
if (score==2)
{
if (sum(object$obs.test)==0)
stop("To plot cumulative residuals vs. covariates, cum.resid=1");
}
if (score==0)
{
B<-object$cum;
if (robust>=1) V<-object$robvar.cum else V<-object$var.cum
p <- ncol(B);
if (!is.null(main)) { if (length(main)!=p) main <- rep(main,length(comp)); mains <- FALSE; }
if (!is.null(xlab)) { if (length(xlab)!=p) xlab <- rep(xlab,length(comp)); }
if (specific.comps==FALSE) comp<-(2:p) else comp<-specific.comps+1
if (stop.time==0) stop.time<-max(B[,1]);
med<-B[,1]<=stop.time & B[,1]>=start.time
B<-B[med,]; Bs<-B[1,]; B<-t(t(B)-Bs); B[,1]<-B[,1]+Bs[1];
V<-V[med,]; Vs<-V[1,]; V<-t( t(V)-Vs);
Vrob<-object$robvar.cum;
Vrob<-Vrob[med,]; Vrobs<-Vrob[1,]; Vrob<-t( t(Vrob)-Vrobs);
c.alpha<- qnorm(1-level/2)
for (v in comp)
{
c.alpha<- qnorm(1-level/2)
est<-B[,v];ul<-B[,v]+c.alpha*V[,v]^.5;nl<-B[,v]-c.alpha*V[,v]^.5;
if (add.to.plot==FALSE)
{
if (is.null(xlab)) xlabl <- "Time" else xlabl <- xlab[v]
if (is.null(ylim)) plot(B[,1],est,ylim=1.05*range(ul,nl),type="s",xlab=xlabl,ylab=ylab,...)
else plot(B[,1],est,ylim=ylim,type="s",xlab=xlabl,ylab=ylab)
if (!is.null(main)) title(main=main[i]);
if (mains==TRUE) title(main=colnames(B)[v]);
} else lines(B[,1],est,type="s");
if (pointwise.ci>=1) {
lines(B[,1],ul,lty=pointwise.ci,type="s");
lines(B[,1],nl,lty=pointwise.ci,type="s");
}
if (robust>=1) {
lines(B[,1],ul,lty=robust,type="s");
lines(B[,1],nl,lty=robust,type="s");
}
if (hw.ci>=1) {
if (level!=0.05) cat("Hall-Wellner bands only 95 % \n");
tau<-length(B[,1])
nl<-B[,v]-1.27*V[tau,v]^.5*(1+V[,v]/V[tau,v])
ul<-B[,v]+1.27*V[tau,v]^.5*(1+V[,v]/V[tau,v])
lines(B[,1],ul,lty=hw.ci,type="s");
lines(B[,1],nl,lty=hw.ci,type="s");
}
if (sim.ci>=1) {
if (level!=0.05) c.alpha<-percen(object$sim.testBeq0[,v-1],1-level)
else c.alpha<-object$conf.band[v-1];
nl<-B[,v]-c.alpha*Vrob[,v]^.5; ul<-B[,v]+c.alpha*Vrob[,v]^.5;
lines(B[,1],ul,lty=sim.ci,type="s");
lines(B[,1],nl,lty=sim.ci,type="s");
}
abline(h=0)
}
}
else if (score==1)
{
dim1<-ncol(object$procBeq0)
if (sum(specific.comps)==FALSE) comp<-2:dim1 else comp<-specific.comps+1
if (!is.null(main)) { if (length(main)==1) main <- rep(main,length(comp)); mains <- FALSE; }
if (!is.null(xlab)) { if (length(xlab)==1) xlab <- c("time",rep(xlab,length(comp))); }
for (i in comp)
{
ranyl<-range(object$procBeq0[,i]);
for (j in 1:50) ranyl<-range(c(ranyl,(object$sim.test.procBeq0[[j]])[,i-1]));
mr<-max(abs(ranyl));
if (add.to.plot==FALSE)
{
if (is.null(xlab)) xlabl <- "Time" else xlabl <- xlab[i]
if (!is.null(ylim))
plot(object$procBeq0[,1],object$procBeq0[,i],type="s",
ylim=ylim,lwd=2,xlab=xlabl,ylab=ylab,...)
else
plot(object$procBeq0[,1],object$procBeq0[,i],type="s",
ylim=c(-mr,mr),lwd=2,xlab=xlabl,ylab=ylab,...)
if (!is.null(main)) title(main=main[i]);
if (mains==TRUE) title(main=colnames(B)[i]);
}
else lines(object$procBeq0[,1],object$procBeq0[,i],type="s")
for (j in 1:50)
lines(object$procBeq0[,1],as.matrix(object$sim.test.procBeq0[[j]])[,i-1],
col="grey",lwd=1,lty=1,type="s")
lines(object$procBeq0[,1],object$procBeq0[,i],lwd=2,type="s")
}
}
else if (score==2)
{
dim1<-length(object$obs.test)
if (sum(specific.comps)==FALSE) comp<-1:dim1 else comp<-specific.comps
if (!is.null(xlab)) { if (length(xlab)==1) xlab <- rep(xlab,length(comp)); }
if (!is.null(main)) { if (length(main)==1) main <- rep(main,length(comp)); mains <- FALSE; }
v <- 0
for (i in comp)
{
v <- v+1
if (nrow(object$proc.cumz[[i]])==1) TYPE<-"p" else TYPE<-"l";
if (is.null(xlab)) xlabl <- colnames(object$proc.cumz[[v]])[1] else xlabl <- xlab[i]
if (TYPE=="l")
{
ranyl<-range(object$proc.cumz[[i]][,2]);
for (j in 1:50) ranyl<-range(c(ranyl,(object$sim.test.proccumz[[i]])[,j]));
mr<-max(abs(ranyl));
if (add.to.plot==FALSE)
{
if (!is.null(ylim))
plot(object$proc.cumz[[i]][,1],object$proc.cumz[[i]][,2],type=TYPE,
ylim=ylim,lwd=2,xlab=xlabl,ylab=ylab,...)
else
plot(object$proc.cumz[[i]][,1],object$proc.cumz[[i]][,2],type=TYPE,
ylim=c(-mr,mr),lwd=2,xlab=xlabl,ylab=ylab,...)
}
else
lines(object$proc.cumz[[i]][,1],object$proc.cumz[[i]][,2],type="l")
if (!is.null(main)) title(main=main[i]);
if (mains==TRUE) title(main=colnames(object$proc.cumz[[i]])[1]);
if (TYPE=="l") for (j in 1:50)
lines(object$proc.cumz[[i]][,1],object$sim.test.proccumz[[i]][,j],
col="grey",lwd=1,lty=1,type="l")
if (TYPE=="p") for (j in 1:50)
points(object$proc.cumz[[i]][,1],object$sim.test.proccumz[[i]][,j],pch=".")
lines(object$proc.cumz[[i]][,1],object$proc.cumz[[i]][,2],lwd=2);
}
if (conf.band==TRUE) {
col.alpha<-0.2
col.ci<-"darkblue"
lty.ci<-2
if (col.alpha==0) col.trans <- col.ci
else
col.trans <- sapply(col.ci, FUN=function(x) do.call(rgb,as.list(c(col2rgb(x)/255,col.alpha))))
if (level!=0.05) c.alpha<-percen(object$sim.test[,i],1-level)
else c.alpha<-object$conf.band.cumz[i];
t<-object$proc.cumz[[i]][,1]
ci<-c.alpha*object$robvar.cumz[1:length(t),i]^.5
lines(t,ci , lwd=1, col=col.ci, lty=lty.ci)
lines(t,-ci , lwd=1, col=col.ci, lty=lty.ci)
tt <- c(t, rev(t))
yy <- c(ci, rev(-ci))
polygon(tt,yy, col=col.trans, lty=0)
}
}
}
}
"summary.cum.residuals" <- function (object,digits=3,...)
{
if (!inherits(object, 'cum.residuals')) stop ("Must be an cum.residuals object")
cat("Test for cumulative MG-residuals \n\n")
mtest<-(sum(object$conf.band)>0)
if (mtest==FALSE) {
cat("Grouped cumulative residuals not computed, you must provide\n")
cat("modelmatrix to get these (see help) \n\n")
}
if (mtest==TRUE) {
test0<-cbind(object$obs.testBeq0,object$pval.testBeq0)
test0.is<-cbind(object$obs.testBeq0.is,object$pval.testBeq0.is)
colnames(test0)<- c("sup| hat B(t) |","p-value H_0: B(t)=0")
colnames(test0.is)<- c("int ( B(t) )^2 dt","p-value H_0: B(t)=0")
cat("Grouped Residuals consistent with model \n\n")
prmatrix(round(test0,digits))
cat("\n")
prmatrix(round(test0.is,digits))
cat("\n")
}
cumtest<-!is.null(object$obs.test)
if (cumtest==FALSE) {
cat("Cumulative tests versus covariates not computed \n\n")
cat("cum.resid=1 to compute these \n\n");
}
if (cumtest==TRUE) {
test0<-cbind(object$obs.test,object$pval.test)
colnames(test0)<- c("sup| hat B(t) |","p-value H_0: B(t)=0")
cat("Residual versus covariates consistent with model \n\n")
prmatrix(round(test0,digits))
}
cat("\n");
} |
PlotRsmOperatingCharacteristics <- function(mu,
lambda,
nu,
zeta1,
lesDistr,
relWeights = 0,
OpChType = "ALL",
legendPosition = c(1,0),
legendDirection = "horizontal",
legendJustification = c(0,1),
nlfRange = NULL,
llfRange = NULL,
nlfAlpha = NULL){
if (missing(zeta1)) zeta1 <- array(-3, dim = length(mu))
if (!all(c(length(mu) == length(lambda), length(mu) == length(nu), length(mu) == length(zeta1))))
stop("Parameters mu, lambda, nu and zeta1 have different lengths.")
lesWghtDistr <- UtilLesionWeightsDistr(length(lesDistr), relWeights)
lesDistr <- UtilLesionDistr(lesDistr)
plotStep <- 0.01
plotStep <- 0.1
zeta <- array(list(), dim = length(mu))
for (i in 1:length(mu)) zeta[[i]] <- seq(from = zeta1[i], to = max(mu)+5, by = plotStep)
ROCPlot <- NA
FROCPlot <- NA
AFROCPlot <- NA
wAFROCPlot <- NA
PDFPlot <- NA
ROCPoints <- data.frame(FPF = NULL, TPF = NULL, Treatment = NULL, stringsAsFactors = FALSE)
ROCDashes <- data.frame(FPF = NULL, TPF = NULL, Treatment = NULL, stringsAsFactors = FALSE)
FROCPoints <- data.frame(NLF = NULL, LLF = NULL, Treatment = NULL, stringsAsFactors = FALSE)
AFROCPoints <- data.frame(FPF = NULL, LLF= NULL, Treatment = NULL, stringsAsFactors = FALSE)
AFROCDashes <- data.frame(FPF = NULL, LLF= NULL, Treatment = NULL, stringsAsFactors = FALSE)
wAFROCPoints <- data.frame(FPF = NULL, wLLF= NULL, Treatment = NULL, stringsAsFactors = FALSE)
wAFROCDashes <- data.frame(FPF = NULL, wLLF= NULL, Treatment = NULL, stringsAsFactors = FALSE)
abnPDFPoints <- data.frame(pdf = NULL, highestZSample = NULL, Treatment = NULL, stringsAsFactors = FALSE)
norPDFPoints <- data.frame(pdf = NULL, highestZSample = NULL, Treatment = NULL, stringsAsFactors = FALSE)
aucROC <- rep(NA, length(mu));aucAFROC <- aucROC;aucwAFROC <- aucROC;aucFROC <- aucROC;lambdaP <- lambda
nuP <- nu
for (i in 1:length(mu)){
if (mu[i] <= 0 ) stop("mu must be greater than zero")
if (lambda[i] < 0 ) stop("lambda must be greater than zero")
if (nu[i] < 0 ) stop("nu must be greater than zero")
lambdaP[i] <- lambda[i] / mu[i]
if (abs(nu[i] * mu[i]) <= 1e-6 ) nuP[i] <- 1e-6 else nuP[i] <- (1-exp(-nu[i] * mu[i]))
FPF <- sapply(zeta[[i]], xROC, lambdaP = lambdaP[i])
TPF <- sapply(zeta[[i]], yROC, mu = mu[i], lambdaP = lambdaP[i], nuP = nuP[i], lesDistr = lesDistr)
NLF <- sapply(zeta[[i]], xFROC, lambdaP = lambdaP[i])
LLF <- sapply(zeta[[i]], yFROC, mu = mu[i], nuP = nuP[i])
maxFPF <- xROC(-20, lambdaP[i])
if( OpChType == "ALL" || OpChType == "ROC"){
ROCPoints <- rbind(ROCPoints, data.frame(FPF = FPF,
TPF = TPF,
Treatment = as.character(i),
stringsAsFactors = FALSE))
ROCDashes <- rbind(ROCDashes, data.frame(FPF = c(FPF[1], 1),
TPF = c(TPF[1], 1),
Treatment = as.character(i),
stringsAsFactors = FALSE))
maxTPF <- yROC(-20, mu[i], lambdaP[i], nuP[i], lesDistr)
AUC <- integrate(y_ROC_FPF, 0, maxFPF, mu = mu[i], lambdaP = lambdaP[i], nuP = nuP[i], lesDistr =lesDistr)$value
aucROC[i] <- AUC + (1 + maxTPF) * (1 - maxFPF) / 2
}
if( OpChType == "ALL" || OpChType == "FROC"){
FROCPoints <- rbind(FROCPoints, data.frame(NLF = NLF,
LLF = LLF,
Treatment = as.character(i),
stringsAsFactors = FALSE))
if (is.null(nlfAlpha)){
maxNLF <- max(NLF)
aucFROC[i] <- integrate(intFROC, 0, maxNLF, mu= mu[i], lambdaP = lambdaP[i], nuP = nuP[i])$value
}else{
maxNLF <- max(NLF)
if (nlfAlpha <= maxNLF){
aucFROC[i] <- integrate(intFROC, 0, nlfAlpha, mu= mu[i], lambdaP = lambdaP[i], nuP = nuP[i])$value
}else{
stop("nlfAlpha cannot be greater than the maximum of NLF.")
}
}
}
if( OpChType == "ALL" || OpChType == "AFROC"){
AFROCPoints <- rbind(AFROCPoints, data.frame(FPF = FPF,
LLF = LLF,
Treatment = as.character(i),
stringsAsFactors = FALSE))
AFROCDashes <- rbind(AFROCDashes, data.frame(FPF = c(FPF[1], 1),
LLF = c(LLF[1], 1),
Treatment = as.character(i),
stringsAsFactors = FALSE))
maxLLF <- yFROC(-20, mu[i], nuP[i])
AUC <- integrate(y_AFROC_FPF, 0, maxFPF, mu = mu[i], lambdaP = lambdaP[i], nuP = nuP[i])$value
aucAFROC[i] <- AUC + (1 + maxLLF) * (1 - maxFPF) / 2
}
if( OpChType == "ALL" || OpChType == "wAFROC"){
wLLF <- sapply(zeta[[i]], ywAFROC, mu[i], nuP[i], lesDistr, lesWghtDistr)
wAFROCPoints <- rbind(wAFROCPoints, data.frame(FPF = FPF,
wLLF = wLLF,
Treatment = as.character(i),
stringsAsFactors = FALSE))
wAFROCDashes <- rbind(wAFROCDashes, data.frame(FPF = c(FPF[1], 1),
wLLF = c(wLLF[1], 1),
Treatment = as.character(i),
stringsAsFactors = FALSE))
maxWLLF <- ywAFROC(-20, mu[i], nuP[i], lesDistr, lesWghtDistr)
AUC <- integrate(y_wAFROC_FPF, 0, maxFPF, mu = mu[i], lambdaP = lambdaP[i], nuP = nuP[i], lesDistr, lesWghtDistr)$value
aucwAFROC[i] <- AUC + (1 + maxWLLF) * (1 - maxFPF) / 2
}
if( OpChType == "ALL" || OpChType == "pdfs"){
deltaFPF <- FPF[1:(length(FPF) - 1)] - FPF[2:length(FPF)]
if( OpChType == "ALL" || OpChType == "pdfs"){
pdfNor <- deltaFPF / plotStep
norPDFPoints <- rbind(norPDFPoints,
data.frame(pdf = pdfNor[pdfNor > 1e-6],
highestZSample = zeta[[i]][-1][pdfNor > 1e-6],
Treatment = as.character(i),
class = "non-diseased",
stringsAsFactors = FALSE))
deltaTPF <- TPF[1:(length(TPF) - 1)] - TPF[2:length(TPF)]
pdfAbn <- deltaTPF / plotStep
abnPDFPoints <- rbind(abnPDFPoints,
data.frame(pdf = pdfAbn[pdfAbn > 1e-6],
highestZSample = zeta[[i]][-1][pdfAbn > 1e-6],
Treatment = as.character(i),
class = "diseased",
stringsAsFactors = FALSE))
}
}
}
if( OpChType == "ALL" || OpChType == "ROC") {
ROCPlot <- with(ROCPoints, {
ggplot(data = ROCPoints) +
geom_line(aes(x = FPF, y = TPF, color = Treatment)) +
geom_line(data = ROCDashes, aes(x = FPF, y = TPF, color = Treatment), linetype = 2) +
theme(legend.position = legendPosition, legend.direction = legendDirection, legend.justification = c(1, 0))
})
}
if( OpChType == "ALL" || OpChType == "FROC"){
FROCPlot <- with(FROCPoints, {
ggplot(data = FROCPoints) +
geom_line(aes(x = NLF, y = LLF, color = Treatment)) +
scale_x_continuous(expand = c(0, 0), limits = nlfRange) +
scale_y_continuous(expand = c(0, 0), limits = llfRange) +
theme(legend.position = legendPosition, legend.direction = legendDirection, legend.justification = c(1, 0))
})
}
if( OpChType == "ALL" || OpChType == "AFROC"){
AFROCPlot <- with(AFROCPoints, {
ggplot(data = AFROCPoints) +
geom_line(aes(x = FPF, y = LLF , color = Treatment)) +
geom_line(data = AFROCDashes, aes(x = FPF, y = LLF, color = Treatment), linetype = 2) +
theme(legend.position = legendPosition, legend.direction = legendDirection, legend.justification = c(1, 0))
}
)
}
if( OpChType == "ALL" || OpChType == "wAFROC"){
wAFROCPlot <- with(wAFROCPoints, {
ggplot(data = wAFROCPoints) +
geom_line(aes(x = FPF, y = wLLF , color = Treatment)) +
geom_line(data = wAFROCDashes, aes(x = FPF, y = wLLF, color = Treatment), linetype = 2) +
theme(legend.position = legendPosition, legend.direction = legendDirection, legend.justification = c(1, 0))
})
}
if( OpChType == "ALL" || OpChType == "pdfs"){
if (legendPosition == "top" || legendPosition == "bottom"){
legendDirection = "horizontal"
}else{
legendDirection = "vertical"
}
PDFPoints <- rbind(norPDFPoints, abnPDFPoints)
PDFPlot <- with(PDFPoints, {
ggplot(data = PDFPoints,
aes(x = highestZSample, y = pdf, color = Treatment, linetype = class)) +
geom_line() + theme(legend.position = legendPosition, legend.box = legendDirection) +
labs(x = "Highest Z Sample")
})
}
return(list(
ROCPlot = ROCPlot,
AFROCPlot = AFROCPlot,
wAFROCPlot = wAFROCPlot,
FROCPlot = FROCPlot,
PDFPlot = PDFPlot,
aucROC = aucROC,
aucAFROC = aucAFROC,
aucwAFROC = aucwAFROC,
aucFROC = aucFROC
))
}
is.wholenumber <- function(x) round(x) == x |
BF=function(data,group){
n=tapply(data, group, length)
k=length(tapply(data, group, length))
xbar=tapply(data, group, mean)
var=tapply(data, group, var)
B=sum(n*(xbar-mean(data))^2)/sum((1-(n/sum(n)))*var);
df1=sum((1-(n-sum(n)))*var)^2;
df2=sum(((1-(n-sum(n)))^2*(var)^2)/(n-1));
df=(df1/df2);
pvalue=1-pf(B,k-1,df);
result=matrix(c(round(B,digits=4),round(k-1),round(pvalue,digits=4)))
rownames(result)=c("Test Statistic","df","p-value")
colnames(result)=c("Brown-Forsythe")
return(t(result))
} |
link_categorical_ch <- function(x, refcat = 1, return_refcat = FALSE) {
stopifnot(length(dim(x)) == 3)
x_tosweep <- if (return_refcat) {
x
} else {
slice(x, 3, -refcat, drop = FALSE)
}
ndraws <- dim(x)[1]
nobsv <- dim(x)[2]
ncat <- dim(x)[3]
log(aperm(
array(
sapply(seq_len(nobsv), function(i) {
slice(x_tosweep, 2, i) / slice(slice(x, 2, i), 2, refcat)
}, simplify = "array"),
dim = c(ndraws, ncat - !return_refcat, nobsv)
),
perm = c(1, 3, 2)
))
}
environment(link_categorical_ch) <- as.environment(asNamespace("brms")) |
htt <- function(data, indices){
d <- data[indices,]
y <- d[,1]
pis <- d[,2]
return(pis^{-1} %*% as.vector(y))
} |
test_that("quansijac error", {
Phi_fn <- function(theta, lambda, alpha) 2 * theta + alpha * lambda
Psi_fn <- function(theta, lambda, alpha) 2 * lambda + alpha * theta
fake_fn1 <- function(theta) 1
fake_fn2 <- function(x, y) 1
res <- try(semislv(1, 1, Phi_fn, Psi_fn, alpha = 1))
expect_equal(class(res), "savespace")
expect_error(semislv(1, 1, fake_fn1, Psi_fn, alpha = 1))
expect_error(semislv(1, 1, fake_fn2, Psi_fn, alpha = 1))
res <- try(semislv(1, 1, Phi_fn, Psi_fn, jac = list(
Phi_der_theta_fn = function(theta, lambda, alpha) 2,
Phi_der_lambda_fn = function(theta, lambda, alpha) alpha,
Psi_der_theta_fn = function(theta, lambda, alpha) alpha,
Psi_der_lambda_fn = function(theta, lambda, alpha) 2
), method = "implicit", alpha = 1))
expect_equal(class(res), "savespace")
res <- try(semislv(theta = 1, lambda = 1, Phi_fn = Phi_fn, Psi_fn = Psi_fn, alpha = 1, jac = list(
Phi_der_theta_fn = function(theta, lambda, alpha) 2
), method = "implicit"))
expect_equal(class(res), "savespace")
expect_error(semislv(1, 1, Phi_fn, Psi_fn, jac = list(
Phi_der_theta_fn = function(x, lambda, alpha) 2,
), method = "implicit", alpha = 1))
ip1 <- semislv(1, 1, Phi_fn, Psi_fn, alpha = 1)
ip2 <- semislv(1, 1, Phi_fn, Psi_fn, jac = list(
Phi_der_theta_fn = function(theta, lambda, alpha) 2,
Phi_der_lambda_fn = function(theta, lambda, alpha) alpha,
Psi_der_theta_fn = function(theta, lambda, alpha) alpha,
Psi_der_lambda_fn = function(theta, lambda, alpha) 2
), alpha = 1)
expect_equal(ip1$theta, ip2$theta)
expect_equal(ip1$lambda, ip2$lambda)
it1 <- semislv(1, 1, Phi_fn, Psi_fn, method = "iterative", alpha = 1)
it2 <- semislv(1, 1, Phi_fn, Psi_fn, method = "iterative", jac = list(
Phi_der_theta_fn = function(theta, lambda, alpha) 2,
Phi_der_lambda_fn = function(theta, lambda, alpha) alpha,
Psi_der_theta_fn = function(theta, lambda, alpha) alpha,
Psi_der_lambda_fn = function(theta, lambda, alpha) 2
), alpha = 1)
expect_equal(it1$theta, it2$theta)
expect_equal(it1$lambda, it2$lambda)
}) |
library(metafor)
dat <- dat.bcg
dat <- escalc(measure = "RR", ai = tpos, bi = tneg, ci = cpos, di = cneg, data = dat)
dat$ablat[c(2, 4, 8)] <- NA
predMatrix <- make.predictorMatrix(dat)
predMatrix[, ] <- 0
predMatrix["ablat", c("yi", "year")] <- 1
impMethod <- make.method(dat)
impMethod["ablat"] <- "pmm"
impMethod
imp <- mice(dat, print = FALSE, predictorMatrix = predMatrix, method = impMethod, seed = 1234)
test_that("does not break metafor package", {
expect_silent(fit <- with(imp, rma(yi, vi, mods = ~ ablat + year)))
}) |
distribution.plot <- function(netfacs.data) {
plot.netfacs <- netfacs.data$result
plot.random <- netfacs.data$used.data$random.prob
plot.random <- plot.random[plot.netfacs$combination.size == 1, ]
plot.netfacs <- plot.netfacs[plot.netfacs$combination.size == 1, ]
distribution.plots <- lapply(1:nrow(plot.netfacs), function(y) {
x.data <- plot.netfacs[y, ]
ran.data <- data.frame(ran = plot.random[y, ])
xx.plot <- ggplot(
data = ran.data,
mapping = aes(x = .data$ran)
) +
geom_density(color = "black", fill = "lightblue") +
xlim(0, max(c(plot.random, plot.netfacs$observed.prob)) + 0.05) +
theme_bw() +
geom_vline(xintercept = x.data$observed.prob, size = 1.2) +
ggtitle(x.data$combination)
return(xx.plot)
})
names(distribution.plots) <- plot.netfacs$combination
return(distribution.plots)
} |
selftest.sampd.tck1 <- function(){
options(guiToolkit="tcltk")
w <- gwindow(title = "Sampling distributions")
size(w) <- c(700, 450)
g <- ggroup(container=w, horizontal=FALSE, use.scrollwindow = TRUE)
gp1 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp1.1 <- ggroup(container = gp1, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("1) ", container = gp1.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("A sampling distribution can be best described as a...", container = gp1.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans1 <- c("(a) A sample of individuals from a parent population one wishes to make inference to. ",
"(b) An idealization, describing an infinite number of independent statistical estimates (e.g., arithmetic means) \ntaken from the same parent distribution, using the same sample size.",
"(c) A collection of statistics describing outcomes from a particular experiment. ",
"(d) A collection of random samples from a normal distribution. ")
f1 <- function(h,....){
if(tail(svalue(r1),1) == ans1[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r1),1)== ans1[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r1),1)== ans1[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r1),1)== ans1[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r1) <- character(0)
}
r1 <- gcheckboxgroup(ans1, container = gp1, checked = FALSE, where = "beginning", handler = f1)
gp2 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp2.1 <- ggroup(container = gp2, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("2) ", container = gp2.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("If the parent distribution is \u0059 ~ N(\u03bc, \u03c3\u00b2), then the sampling distribution of \u0232 will be: ", container = gp2.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans2 <- c("(a) \u0232 ~ N(\u0232, \u03c3\u00b2).",
"(b) \u0232 ~ N(\u03bc, \u03c3/n).",
"(c) \u0232 ~ N(\u03bc/n, \u03c3\u00b2).",
"(d) \u0232 ~ N(\u03bc, \u03c3\u00b2/n).")
f2 <- function(h,....){
if(tail(svalue(r2),1) == ans2[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r2),1)== ans2[4]){
gmessage(msg="Correct")
}
svalue(r2) <- character(0)
}
r2 <- gcheckboxgroup(ans2, container = gp2, checked = FALSE, where = "beginning", handler = f2)
gp3 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp3.1 <- ggroup(container = gp3, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("3) ", container = gp3.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("Which of the following describes the Central Limit Theorem?", container = gp3.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans3 <- c("(a) If Y ~ N(\u03bc, \u03c3\u00b2), then \u0232 ~ N(\u03bc/n, \u03c3\u00b2/n).",
"(b) If the sample size from Y is large, then the variance for the sampling distribution of \u0232 will be small.",
"(c) Even if Y is not normal, if the sample size from Y is large, then \u0232 will be approximately normal.",
"(d) None of the above.")
f3 <- function(h,....){
if(tail(svalue(r3),1) == ans3[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r3),1)== ans3[2]){
gmessage(msg="This does occur, but it is due to the Law of Large Numbers, not the Central Limit Theorem.", icon = "error")
}
if(tail(svalue(r3),1)== ans3[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r3),1)== ans3[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r3) <- character(0)
}
r3 <- gcheckboxgroup(ans3, container = gp3, checked = FALSE, where = "beginning", handler = f3)
gp4 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp4.1 <- ggroup(container = gp4, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("4) ", container = gp4.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("Which of the following statistics have sampling distributions?", container = gp4.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans4 <- c("(a) The sample mean",
"(b) The sample median",
"(c) The sample standard deviation.",
"(d) All of the above.")
f4 <- function(h,....){
if(tail(svalue(r4),1) == ans4[1]){
gmessage(msg="Partially correct", icon = "error")
}
if(tail(svalue(r4),1)== ans4[2]){
gmessage(msg="Partially correct", icon = "error")
}
if(tail(svalue(r4),1)== ans4[3]){
gmessage(msg="Partially correct", icon = "error")
}
if(tail(svalue(r4),1)== ans4[4]){
gmessage(msg="Correct. Any statistical estimator can have a sampling distribution.")
}
svalue(r4) <- character(0)
}
r4 <- gcheckboxgroup(ans4, container = gp4, checked = FALSE, where = "beginning", handler = f4)
gp5 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp5.1 <- ggroup(container = gp5, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("5) ", container = gp5.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from a normal parent distribution we to make inference to, Y, with sample size n. \nAssume that \u03bc\u2080 is equal to the mean of Y, \u03bc. That is, assume \u03bc = \u03bc\u2080. \nWhat is the sampling distribution of \u221an(\u0232 - \u03bc\u2080)/S, where S is the sample standard deviation.
", container = gp5.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans5 <- c("(a) N(0,1)",
"(b) F(n\u2082 - 1, n\u2082 - 1)",
"(c) t(n - 1)",
"(d) t(n)")
f5 <- function(h,....){
if(tail(svalue(r5),1) == ans5[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r5),1)== ans5[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r5),1)== ans5[3]){
gmessage(msg="Correct")
}
if(tail(svalue(r5),1)== ans5[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r5) <- character(0)
}
r5 <- gcheckboxgroup(ans5, container = gp5, checked = FALSE, where = "beginning", handler = f5)
gp6 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp6.1 <- ggroup(container = gp6, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("6) ", container = gp6.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("Given the assumptions in Question 5, what is the sampling distribution of \u221an(\u0232 - \u03bc\u2080)/\u03c3",
container = gp6.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans6 <- c("(a) N(0,1)",
"(b) F(n\u2082 - 1, n\u2082 - 1)",
"(c) t(n - 1)",
"(d) t(n)")
f6 <- function(h,....){
if(tail(svalue(r6),1) == ans6[1]){
gmessage(msg="Correct")
}
if(tail(svalue(r6),1)== ans6[2]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r6),1)== ans6[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r6),1)== ans6[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r6) <- character(0)
}
r6 <- gcheckboxgroup(ans6, container = gp6, checked = FALSE, where = "beginning", handler = f6)
gp7 <- gframe(container = g, spacing = 2, pos = 0, horizontal = FALSE)
gp7.1 <- ggroup(container = gp7, spacing = 2, pos = 0, horizontal = TRUE)
q <- glabel("7) ", container = gp7.1, horizontal = TRUE)
font(q) <- list(weight = "bold")
qq <- glabel("We sample from two normal distributions, Y\u2081 and Y\u2082, with sample sizes n\u2081 and n\u2082, respectively. \nWe assume that the variances of Y\u2081 and Y\u2082 are equal. \nWhat is the sampling distribution of the ratio of sample variances: S\u2081\u00b2/S\u2082\u00b2",
container = gp7.1, anchor = c(-1,1))
font(qq) <- list(family = "cambria", size = 11)
ans7 <- c("(a) N(0,1)",
"(b) F(n\u2081 - 1, n\u2082 - 1)",
"(c) t(n - 1)",
"(d) t(n)")
f7 <- function(h,....){
if(tail(svalue(r7),1) == ans7[1]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r7),1)== ans7[2]){
gmessage(msg="Correct")
}
if(tail(svalue(r7),1)== ans7[3]){
gmessage(msg="Incorrect", icon = "error")
}
if(tail(svalue(r7),1)== ans7[4]){
gmessage(msg="Incorrect", icon = "error")
}
svalue(r7) <- character(0)
}
r7 <- gcheckboxgroup(ans7, container = gp7, checked = FALSE, where = "beginning", handler = f7)
} |
install.packages("RTextTools")
library(RTextTools) |
cpsd <- function(x, window = nextpow2(sqrt(NROW(x))), overlap = 0.5,
nfft = ifelse(isScalar(window), window, length(window)),
fs = 1,
detrend = c("long-mean", "short-mean",
"long-linear", "short-linear",
"none")) {
pw <- pwelch(x, window, overlap, nfft, fs, detrend)
rv <- list(freq = pw$freq, cross = pw$cross)
rv
}
csd <- cpsd |
fssa20 <- function(n=1000,
x=33, p=runif(4, max=0.9),
set=(x^2+1)/2, all=TRUE,
shape=c(1,1)) {
rfq <- array(0, dim=rep(x, times=2))
for (i in seq(n))
rfq <- rfq + (ssa20(x, p, set, all, shape) > 1)
return(rfq/n)
}
fssa30 <- function(n=1000,
x=33, p=runif(6, max=0.6),
set=(x^3+1)/2, all=TRUE,
shape=c(1,1)) {
rfq <- array(0, dim=rep(x, times=3))
for (i in seq(n))
rfq <- rfq + (ssa30(x, p, set, all, shape) > 1)
return(rfq/n)
} |
SL.leekasso <- function (Y, X, newX, family, obsWeights, id, ...)
{
.SL.require("sva")
N <- length(Y)
mod <- cbind(rep.int(1, N), Y)
mod0 <- cbind(rep.int(1, N))
pValues <- sva::f.pvalue(t(X), mod, mod0)
index <- which(rank(pValues) <= 10)
lm1 <- lm(Y ~ ., data = X[, index])
pred <- predict.lm(lm1, newdata = newX[, index])
fit <- list(object = lm1, index = index)
class(fit) <- c("SL.leekasso")
out <- list(pred = pred, fit = fit)
return(out)
}
predict.SL.leekasso <- function(object, newdata, ...){
pred <- predict(object = object$object, newdata = newdata[, object$index], type = "response")
pred
} |
options(prompt = "> ", continue = "+ ", width = 70,
useFancyQuotes = FALSE, digits = 3)
library(rebmix)
data(galaxy)
galaxyest <- list(normal = NULL, lognormal = NULL, Weibull = NULL, gamma = NULL)
pdf <- c("normal", "lognormal", "Weibull", "gamma")
for (i in 1:4) {
galaxyest[[i]] <- REBMIX(Dataset = list(galaxy = galaxy),
Preprocessing = "histogram",
cmax = 10,
Criterion = "AIC",
pdf = pdf[i],
K = 7:20)
}
summary(galaxyest$normal)
summary(galaxyest$lognormal)
summary(galaxyest$Weibull)
summary(galaxyest$gamma)
plot(galaxyest$lognormal, pos = 1, what = c("pdf", "marginal pdf"), ncol = 2, npts = 1000)
a.theta1.all(galaxyest$lognormal, pos = 1)
a.theta2.all(galaxyest$lognormal, pos = 1) |
lav_mvreg_loglik_data <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
casewise = FALSE,
Sinv.method = "eigen") {
Y <- unname(Y); Q <- NCOL(Y); N <- NROW(Y)
X <- cbind(1, unname(eXo))
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(casewise) {
LOG.2PI <- log(2 * pi)
if(Sinv.method == "chol") {
cS <- chol(res.cov); icS <- backsolve(cS, diag(Q))
logdet <- -2 * sum(log(diag(icS)))
RES <- Y - X %*% Beta
DIST <- rowSums((RES %*% icS)^2)
} else {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = TRUE,
Sinv.method = Sinv.method)
logdet <- attr(res.cov.inv, "logdet")
RES <- Y - X %*% Beta
DIST <- rowSums(RES %*% res.cov.inv * RES)
}
loglik <- -(Q * LOG.2PI + logdet + DIST)/2
} else {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = TRUE,
Sinv.method = Sinv.method)
logdet <- attr(res.cov.inv, "logdet")
RES <- Y - X %*% Beta
TOTAL <- sum( rowSums(RES %*% res.cov.inv * RES) )
loglik <- -(N*Q/2)*log(2*pi) - (N/2)*logdet - (1/2)*TOTAL
}
loglik
}
lav_mvreg_loglik_samplestats <- function(sample.res.int = NULL,
sample.res.slopes = NULL,
sample.res.cov = NULL,
sample.mean.x = NULL,
sample.cov.x = NULL,
sample.nobs = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Q <- NCOL(sample.res.cov); N <- sample.nobs
LOG.2PI <- log(2 * pi)
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
sample.B <- rbind(matrix(sample.res.int, nrow = 1), t(sample.res.slopes))
sample.xx <- rbind( cbind(1, matrix(sample.mean.x, nrow = 1,)),
cbind(matrix(sample.mean.x, ncol = 1),
sample.cov.x + tcrossprod(sample.mean.x)) )
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = TRUE,
Sinv.method = Sinv.method)
logdet <- attr(res.cov.inv, "logdet")
} else {
logdet <- attr(res.cov.inv, "logdet")
if(is.null(logdet)) {
ev <- eigen(res.cov.inv, symmetric = TRUE, only.values = TRUE)
logdet <- -1 * sum(log(ev$values))
}
}
DIST1 <- sum(res.cov.inv * sample.res.cov)
Diff <- sample.B - Beta
DIST2 <- sum(res.cov.inv * crossprod(Diff, sample.xx) %*% Diff)
loglik <- -(N/2) * (Q*log(2*pi) + logdet + DIST1 + DIST2)
loglik
}
lav_mvreg_dlogl_dbeta <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); X <- cbind(1, unname(eXo))
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
RES <- Y - X %*% Beta
dbeta <- as.numeric( t(X) %*% RES %*% res.cov.inv )
dbeta
}
lav_mvreg_dlogl_drescov <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.cov = NULL,
res.int = NULL,
res.slopes = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); N <- NROW(Y); X <- cbind(1, unname(eXo))
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
RES <- Y - X %*% Beta
W.tilde <- crossprod(RES)/N
dres.cov <- -(N/2)* (res.cov.inv - (res.cov.inv %*% W.tilde %*% res.cov.inv))
dres.cov
}
lav_mvreg_dlogl_dvechrescov <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); N <- NROW(Y); X <- cbind(1, unname(eXo))
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
RES <- Y - X %*% Beta
W.tilde <- crossprod(RES)/N
dres.cov <- -(N/2)* (res.cov.inv - (res.cov.inv %*% W.tilde %*% res.cov.inv))
dvechres.cov <- as.numeric( lav_matrix_duplication_pre(
as.matrix(lav_matrix_vec(dres.cov)) ) )
dvechres.cov
}
lav_mvreg_scores_beta <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); Q <- NCOL(Y); X <- cbind(1, unname(eXo)); P <- NCOL(X)
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
RES <- Y - X %*% Beta
RES <- RES %*% res.cov.inv
SC.Beta <- X[, rep(1:P, times = Q), drop = FALSE] *
RES[,rep(1:Q, each = P), drop = FALSE]
SC.Beta
}
lav_mvreg_scores_vech_sigma <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); Q <- NCOL(Y); X <- cbind(1, unname(eXo))
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
isigma <- lav_matrix_vech(res.cov.inv)
RES <- Y - X %*% Beta
RES <- RES %*% res.cov.inv
idx1 <- lav_matrix_vech_col_idx(Q)
idx2 <- lav_matrix_vech_row_idx(Q)
Z <- RES[,idx1] * RES[,idx2]
SC <- t( t(Z) - isigma )
SC[,lav_matrix_diagh_idx(Q)] <- SC[,lav_matrix_diagh_idx(Q)] / 2
SC
}
lav_mvreg_scores_beta_vech_sigma <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
Y <- unname(Y); Q <- NCOL(Y); X <- cbind(1, unname(eXo)); P <- NCOL(X)
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
isigma <- lav_matrix_vech(res.cov.inv)
RES <- Y - X %*% Beta
RES <- RES %*% res.cov.inv
SC.Beta <- X[, rep(1:P, times = Q), drop = FALSE] *
RES[,rep(1:Q, each = P), drop = FALSE]
idx1 <- lav_matrix_vech_col_idx(Q)
idx2 <- lav_matrix_vech_row_idx(Q)
Z <- RES[,idx1] * RES[,idx2]
SC <- t( t(Z) - isigma )
SC[,lav_matrix_diagh_idx(Q)] <- SC[,lav_matrix_diagh_idx(Q)] / 2
cbind(SC.Beta, SC)
}
lav_mvreg_logl_hessian_data <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
res.cov.inv = NULL,
Sinv.method = "eigen") {
N <- NROW(Y)
observed <- lav_mvreg_information_observed_data(Y = Y, eXo = eXo,
Beta = Beta, res.int = res.int, res.slopes = res.slopes,
res.cov = res.cov, res.cov.inv = res.cov.inv,
Sinv.method = Sinv.method)
-N*observed
}
lav_mvreg_logl_hessian_samplestats <- function(
sample.res.int = NULL,
sample.res.slopes = NULL,
sample.res.cov = NULL,
sample.mean.x = NULL,
sample.cov.x = NULL,
sample.nobs = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
N <- sample.nobs
observed <- lav_mvreg_information_observed_samplestats(
sample.res.int = sample.res.int, sample.res.slopes = sample.res.slopes,
sample.res.cov = sample.res.cov, sample.mean.x = sample.mean.x,
sample.cov.x = sample.cov.x, Beta = Beta, res.int = res.int,
res.slopes = res.slopes, res.cov = res.cov, Sinv.method = Sinv.method,
res.cov.inv = res.cov.inv)
-N*observed
}
lav_mvreg_information_expected <- function(Y = NULL,
eXo = NULL,
sample.mean.x = NULL,
sample.cov.x = NULL,
sample.nobs = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
res.cov.inv = NULL,
Sinv.method = "eigen") {
eXo <- unname(eXo)
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
if(is.null(sample.nobs)) {
sample.nobs <- nrow(eXo)
} else {
N <- sample.nobs
}
if(is.null(sample.mean.x)) {
sample.mean.x <- base::.colMeans(eXo, m = NROW(eXo), n = NCOL(eXo))
}
if(is.null(sample.cov.x)) {
sample.cov.x <- lav_matrix_cov(eXo)
}
sample.xx <- rbind( cbind(1, matrix(sample.mean.x, nrow = 1,)),
cbind(matrix(sample.mean.x, ncol = 1),
sample.cov.x + tcrossprod(sample.mean.x)) )
I11 <- res.cov.inv %x% sample.xx
I22 <- 0.5 * lav_matrix_duplication_pre_post(res.cov.inv %x% res.cov.inv)
lav_matrix_bdiag(I11, I22)
}
lav_mvreg_information_observed_data <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
res.cov.inv = NULL,
Sinv.method = "eigen") {
Y <- unname(Y); X1 <- cbind(1, unname(eXo)); N <- NROW(Y)
QR <- qr(X1)
sample.B <- qr.coef(QR, Y)
sample.res.int <- as.numeric(sample.B[1,])
sample.res.slopes <- t(sample.B[-1,,drop = FALSE])
sample.res.cov <- cov(qr.resid(QR, Y)) * (N-1)/N
sample.mean.x <- base::.colMeans(eXo, m = NROW(eXo), n = NCOL(eXo))
sample.cov.x <- lav_matrix_cov(eXo)
lav_mvreg_information_observed_samplestats(sample.res.int = sample.res.int,
sample.res.slopes = sample.res.slopes, sample.res.cov = sample.res.cov,
sample.mean.x = sample.mean.x, sample.cov.x = sample.cov.x,
Beta = Beta, res.int = res.int, res.slopes = res.slopes,
res.cov = res.cov, Sinv.method = Sinv.method, res.cov.inv = res.cov.inv)
}
lav_mvreg_information_observed_samplestats <-
function(sample.res.int = NULL,
sample.res.slopes = NULL,
sample.res.cov = NULL,
sample.mean.x = NULL,
sample.cov.x = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
Sinv.method = "eigen",
res.cov.inv = NULL) {
if(is.null(Beta)) {
Beta <- rbind(matrix(res.int, nrow = 1), t(res.slopes))
}
sample.B <- rbind(matrix(sample.res.int, nrow = 1), t(sample.res.slopes))
sample.xx <- rbind( cbind(1, matrix(sample.mean.x, nrow = 1,)),
cbind(matrix(sample.mean.x, ncol = 1),
sample.cov.x + tcrossprod(sample.mean.x)) )
W.tilde <- ( sample.res.cov +
t(sample.B - Beta) %*% sample.xx %*% (sample.B - Beta) )
if(is.null(res.cov.inv)) {
res.cov.inv <- lav_matrix_symmetric_inverse(S = res.cov, logdet = FALSE,
Sinv.method = Sinv.method)
}
H11 <- res.cov.inv %x% sample.xx
H21 <- lav_matrix_duplication_pre( res.cov.inv %x%
(res.cov.inv %*% (crossprod(sample.B - Beta, sample.xx) )) )
H12 <- t(H21)
AAA <- res.cov.inv %*% (2*W.tilde - res.cov) %*% res.cov.inv
H22 <- (1/2) * lav_matrix_duplication_pre_post(res.cov.inv %x% AAA)
out <- rbind( cbind(H11, H12),
cbind(H21, H22) )
out
}
lav_mvreg_information_firstorder <- function(Y = NULL,
eXo = NULL,
Beta = NULL,
res.int = NULL,
res.slopes = NULL,
res.cov = NULL,
res.cov.inv = NULL,
Sinv.method = "eigen") {
N <- NROW(Y)
SC <- lav_mvreg_scores_beta_vech_sigma(Y = Y, eXo = eXo, Beta = Beta,
res.int = res.int, res.slopes = res.slopes, res.cov = res.cov,
Sinv.method = Sinv.method, res.cov.inv = res.cov.inv)
crossprod(SC)/N
} |
try(dev.off(),silent=TRUE)
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1), oma = c(0, 0, 2, 0))
plot(airquality$Wind, airquality$Ozone, main = "Ozone and Wind")
plot(airquality$Solar.R, airquality$Ozone, main = "Ozone and Solar Radiation")
plot(airquality$Temp, airquality$Ozone, main = "Ozone and Temperature")
mtext("Ozone and Weather in New York City", outer = TRUE) |
extract.hats <- function(slgf.obj, model.index=NULL){
result <- slgf.obj$results
if(is.null(model.index)){
model.index <- which(result$Model==model & result$Scheme==scheme & result$Variance==var)
}
if(result$Variance[model.index]=="Homosk"){
model <- as.character(result$Model[model.index])
scheme <- as.character(result$Scheme[model.index])
mle.index <- result$mle.index[model.index]
mle.coef <- unlist(unname(slgf.obj$coefficients[mle.index]))
mle.var <- unlist(unname(slgf.obj$variances[mle.index]))
return.list <- list(model=model, scheme=scheme, coef=mle.coef, sigsq=mle.var)
names(return.list)[1] <- "model"
return(return.list)
}
if(result$Variance[model.index]=="Heterosk"){
model <- as.character(result$Model[model.index])
scheme <- as.character(result$Scheme[model.index])
scheme1 <- paste0(strsplit(scheme, "}")[[1]][1],"}")
scheme2 <- paste0(strsplit(scheme, "}")[[1]][2],"}")
mle.index <- result$mle.index[model.index]
mle.coef <- unlist(unname(slgf.obj$coefficients[mle.index]))
mle.var1 <- unlist(unname(slgf.obj$variances[mle.index][[1]][1]))
mle.var2 <- unlist(unname(slgf.obj$variances[mle.index][[1]][2]))
return.list <- list(model=model, scheme=scheme, coef=mle.coef,
sigsq.1=mle.var1, sigsq.2=mle.var2)
names(return.list)[4] <- paste0("sigsq",".",scheme1)
names(return.list)[5] <- paste0("sigsq",".",scheme2)
return(return.list)
}
} |
estfun.systemfit <- function ( obj, residFit = TRUE, ... ) {
if( !is.null( obj$restrict.matrix ) || !is.null( obj$restrict.rhs ) ||
!is.null( obj$restrict.regMat ) ) {
stop( "returning the estimation function for models with restrictions",
" has not yet been implemented.")
}
res <- unlist( residuals( obj ) )
if( is.null( obj$eq[[1]]$inst ) ) {
mm <- model.matrix( obj )
} else {
mm <- model.matrix( obj, which = "xHat" )
if( residFit ) {
res[ !is.na( res ) ] <- res[ !is.na( res ) ] +
( model.matrix( obj ) - mm ) %*% coef( obj )
}
}
if( sum( !is.na( res ) ) != nrow( mm ) ) {
stop( "internal error: the number of residuals is not equal to the",
" number of rows of the model matrix. Please contact the maintainer." )
}
if( is.null( obj$residCovEst ) ) {
omegaInvXmat <- mm
} else {
omegaInvXmat <- t( .calcXtOmegaInv( xMat = mm, sigma = obj$residCovEst,
validObsEq = !is.na( residuals( obj ) ), invertSigma = TRUE ) )
}
result <- res[ !is.na( res ) ] * omegaInvXmat
dimnames( result ) <- dimnames( mm )
if( max( abs( colSums( result ) ) ) > 1e-6 ) {
warning( "the columns of the returned estimating function",
" do not all sum up to zero,",
" which indicates that the wrong estimating function is returned" )
}
return( result )
} |
library(testthat)
library(stubthat)
test_that("Required parameters are present", {
expect_error(CreateStratifiedPartition())
expect_error(CreateStratifiedPartition(validationType = "CV"))
})
test_that("validationType = 'CV' option", {
expect_error(CreateStratifiedPartition(validationType = "CV",
holdoutPct = 20),
"reps must be specified")
ValidCase <- CreateStratifiedPartition(validationType = "CV",
holdoutPct = 20, reps = 5)
expect_equal(length(ValidCase), 4)
expect_equal(ValidCase$cvMethod, "stratified")
expect_equal(ValidCase$validationType, "CV")
expect_equal(ValidCase$holdoutPct, 20)
expect_equal(ValidCase$reps, 5)
})
test_that("validationType = 'TVH' option", {
expect_error(CreateStratifiedPartition(validationType = "TVH",
holdoutPct = 20),
"validationPct must be specified")
ValidCase <- CreateStratifiedPartition(validationType = "TVH",
holdoutPct = 20,
validationPct = 16)
expect_equal(length(ValidCase), 4)
expect_equal(ValidCase$cvMethod, "stratified")
expect_equal(ValidCase$validationType, "TVH")
expect_equal(ValidCase$holdoutPct, 20)
expect_equal(ValidCase$validationPct, 16)
})
test_that("validationType = 'CV' option can be used to SetTarget", {
with_mock("GetProjectStatus" = function(...) { list("stage" = ProjectStage$AIM) },
"datarobot::DataRobotPATCH" = function(...) {
list(...)
},
"datarobot::WaitForAsyncReturn" = function(...) { "How about not" }, {
stratifiedPartition <- CreateStratifiedPartition(validationType = "CV",
holdoutPct = 20,
reps = 5)
SetTarget(project = fakeProject,
target = fakeTarget,
partition = stratifiedPartition)
})
})
test_that("validationType = 'TVH' option can be used to SetTarget", {
with_mock("GetProjectStatus" = function(...) { list("stage" = ProjectStage$AIM) },
"datarobot::DataRobotPATCH" = function(...) {
list(...)
},
"datarobot::WaitForAsyncReturn" = function(...) { "How about not" }, {
stratifiedPartition <- CreateStratifiedPartition(validationType = "TVH",
holdoutPct = 20,
validationPct = 16)
SetTarget(project = fakeProject,
target = fakeTarget,
partition = stratifiedPartition)
})
})
test_that("Invalid validationType returns message", {
expect_error(CreateStratifiedPartition(validationType = "XYZ",
holdoutPct = 20,
validationPct = 16))
}) |
library(hdf5)
fname <- "/n/Moorcroft_Lab/Users/mcd/inputs/fluxnet/bartlett/snowcorHDF/ED_OL_2002JUN.h5"
met <- hdf5load(fname,load=FALSE)
par(mfrow=c(3,4))
for(i in 1:12){
plot(met[[i]],main=names(met)[i],type='l')
} |
library(RUnit)
summarizePos <- try(summarizeFilterResults(tinyMetaObject,"pValueFDR0.05_es0_nStudies1_looaTRUE_hetero0"))
checkTrue(!is(summarizePos,"try-error"))
summarizeNeg <- try(summarizeFilterResults(tinyMetaObject,"BIGFAKELABEL"))
checkTrue(is(summarizeNeg,"try-error")) |
test_that("srFunShow() messages",{
expect_error(srFunShow("Derek"),"should be one of")
expect_error(srFunShow(type="BevertonHolt",param=0),"must be from")
expect_error(srFunShow(type="BevertonHolt",param=5),"must be from")
expect_error(srFunShow(type="Ricker",param=0),"must be from")
expect_error(srFunShow(type="Ricker",param=4),"must be from")
})
test_that("srFuns() messages",{
expect_error(srFuns(type="Derek"),"should be one")
expect_error(srFuns(type="BevertonHolt",param=0),"must be in")
expect_error(srFuns(type="BevertonHolt",param=5),"must be in")
expect_error(srFuns(type="BevertonHolt",param=c(1,3)),"Only one")
expect_error(srFuns(type="Ricker",param=0),"must be in")
expect_error(srFuns(type="Ricker",param=4),"must be in")
expect_error(srFuns(type="Ricker",param=c(1,3)),"Only one")
expect_warning(srFuns(type="Shepherd",param=2),"param=1")
expect_warning(srFuns(type="Saila",param=2),"param=1")
expect_warning(srFuns(type="independence",param=2),"param=1")
})
test_that("srStarts() messages",{
CodNorwegian$fyear <- factor(CodNorwegian$year)
expect_warning(srStarts(recruits~stock,data=CodNorwegian,dynamicPlot=TRUE),
"functionality has been moved to")
expect_error(srStarts(type="Derek"))
expect_error(srStarts(recruits~stock,data=CodNorwegian,
type="BevertonHolt",param=0),
"'param' must be in")
expect_error(srStarts(recruits~stock,data=CodNorwegian,
type="BevertonHolt",param=5),
"'param' must be in")
expect_error(srStarts(recruits~stock,data=CodNorwegian,
type="BevertonHolt",param=c(1,3)),
"Only one 'param'")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=0),
"'param' must be in")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=4),
"'param' must be in")
expect_error(srStarts(recruits~stock,data=CodNorwegian,
type="Ricker",param=c(1,3)),
"Only one 'param'")
expect_error(srStarts(~stock,data=CodNorwegian),"with both LHS and RHS")
expect_error(srStarts(stock~1,data=CodNorwegian),"with both LHS and RHS")
expect_error(srStarts(~stock+recruits,data=CodNorwegian),
"only one LHS variable")
expect_error(srStarts(stock+recruits~1,data=CodNorwegian),
"with both LHS and RHS")
expect_error(srStarts(stock~fyear,data=CodNorwegian),
"RHS variable must be numeric")
expect_error(srStarts(fyear~recruits,data=CodNorwegian),
"LHS variable must be numeric")
expect_error(srStarts(stock~recruits+fyear,data=CodNorwegian),
"only one LHS and only one RHS")
expect_error(srStarts(recruits~stock,data=CodNorwegian,fixed=list(c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,
fixed=list(a=3,c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,
fixed=list(a=3,b=0.1,c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,param=2,
fixed=list(b=1)),
"is not a parameter")
expect_error(srStarts(recruits~stock,data=CodNorwegian,param=4,
fixed=list(b=1)),
"is not a parameter")
expect_error(srStarts(recruits~stock,data=CodNorwegian,param=1,
fixed=list(Rp=1)),
"is not a parameter")
expect_error(srStarts(recruits~stock,data=CodNorwegian,param=3,
fixed=list(Rp=1)),
"is not a parameter")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,param=1,
fixed=list(a=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,param=1,
fixed=list(b=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,param=2,
fixed=list(Rp=-1)),
"not positive")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",
fixed=list(c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",
fixed=list(a=3,c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",
fixed=list(a=3,b=0.1,c=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=3,
fixed=list(b=1)),
"is not a parameter")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=1,
fixed=list(Rp=1)),
"is not a parameter")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=2,
fixed=list(Rp=1)),
"is not a parameter")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",
fixed=list(a=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",
fixed=list(b=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=3,
fixed=list(Rp=-1)),
"not positive")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Shepherd",
fixed=list(d=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="Shepherd",
fixed=list(a=3,d=1)),
"not named")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Shepherd",
fixed=list(a=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Shepherd",
fixed=list(b=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="Shepherd",
fixed=list(c=-1)),
"not positive")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda",
fixed=list(d=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda",
fixed=list(a=3,d=1)),
"not named")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda",
fixed=list(a=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda",
fixed=list(b=-1)),
"not positive")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda",
fixed=list(c=-1)),
"not positive")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="independence",
fixed=list(d=1)),
"not named")
expect_error(srStarts(recruits~stock,data=CodNorwegian,type="independence",
fixed=list(a=3,d=1)),
"not named")
expect_warning(srStarts(recruits~stock,data=CodNorwegian,type="independence",
fixed=list(a=-1)),
"not positive")
})
test_that("srFuns() output",{
expect_equal(mode(srFunShow(type="BevertonHolt",param=1)),"expression")
expect_equal(mode(srFunShow(type="BevertonHolt",param=2)),"expression")
expect_equal(mode(srFunShow(type="BevertonHolt",param=3)),"expression")
expect_equal(mode(srFunShow(type="BevertonHolt",param=4)),"expression")
expect_equal(mode(srFunShow(type="Ricker",param=1)),"expression")
expect_equal(mode(srFunShow(type="Ricker",param=2)),"expression")
expect_equal(mode(srFunShow(type="Ricker",param=3)),"expression")
expect_equal(mode(srFunShow(type="Shepherd")),"expression")
expect_equal(mode(srFunShow(type="SailaLorda")),"expression")
})
test_that("srFuns() output",{
expect_is(srFuns("BevertonHolt",param=1),"function")
expect_is(srFuns("BevertonHolt",param=2),"function")
expect_is(srFuns("BevertonHolt",param=3),"function")
expect_is(srFuns("BevertonHolt",param=4),"function")
expect_is(srFuns("Ricker",param=1),"function")
expect_is(srFuns("Ricker",param=2),"function")
expect_is(srFuns("Ricker",param=3),"function")
expect_is(srFuns("Shepherd"),"function")
expect_is(srFuns("Saila"),"function")
expect_is(srFuns("independence"),"function")
expect_is(srFuns("BevertonHolt",param=1,simple=TRUE),"function")
expect_is(srFuns("BevertonHolt",param=2,simple=TRUE),"function")
expect_is(srFuns("BevertonHolt",param=3,simple=TRUE),"function")
expect_is(srFuns("BevertonHolt",param=4,simple=TRUE),"function")
expect_is(srFuns("Ricker",param=1,simple=TRUE),"function")
expect_is(srFuns("Ricker",param=2,simple=TRUE),"function")
expect_is(srFuns("Ricker",param=3,simple=TRUE),"function")
expect_is(srFuns("Shepherd",simple=TRUE),"function")
expect_is(srFuns("Saila",simple=TRUE),"function")
expect_is(srFuns("independence",simple=TRUE),"function")
expect_message(srFuns("BevertonHolt",param=1,msg=TRUE),
"first parameterization of the 'Beverton-Holt'")
expect_message(srFuns("BevertonHolt",param=2,msg=TRUE),
"second parameterization of the 'Beverton-Holt'")
expect_message(srFuns("BevertonHolt",param=3,msg=TRUE),
"third parameterization of the 'Beverton-Holt'")
expect_message(srFuns("BevertonHolt",param=4,msg=TRUE),
"fourth parameterization of the 'Beverton-Holt'")
expect_message(srFuns("Ricker",param=1,msg=TRUE),
"first parameterization of the 'Ricker'")
expect_message(srFuns("Ricker",param=2,msg=TRUE),
"second parameterization of the 'Ricker'")
expect_message(srFuns("Ricker",param=3,msg=TRUE),
"third parameterization of the 'Ricker'")
expect_message(srFuns("Shepherd",msg=TRUE),"Shepherd")
expect_message(srFuns("Saila",msg=TRUE),"Saila")
expect_message(srFuns("independence",msg=TRUE),"density-independent")
})
test_that("srStarts() output",{
CodNorwegian$fyear <- factor(CodNorwegian$year)
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="BevertonHolt",param=1)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="BevertonHolt",param=2)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","Rp"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="BevertonHolt",param=3)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="BevertonHolt",param=4)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","Rp"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=1)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=2)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="Ricker",param=3)
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","Rp"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="Shepherd")
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b","c"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="SailaLorda")
expect_is(tmp,"list")
expect_equal(names(tmp),c("a","b","c"))
tmp <- srStarts(recruits~stock,data=CodNorwegian,type="independence")
expect_is(tmp,"list")
expect_equal(names(tmp),"a")
}) |
pfa <- function(object, name=NULL, version=NULL, doc=NULL, metadata=NULL, randseed=NULL, options=NULL, ...) UseMethod("pfa")
extract_params <- function(object, ...) UseMethod("extract_params")
build_model <- function(object, ...) UseMethod("build_model") |
test_that("FilterImportance", {
set.seed(42)
task = mlr3::mlr_tasks$get("wine")
learner = mlr3::mlr_learners$get("classif.rpart")
f = FilterImportance$new(learner = learner)
f$calculate(task)
expect_filter(f, task = task)
}) |
context("Bootstrap functions")
test_that("getSignReference works", {
alpha <- list(matrix(1:9, nrow = 3), matrix(-1 * (9:1), nrow = 3), matrix(c(1:5, 4:1), nrow = 3))
expectedOut <- list(
position = c(9, 1, 5), isNegative = c(FALSE, TRUE, FALSE),
allNegative = list(
matrix(1:9, nrow = 3) < 0,
matrix(-1 * (9:1), nrow = 3) < 0,
matrix(c(1:5, 4:1), nrow = 3) < 0
)
)
out <- getSignReference(alpha)
expect_equal(out, expectedOut)
})
test_that("unifySign works when all are present", {
ref <- list(position = c(9, 1, 5), isNegative = c(FALSE, TRUE, FALSE))
encod <- list(
list(
alpha = list(matrix(1:9, nrow = 3), matrix(1:9, nrow = 3), matrix(1:9, nrow = 3)),
pc = matrix(1:9, nrow = 3)
),
list(
alpha = list(matrix(-1 * (9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3)),
pc = matrix(-1 * (9:1), nrow = 3)
)
)
expectedOut <- list(
list(
alpha = list(matrix(1:9, nrow = 3), matrix(-1 * (1:9), nrow = 3), matrix(1:9, nrow = 3)),
pc = matrix(c(1:3, -4, -5, -6, 7:9), nrow = 3)
),
list(
alpha = list(matrix((9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3), matrix((9:1), nrow = 3)),
pc = matrix(c(9:7, -6, -5, -4, 3:1), nrow = 3)
)
)
out <- unifySign(encod, ref)
expect_equal(out, expectedOut)
})
test_that("unifySign works when there are some NULL elements", {
ref <- list(position = c(9, 1, 5), isNegative = c(FALSE, TRUE, FALSE))
encod <- list(
list(
alpha = list(matrix(1:9, nrow = 3), matrix(1:9, nrow = 3), matrix(1:9, nrow = 3)),
pc = matrix(1:9, nrow = 3)
),
NULL,
list(
alpha = list(matrix(-1 * (9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3)),
pc = matrix(-1 * (9:1), nrow = 3)
)
)
expectedOut <- list(
list(
alpha = list(matrix(1:9, nrow = 3), matrix(-1 * (1:9), nrow = 3), matrix(1:9, nrow = 3)),
pc = matrix(c(1:3, -4, -5, -6, 7:9), nrow = 3)
),
NULL,
list(
alpha = list(matrix((9:1), nrow = 3), matrix(-1 * (9:1), nrow = 3), matrix((9:1), nrow = 3)),
pc = matrix(c(9:7, -6, -5, -4, 3:1), nrow = 3)
)
)
out <- unifySign(encod, ref)
expect_equal(out, expectedOut)
})
test_that("compute_optimal_encoding throws error", {
set.seed(42)
K <- 2
d_JK <- generate_2State(n = 10)
d_JK2 <- cut_data(d_JK, 1)
m <- 10
b <- create.bspline.basis(c(0, 1), nbasis = m, norder = 4)
expect_error(compute_optimal_encoding(d_JK2, b, nCores = 1, computeCI = 2), regexp = "computeCI must be either TRUE or FALSE.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 0, propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 10.5, propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = NA, propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = c(), propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = c(20, 50), propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = NaN, propBootstrap = 0.5), regexp = "nBootstrap must be an integer > 0.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = 0), regexp = "propBootstrap must be a real between 0 and 1.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = 1.5), regexp = "propBootstrap must be a real between 0 and 1.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = c(0.5, 0.8)), regexp = "propBootstrap must be a real between 0 and 1.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = NA), regexp = "propBootstrap must be a real between 0 and 1.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = NaN), regexp = "propBootstrap must be a real between 0 and 1.")
expect_error(compute_optimal_encoding(d_JK2, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = c()), regexp = "propBootstrap must be a real between 0 and 1.")
})
test_that("compute_optimal_encoding works with computeCI = TRUE", {
skip_on_cran()
set.seed(42)
n <- 200
Tmax <- 1
K <- 2
m <- 10
d <- generate_2State(n)
dT <- cut_data(d, Tmax)
row.names(dT) <- NULL
b <- create.bspline.basis(c(0, Tmax), nbasis = m, norder = 4)
expect_silent(fmca <- compute_optimal_encoding(dT, b, computeCI = TRUE, nBootstrap = 50, propBootstrap = 0.5, nCores = 1, verbose = FALSE))
expect_type(fmca, "list")
expect_named(fmca, c("eigenvalues", "alpha", "pc", "F", "G", "V", "basisobj", "label", "pt", "bootstrap", "varAlpha", "runTime"))
expect_length(fmca$bootstrap, 50)
expect_named(fmca$bootstrap[[1]], c("eigenvalues", "alpha", "pc", "F", "G"))
expect_length(fmca$bootstrap[[1]]$eigenvalues, K * m)
trueEigVal <- 1 / ((1:m) * (2:(m + 1)))
expect_lte(max(abs(fmca$eigenvalues[1:m] - trueEigVal)), 0.01)
expect_type(fmca$bootstrap[[1]]$alpha, "list")
expect_length(fmca$bootstrap[[1]]$alpha, m * K)
expect_equal(dim(fmca$bootstrap[[1]]$alpha[[1]]), c(m, K))
expect_equal(dim(fmca$bootstrap[[1]]$pc), c(100, m * K))
expect_equal(dim(fmca$bootstrap[[1]]$F), c(2 * m, 2 * m))
expect_equal(dim(fmca$bootstrap[[1]]$G), c(2 * m, 2 * m))
expect_equal(fmca$label, data.frame(label = 0:1, code = 1:2))
})
test_that("plot.fmca works with addCI = TRUE", {
skip_on_cran()
set.seed(42)
n <- 25
Tmax <- 1
K <- 2
m <- 6
d <- generate_2State(n)
dT <- cut_data(d, Tmax)
row.names(dT) <- NULL
b <- create.bspline.basis(c(0, Tmax), nbasis = m, norder = 4)
fmca <- compute_optimal_encoding(dT, b, computeCI = TRUE, nBootstrap = 25, propBootstrap = 1, nCores = 1, verbose = FALSE)
expect_warning(plot(fmca, addCI = TRUE), regexp = NA)
expect_warning(plot(fmca, addCI = TRUE, states = 1), regexp = NA)
expect_warning(plot(fmca, addCI = TRUE, states = 1:3), regexp = NA)
expect_warning(plot(fmca, addCI = TRUE, coeff = 5), regexp = NA)
expect_warning(plot(fmca, addCI = TRUE, col = c("red", "blue")), regexp = NA)
expect_error(plot(fmca, addCI = 6), regexp = "addCI must be either TRUE or FALSE.")
expect_error(plot(fmca, addCI = TRUE, states = c("a", "b")), regexp = "No correct states given.")
expect_error(plot(fmca, addCI = TRUE, coeff = -5), regexp = "coeff must be a positive real.")
}) |
levbox_mergetime <- function(var, level = 1, path, pattern, outfile,
lon1 = -180, lon2 = 180, lat1 = -90, lat2 = 90,
nc34 = 4, overwrite = FALSE, verbose = FALSE) {
box_mergetime(var, path, pattern, outfile, lon1, lon2, lat1, lat2, level,
nc34, overwrite, verbose)
} |
test_that("at returns the correct values", {
gen_func <- at(c(0, 10, 15))
expect_equal(gen_func(), c(0, 10, 5, -1))
gen_func <- at(0, 10, 15)
expect_equal(gen_func(), c(0, 10, 5, -1))
})
test_that("from returns the correct values", {
gen_func <- from(5, function() 1)
expect_equal(gen_func(), 5)
expect_equal(gen_func(), 1)
gen_func <- from(5, function() 1, arrive = FALSE)
expect_equal(gen_func(), 6)
expect_equal(gen_func(), 1)
})
test_that("to returns the correct values", {
gen_func <- to(3, function() 1)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), -1)
gen_func <- to(3, function() c(1, 1))
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), -1)
gen_func <- to(3, function() c(1, 1, 1))
expect_equal(gen_func(), c(1, 1, -1))
})
test_that("from_to returns the correct values", {
gen_func <- from_to(5, 8, function() 1)
expect_equal(gen_func(), 5)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), -1)
gen_func <- from_to(5, 8, function() c(1, 1))
expect_equal(gen_func(), 5)
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), -1)
gen_func <- from_to(5, 8, function() c(1, 1, 1))
expect_equal(gen_func(), 5)
expect_equal(gen_func(), c(1, 1, -1))
gen_func <- from_to(5, 8, function() 1, every=10)
expect_equal(gen_func(), 5)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 8)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 8)
gen_func <- from_to(5, 8, function() c(1, 1), every=10)
expect_equal(gen_func(), 5)
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), 8)
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), 8)
gen_func <- from_to(5, 8, function() c(1, 1, 1), every=10)
expect_equal(gen_func(), 5)
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), 8)
expect_equal(gen_func(), c(1, 1))
expect_equal(gen_func(), 8)
gen_func <- from_to(5, 8, function() 1, arrive = FALSE)
expect_equal(gen_func(), 6)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), -1)
gen_func <- from_to(5, 8, function() c(1, 1), arrive = FALSE)
expect_equal(gen_func(), c(6, 1))
expect_equal(gen_func(), -1)
gen_func <- from_to(5, 8, function() c(1, 1, 1), arrive = FALSE)
expect_equal(gen_func(), c(6, 1, -1))
gen_func <- from_to(5, 8, function() 1, arrive = FALSE, every=10)
expect_equal(gen_func(), 6)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 9)
expect_equal(gen_func(), 1)
expect_equal(gen_func(), 9)
gen_func <- from_to(5, 8, function() c(1, 1), arrive = FALSE, every=10)
expect_equal(gen_func(), c(6, 1))
expect_equal(gen_func(), c(9, 1))
expect_equal(gen_func(), c(9, 1))
gen_func <- from_to(5, 8, function() c(1, 1, 1), arrive = FALSE, every=10)
expect_equal(gen_func(), c(6, 1))
expect_equal(gen_func(), c(9, 1))
expect_equal(gen_func(), c(9, 1))
})
test_that("environments are properly replaced and variables transferred", {
start_time <- local({ start <- 1; function() start })
stop_time <- local({ stop <- 2; function() stop })
dist <- local({ x <- 3; function() x })
every <- local({ ev <- 4; function() ev })
gen_func <- from(start_time, dist)
expect_equal(environment(gen_func)$start, 1)
expect_equal(environment(gen_func)$stop, NULL)
expect_equal(environment(gen_func)$x, 3)
expect_equal(environment(gen_func)$ev, NULL)
gen_func <- to(stop_time, dist)
expect_equal(environment(gen_func)$start, NULL)
expect_equal(environment(gen_func)$stop, 2)
expect_equal(environment(gen_func)$x, 3)
expect_equal(environment(gen_func)$ev, NULL)
gen_func <- from_to(start_time, stop_time, dist, every=every)
expect_equal(environment(gen_func)$start, 1)
expect_equal(environment(gen_func)$stop, 2)
expect_equal(environment(gen_func)$x, 3)
expect_equal(environment(gen_func)$ev, 4)
})
test_that("schedule returns the correct values", {
expect_error(schedule(1, 1))
expect_error(schedule(c(1, 2), 1))
expect_error(schedule(1, c(1, 2)))
expect_error(schedule(c(2, 1), c(1, 2)))
expect_error(schedule(c(2, 1), c(1, 2), 1))
expect_error(schedule(c(0, 1), c(1, 2), 1))
sch <- schedule(c(1, 3), c(1, 2), Inf)$schedule
expect_equal(sch$init, 0)
expect_equal(sch$intervals, c(1, 2))
expect_equal(sch$values, c(1, 2))
expect_equal(sch$period, -1)
sch <- schedule(c(1, 3), c(1, 2), 3)$schedule
expect_equal(sch$init, 2)
expect_equal(sch$intervals, c(1, 2, 1))
expect_equal(sch$values, c(1, 2, 1))
expect_equal(sch$period, 3)
sch <- schedule(c(0, 2), c(1, 2), 3)$schedule
expect_equal(sch$init, 1)
expect_equal(sch$intervals, c(0, 2, 1))
expect_equal(sch$values, c(1, 2, 1))
expect_equal(sch$period, 3)
})
test_that("when_activated returns the correct values", {
gen_func <- when_activated()
expect_equal(gen_func(), -1)
expect_equal(gen_func(), c(0, -1))
gen_func <- when_activated(function() 5)
expect_equal(gen_func(), -1)
expect_equal(gen_func(), c(rep(0, 5), -1))
}) |
library(testit)
library(vpc)
nonmem_df <- data.frame(ID = 0, MDV = 0, DV = 0)
phx_df <- data.frame(ID = 0, COBS = 0)
assert("software type returned properly",
vpc:::guess_software("NONmem", nonmem_df) == "nonmem")
assert("software type returned properly",
vpc:::guess_software("nonmem", phx_df) == "nonmem")
assert("software type returned properly",
vpc:::guess_software("auto", nonmem_df) == "nonmem")
assert("software type returned properly",
vpc:::guess_software("auto", phx_df) == "phoenix") |
lossfunc <- function(obj = list(Loss = NULL, ES = NULL), beta = 1e-04) {
if (!is.list(obj) && !is.data.frame(obj)) {
stop("A list or data frame containing two vectors with equal
length and without NAs must be passed to", " 'obj'.")
}
if (class(obj) != "ufRisk" && (length(obj[["Loss"]]) <= 1 ||
any(is.na(obj[["Loss"]])) ||
!is.numeric(obj[["Loss"]]))) {
stop("A numeric vector of length > 1 and without NAs must be passed to",
" 'obj$Loss'.")
}
if (class(obj) != "ufRisk" && (length(obj[["ES"]]) <= 1 ||
any(is.na(obj[["ES"]])) ||
!is.numeric(obj[["ES"]]))) {
stop("A numeric vector of length > 1 and without NAs must be passed to",
" 'obj$ES'.")
}
if (length(beta) != 1 || is.na(beta) || !is.numeric(beta)) {
stop("A single numeric value must be passed to"," 'beta'")
}
if(class(obj) == "ufRisk") {
Loss <- -obj[["ret.out"]]
}
else {
Loss <- obj[["Loss"]]
}
ES <- obj[["ES"]]
loss.ed <- (Loss - ES)[Loss > ES]
loss.ex2 <- (Loss - ES)[Loss <= ES]
loss.ex1 <- ES[Loss <= ES]
loss.ex23 <- (Loss - ES)[Loss <= ES & Loss >= 0]
loss.ex3 <- ES[Loss <= ES & Loss < 0]
RLF <- sum(loss.ed^2)
FLF2 <- sum(abs(loss.ex2)) * beta
FLF23 <- sum(abs(loss.ex23)) * beta
FLF3 <- sum(loss.ex3) * beta
FLF1 <- sum(loss.ex1) * beta
loss.func1 <- RLF * 10000
loss.func2 <- (RLF + FLF1) * 10000
loss.func3 <- (RLF + FLF2) * 10000
loss.func4 <- (RLF + FLF23 + FLF3) * 10000
result <- list(lossfunc1 = loss.func1,
lossfunc2 = loss.func2,
lossfunc3 = loss.func3,
lossfunc4 = loss.func4)
message("Please note that the following results are multiplied with 10000.")
message("")
return(result)
} |
"mozart" |
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(scales)
library(lubridate)
library(stringr)
library(ggrepel)
library(zoo)
library(Hmisc)
library(igraph)
library(lemon)
library(readxl)
library(tidyverse)
folder_name <- "_jkb/0011_rebalance_stock_bond"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
make_plots <- 1
n_years <- 30
wt_stock <- 0.6
wt_bond <- 1 - wt_stock
bw_colors <- c("
spx <- read.csv(paste0(importdir, "_jkb/0011_rebalance_stock_bond/spx_timeseries_4-27-2021.csv"), skip = 6) %>%
rename(symbol = Symbol) %>%
select(-Name, -Metric) %>%
gather(-symbol, key=key, value = value) %>%
mutate(year = gsub("X(\\d+)\\.(\\d+)\\.(\\d+)", "\\1", key, perl = TRUE),
month = gsub("X(\\d+)\\.(\\d+)\\.(\\d+)", "\\2", key, perl = TRUE),
day = gsub("X(\\d+)\\.(\\d+)\\.(\\d+)", "\\3", key, perl = TRUE),
date = as.Date(paste0(year, "-", month, "-", day), format = "%Y-%m-%d")) %>%
filter(symbol != "", !is.na(value)) %>%
arrange(date) %>%
mutate(ret_1yr = lead(value, 12)/value - 1) %>%
select(date, value, ret_1yr) %>%
drop_na()
spx_median_1yr_ret <- quantile(spx$ret_1yr, probs = 0.5)
raw <- read.csv(paste0(importdir, "_jkb/0011_rebalance_stock_bond/sp500_5yr_treasury.csv"), skip = 6) %>%
filter(Date != "", `S.P.500.Index` != "") %>%
mutate(date = as.Date(Date, format = "%m/%d/%Y"),
month = month(date),
ret_stock = as.numeric(`S.P.500.Index`),
ret_bond = as.numeric(`Five.Year.US.Treasury.Notes`)) %>%
select(date, contains("ret_"), month) %>%
filter(date < "2021-01-31")
run_rebal <- function(start_date, end_date, rebal_month, rebal_string, rebal_addition){
df <- raw %>%
filter(date >= start_date,
date < end_date)
for(i in 1:nrow(df)){
mt <- df[i, "month"]
if(i == 1){
df[i, "value_stock"] <- wt_stock*100
df[i, "value_bond"] <- wt_bond*100
df[i, "value_port"] <- df[i, "value_stock"] + df[i, "value_bond"]
df[i, "rebalance"] <- 0
df[i, "ret_port"] <- 0
} else{
if(mt == rebal_month){
df[i, "rebalance"] <- 1
df[i, "value_stock"] <- (df[(i-1), "value_port"] * wt_stock) * (1 + df[i, "ret_stock"]) + (rebal_addition*wt_stock)
df[i, "value_bond"] <- (df[(i-1), "value_port"] * wt_bond) * (1 + df[i, "ret_bond"]) + (rebal_addition*wt_bond)
} else{
df[i, "rebalance"] <- 0
if(rebal_addition > 0){
stock_target <- (df[(i-1), "value_port"] + rebal_addition) * wt_stock
prior_stock_value <- df[(i-1), "value_stock"]
if(prior_stock_value > stock_target){
wt_stock_temp <- 0
wt_bond_temp <- 1
} else if((prior_stock_value + rebal_addition) < stock_target){
wt_stock_temp <- 1
wt_bond_temp <- 0
} else {
wt_stock_temp <- (stock_target - prior_stock_value)/rebal_addition
wt_bond_temp <- 1 - wt_stock_temp
}
} else{
wt_stock_temp <- 0
wt_bond_temp <- 0
}
stock_addition <- rebal_addition*wt_stock_temp
bond_addition <- rebal_addition*wt_bond_temp
df[i, "value_stock"] <- (df[(i-1), "value_stock"] + stock_addition) * (1 + df[i, "ret_stock"])
df[i, "value_bond"] <- (df[(i-1), "value_bond"] + bond_addition) * (1 + df[i, "ret_bond"])
}
df[i, "value_port"] <- df[i, "value_stock"] + df[i, "value_bond"]
df[i, "ret_port"] <- df[i, "value_port"]/df[(i-1), "value_port"] - 1
}
}
dd <- df %>%
select(date, value_port) %>%
drawdown_path()
file_path <- paste0(out_path, "/rebal_", rebal_month, "_", rebal_addition, "/", date_to_string(start_date), "_area.jpeg")
if(make_plots == 1 & start_date == "1930-01-31"){
to_plot <- df %>%
select(date, contains("value_")) %>%
mutate(`Stock %` = value_stock/value_port,
`Bond %` = 1 - `Stock %`) %>%
select(date, `Stock %`, `Bond %`) %>%
gather(-date, key=key, value=value)
plot <- ggplot(to_plot, aes(x=date, y=value, fill=key)) +
geom_area(alpha=0.6 , size=1) +
scale_fill_manual(values = bw_colors[1:2]) +
scale_y_continuous(label = percent_format(accuracy = 1), breaks = seq(0, 1, 0.1), limits = c(0, 1)) +
of_dollars_and_data_theme +
theme(legend.title = element_blank(),
legend.position = "bottom") +
ggtitle(paste0(100*wt_stock, "/", 100*wt_bond," Stock/Bond Portfolio Share\n", rebal_string)) +
labs(x = "Date" , y = "Percentage in Stocks/Bonds")
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
}
final_value <- df[nrow(df), "value_port"]
final_stock_pct <- df[nrow(df), "value_stock"]/final_value
final_sd <- sd(df$ret_port) * sqrt(12)
max_dd <- min(dd$pct)
final_cor <- cor(df$ret_stock, df$ret_bond)
tmp_result <- data.frame(start_date = start_date,
end_date = end_date,
rebal_month = rebal_month,
rebal_addition = rebal_addition,
final_value = final_value,
final_stock_pct = final_stock_pct,
max_dd = max_dd,
final_sd = final_sd,
final_cor = final_cor)
return(tmp_result)
}
result_file <- paste0(localdir, "rebalance_stock_bond_all_sims.Rds")
if(!file.exists(result_file)){
final_results <- data.frame()
all_dates <- raw %>% filter(month(date) == 1) %>% select(date) %>% distinct()
total_months <- nrow(all_dates)
period_months <- n_years
rebal_sims <- data.frame(rebal_month = c(rep(seq(1, 12, 1), 2), 99, 99),
rebal_additions = c(rep(0, 12), rep(100, 12), 0, 100))
for(i in 1:nrow(rebal_sims)){
r <- rebal_sims[i, "rebal_month"]
r_addition <- rebal_sims[i, "rebal_additions"]
sim <- data.frame(start_date = all_dates[1:(total_months - period_months), "date"],
end_date = all_dates[(period_months+1):total_months, "date"],
rebal_month = rep(r, total_months - period_months))
if(r <= 12){
rebal_string <- paste0("Rebalanced Each ", month.abb[r])
} else{
rebal_string <- "Never Rebalanced"
}
dir.create(file.path(paste0(out_path, "/rebal_", r, "_", r_addition)), showWarnings = FALSE)
for(s in 1:nrow(sim)){
start <- sim[s, "start_date"]
end <- sim[s, "end_date"]
rebal_month <- sim[s, "rebal_month"]
print(start)
print(rebal_month)
if(s == 1 & i == 1){
final_results <- run_rebal(start, end, rebal_month, rebal_string, r_addition)
} else{
final_results <- final_results %>% bind_rows(run_rebal(start, end, rebal_month, rebal_string, r_addition))
}
}
}
saveRDS(final_results, result_file)
} else{
final_results <- readRDS(result_file)
}
summary <- final_results %>%
filter(rebal_month <= 12) %>%
group_by(start_date, end_date, rebal_addition) %>%
summarise(min_value = min(final_value),
max_value = max(final_value),
value_pct_diff = max_value/min_value - 1,
value_diff_annualized = (1+value_pct_diff)^(1/n_years) - 1,
max_dd = mean(max_dd),
min_sd = min(final_sd),
max_sd = max(final_sd)) %>%
ungroup() %>%
mutate(rebal_addition_string = ifelse(rebal_addition == 0, "Not Adding Funds", "Adding Funds Monthly"))
to_plot <- summary %>%
select(start_date, max_dd, rebal_addition_string)
file_path <- paste0(out_path, "/_max_dd_add_funds_vs_not.jpeg")
text_labels <- data.frame()
text_labels[1, "start_date"] <- as.Date("1961-01-01")
text_labels[1, "max_dd"] <- -0.05
text_labels[1, "label"] <- "Adding Funds Monthly"
text_labels[2, "start_date"] <- as.Date("1961-01-01")
text_labels[2, "max_dd"] <- -0.38
text_labels[2, "label"] <- "Not Adding Funds"
plot <- ggplot(to_plot, aes(x = start_date, y = max_dd, col = rebal_addition_string)) +
geom_line() +
geom_text(data = text_labels, aes(x=start_date, y = max_dd, col = label, label = label, family = "my_font")) +
scale_color_manual(values = bw_colors, guide = FALSE) +
scale_x_date(date_labels ="%Y", breaks = c(
as.Date("1930-01-01"),
as.Date("1940-01-01"),
as.Date("1950-01-01"),
as.Date("1960-01-01"),
as.Date("1970-01-01"),
as.Date("1980-01-01"),
as.Date("1990-01-01")
)) +
scale_y_continuous(label = percent_format(accuracy = 1), limits = c(-0.7, 0), breaks = seq(-0.7, 0, 0.1)) +
of_dollars_and_data_theme +
ggtitle(paste0("Maximum Drawdown for ",100*wt_stock, "/", 100*wt_bond," Portfolio\nRebalanced Annually Over ", n_years, " Years")) +
labs(x = "Start Year" , y = "Maximum Drawdown")
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- final_results %>%
filter(rebal_addition == 0, rebal_month == 1 | rebal_month == 99) %>%
mutate(rebalance_string = ifelse(rebal_month <= 12, "Rebalance Annually", "Never Rebalance"))
file_path <- paste0(out_path, "/_max_dd_rebalance_vs_not.jpeg")
text_labels <- data.frame()
text_labels[1, "start_date"] <- as.Date("1961-01-01")
text_labels[1, "max_dd"] <- -0.1
text_labels[1, "label"] <- "Rebalance Annually"
text_labels[2, "start_date"] <- as.Date("1961-01-01")
text_labels[2, "max_dd"] <- -0.45
text_labels[2, "label"] <- "Never Rebalance"
plot <- ggplot(to_plot, aes(x = start_date, y = max_dd, col = rebalance_string)) +
geom_line() +
geom_text(data = text_labels, aes(x=start_date, y = max_dd, col = label, label = label, family = "my_font")) +
scale_color_manual(values = bw_colors, guide = FALSE) +
scale_x_date(date_labels ="%Y", breaks = c(
as.Date("1930-01-01"),
as.Date("1940-01-01"),
as.Date("1950-01-01"),
as.Date("1960-01-01"),
as.Date("1970-01-01"),
as.Date("1980-01-01"),
as.Date("1990-01-01")
)) +
scale_y_continuous(label = percent_format(accuracy = 1), limits = c(-0.7, 0), breaks = seq(-0.7, 0, 0.1)) +
of_dollars_and_data_theme +
ggtitle(paste0("Maximum Drawdown for ",100*wt_stock, "/", 100*wt_bond," Portfolio\nOver ", n_years, " Years")) +
labs(x = "Start Year" , y = "Maximum Drawdown")
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- final_results %>%
filter(rebal_addition == 0, rebal_month == 1 | rebal_month == 99) %>%
mutate(rebalance_string = ifelse(rebal_month <= 12, "Rebalance Annually", "Never Rebalance"))
file_path <- paste0(out_path, "/_stock_pct_rebalance_vs_not.jpeg")
text_labels <- data.frame()
text_labels[1, "start_date"] <- as.Date("1961-01-01")
text_labels[1, "final_stock_pct"] <- 1
text_labels[1, "label"] <- "Never Rebalance"
text_labels[2, "start_date"] <- as.Date("1961-01-01")
text_labels[2, "final_stock_pct"] <- 0.45
text_labels[2, "label"] <- "Rebalance Annually"
plot <- ggplot(to_plot, aes(x = start_date, y = final_stock_pct, col = rebalance_string)) +
geom_line() +
geom_text(data = text_labels, aes(x=start_date, y = final_stock_pct, col = label, label = label, family = "my_font")) +
scale_color_manual(values = bw_colors, guide = FALSE) +
scale_y_continuous(label = percent_format(accuracy = 1), limits = c(0, 1), breaks = seq(0, 1, 0.1)) +
scale_x_date(date_labels ="%Y", breaks = c(
as.Date("1930-01-01"),
as.Date("1940-01-01"),
as.Date("1950-01-01"),
as.Date("1960-01-01"),
as.Date("1970-01-01"),
as.Date("1980-01-01"),
as.Date("1990-01-01")
)) +
of_dollars_and_data_theme +
ggtitle(paste0("Final Stock Percentage for ",100*wt_stock, "/", 100*wt_bond," Portfolio\nOver ", n_years, " Years")) +
labs(x = "Start Year" , y = "Final Stock Percentage")
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
file_path <- paste0(out_path, "/_growth_rebalance_vs_not.jpeg")
text_labels <- data.frame()
text_labels[1, "start_date"] <- as.Date("1940-01-01")
text_labels[1, "final_value"] <- 3000
text_labels[1, "label"] <- "Never Rebalance"
text_labels[2, "start_date"] <- as.Date("1970-01-01")
text_labels[2, "final_value"] <- 1000
text_labels[2, "label"] <- "Rebalance Annually"
plot <- ggplot(to_plot, aes(x = start_date, y = final_value, col = rebalance_string)) +
geom_line() +
geom_text(data = text_labels, aes(x=start_date, y = final_value, col = label, label = label, family = "my_font")) +
scale_color_manual(values = bw_colors, guide = FALSE) +
scale_y_continuous(label = dollar) +
scale_x_date(date_labels ="%Y", breaks = c(
as.Date("1930-01-01"),
as.Date("1940-01-01"),
as.Date("1950-01-01"),
as.Date("1960-01-01"),
as.Date("1970-01-01"),
as.Date("1980-01-01"),
as.Date("1990-01-01")
)) +
of_dollars_and_data_theme +
ggtitle(paste0("Final Portfolio Value for ",100*wt_stock, "/", 100*wt_bond," Portfolio\nOver ", n_years, " Years")) +
labs(x = "Start Year" , y = "Final Value of $100 Investment")
ggsave(file_path, plot, width = 15, height = 12, units = "cm") |
get_tiles <- function(x,
provider = "OpenStreetMap",
zoom,
crop = FALSE,
verbose = FALSE,
apikey,
cachedir,
forceDownload = FALSE) {
if (gdal() < "2.2.3"){
warning(paste0("Your GDAL version is ",gdal(),
". You need GDAL >= 2.2.3 to use maptiles."),
call. = FALSE)
return(invisible(NULL))
}
if(inherits(x, 'bbox')){
x <- st_as_sfc(x)
}
if(inherits(x, 'SpatRaster')){
x <- terra::as.polygons(x, extent = TRUE)
x <- terra::project(x, "epsg:4326")
x <- terra::ext(x)
} else if(inherits(x, 'SpatVector')){
x <- terra::project(x, "epsg:4326")
x <- terra::ext(x)
}
if(inherits(x, c('sf', 'sfc'))){
origin_proj <- st_crs(x)$wkt
if (nrow(x) == 1 && inherits(st_geometry(x), "sfc_POINT")) {
xt <- st_transform(x, 3857)
st_geometry(xt) <- st_buffer(st_geometry(xt), 1000)
crop <- FALSE
bbx <- st_bbox(st_transform(st_as_sfc(st_bbox(xt)), 4326))
} else {
bbx <- st_bbox(st_transform(st_as_sfc(st_bbox(x)), 4326))
cb <- st_bbox(x)
}
} else if(inherits(x, "SpatExtent")){
origin_proj <- st_crs("epsg:4326")$wkt
bbx <- as.vector(x)[c(1,3,2,4)]
cb <- bbx
} else {
stop(paste0("x should be an sf, sfc, bbox, SpatRaster,",
" SpatVector or SpatExtent object"),
call. = FALSE)
}
if (missing(zoom)) {
gz <- slippymath::bbox_tile_query(bbx)
zoom <- min(gz[gz$total_tiles %in% 4:10, "zoom"])
}
tile_grid <- slippymath::bbox_to_tile_grid(bbox = bbx, zoom = zoom)
param <- get_param(provider)
tile_grid$tiles$s <- sample(param$sub, nrow(tile_grid$tiles), replace = T)
tile_grid$src <- param$src
if(missing(apikey)){
apikey <- ""
}
tile_grid$q <- sub("XXXXXX", apikey, param$q)
tile_grid$cit <- param$cit
if (length(grep("jpg", param$q)) > 0) {
ext <- "jpg"
} else if (length(grep("png", param$q)) > 0) {
ext <- "png"
}
tile_grid$ext <- ext
images <- get_tiles_n(tile_grid, verbose, cachedir, forceDownload)
rout <- compose_tile_grid(tile_grid, images)
terra::crs(rout) <- "epsg:3857"
if(st_crs("epsg:3857")$wkt!=origin_proj){
temprast <- rast(rout)
temprast <- project(temprast, origin_proj)
terra::res(temprast) <- signif(terra::res(temprast), 3)
rout <- terra::project(rout, temprast)
rout <- terra::trim(rout)
}
rout <- terra::clamp(rout, lower = 0, upper = 255, values = TRUE)
if (crop == TRUE) {
k <- min(c(0.052 * (cb[4] - cb[2]), 0.052 * (cb[3] - cb[1])))
cb <- cb + c(-k, -k, k, k)
rout <- terra::crop(rout, cb[c(1, 3, 2, 4)])
}
RGB(rout)<- 1:3
rout
}
get_tiles_n <- function(tile_grid, verbose, cachedir, forceDownload) {
images <- apply(
X = tile_grid$tiles,
MARGIN = 1,
FUN = dl_t,
z = tile_grid$zoom,
ext = tile_grid$ext,
src = tile_grid$src,
q = tile_grid$q,
verbose = verbose,
cachedir = cachedir,
forceDownload = forceDownload
)
if (verbose) {
message(
"Zoom:", tile_grid$zoom, "\nData and map tiles sources:\n",
tile_grid$cit
)
}
images
}
dl_t <- function(x, z, ext, src, q, verbose, cachedir, forceDownload) {
if (missing(cachedir)) {
cachedir <- tempdir()
} else {
if (!dir.exists(cachedir)) dir.create(cachedir)
subdir <- paste0(cachedir, "/", src)
if (!dir.exists(subdir)) dir.create(subdir)
cachedir <- subdir
}
outfile <- paste0(cachedir, "/", src, "_", z, "_", x[1], "_", x[2], ".", ext)
if (!file.exists(outfile) | isTRUE(forceDownload)) {
q <- gsub(pattern = "{s}", replacement = x[3], x = q, fixed = TRUE)
q <- gsub(pattern = "{x}", replacement = x[1], x = q, fixed = TRUE)
q <- gsub(pattern = "{y}", replacement = x[2], x = q, fixed = TRUE)
q <- gsub(pattern = "{z}", replacement = z, x = q, fixed = TRUE)
if (verbose) {
message(q, " => ", outfile)
}
curl::curl_download(url = q, destfile = outfile)
}
outfile
}
compose_tile_grid <- function(tile_grid, images) {
bricks <- vector("list", nrow(tile_grid$tiles))
for (i in seq_along(bricks)) {
bbox <- slippymath::tile_bbox(
tile_grid$tiles$x[i], tile_grid$tiles$y[i],
tile_grid$zoom
)
img <- images[i]
if (tile_grid$ext == "png") {
img <- png::readPNG(img) * 255
if (dim(img)[3] == 4) {
nrow <- dim(img)[1]
for (j in seq_len(nrow)) {
row <- img[j, , ]
alpha <- row[, 4] == 0
row[alpha, ] <- NA
img[j, , ] <- row
}
}
}
r_img <- suppressWarnings(terra::rast(img))
if (is.null(terra::RGB(r_img))) {
terra::RGB(r_img) <- c(1,2,3)
}
terra::ext(r_img) <- terra::ext(bbox[c(
"xmin", "xmax",
"ymin", "ymax"
)])
bricks[[i]] <- r_img
}
if (length(bricks) == 1) {
rout <- bricks[[1]]
rout <- terra::merge(rout, rout)
}else{
warp_method <- function(){
out_ras <- tryCatch({
save_ras <- function(ras, .img){
name <- paste(file_path_sans_ext(.img),
'.tif', sep = "")
if (!file.exists(name)){
terra::writeRaster(ras, name)
}
return(name)
}
ras_files <- mapply(save_ras, bricks, images)
merge_path <- tempfile(fileext = '.tif')
sf::gdal_utils(util = "warp",
source = as.character(ras_files),
destination = merge_path)
outras <- terra::rast(merge_path)
return(outras)
},
error = function(e) {
warning(
"\nReceived error from gdalwarp.",
"Attempting merge using terra::merge")
outras <- do.call(terra::merge, bricks)
return(outras)
}
)
}
rout <- warp_method()
}
rout
}
get_param <- function(provider) {
if (length(provider) == 4) {
param <- provider
} else {
param <- maptiles_providers[[provider]]
}
param
} |
.t.12.dens <- function(x, u, nu) {
if (is.null(dim(u))) {
u1 <- u[1]
u2 <- u[2]
} else {
u1 <- u[, 1]
u2 <- u[, 2]
}
res.f <- -((nu * sqrt(1 - (x^2)) * (((nu + (u1^2)) * (nu + (u2^2))) /
(nu^2))^((1 + nu) / 2) * gamma(nu / 2) * gamma((2 + nu) / 2)) /
((nu * (-1 + (x^2)) - (u1^2) + 2 * x * u1 * u2 - (u2^2)) *
((nu - nu * (x^2) + (u1^2) - 2 * x * u1 * u2 + (u2^2)) /
(nu - nu * (x^2)))^(nu / 2) * (gamma((1 + nu) / 2))^2))
return(res.f)
}
.V.t <- function(u, rho, nu) {
res.f <- (-rho^3 + (2 + nu) * u[1] * u[2] + nu * (rho^2) * u[1] * u[2] -
rho * (-1 + (1 + nu) * u[1]^2 + (1 + nu) * u[2]^2)) /
((-1 + rho^2) * (-1 + rho^2 - u[1]^2 + 2 * rho * u[1] * u[2] - u[2]^2))
return(res.f)
}
.S.t <- function(u, rho, nu) {
res.f <- (1 + (rho^6) - (u[1]^4) - 2 * nu * (rho^5) * u[1] * u[2] + 2 *
(u[1]^2) * (u[2]^2) - (u[2]^4) - nu * ((u[1]^2) + (u[1]^4) +
(u[2]^2) + (u[2]^4)) + 4 * (rho^3) * u[1] * u[2] * (-2 +
(u[1]^2) + (u[2]^2) + nu * (-1 + (u[1]^2) + (u[2]^2))) + 2 *
rho * u[1] * u[2] * (2 * (2 + (u[1]^2) + (u[2]^2)) + nu *
(3 + 2 * (u[1]^2) + 2 * (u[2]^2))) - (rho^2) * (1 + (1 + nu) *
(u[1]^4) + 2 * (2 + nu) * (u[2]^2) + (1 + nu) * (u[2]^4) + 2 *
(u[1]^2) * (2 + nu + 7 * (u[2]^2) + 5 * nu * (u[2]^2))) +
(rho^4) * (-1 + (4 + 3 * nu) * (u[2]^2) + (u[1]^2) * (4 + nu *
(3 - 2 * (u[2]^2))))) / ((-1 + (rho^2))^2 * (1 - (rho^2) +
(u[1]^2) - 2 * rho * u[1] * u[2] + (u[2]^2))^2)
return(res.f)
} |
az_subscription <- R6::R6Class("az_subscription",
public=list(
id=NULL,
name=NULL,
state=NULL,
policies=NULL,
authorization_source=NULL,
token=NULL,
initialize=function(token, id=NULL, parms=list())
{
if(is_empty(id) && is_empty(parms))
stop("Must supply either subscription ID, or parameter list")
self$token <- token
if(is_empty(parms))
parms <- call_azure_rm(self$token, subscription=id, operation="")
self$id <- parms$subscriptionId
self$name <- parms$displayName
self$state <- parms$state
self$policies <- parms$subscriptionPolicies
self$authorization_source <- parms$authorizationSource
NULL
},
list_locations=function(info=c("partial", "all"))
{
info <- match.arg(info)
res <- self$do_operation("locations", http_status_handler="pass")
cont <- httr::content(res, simplifyVector=TRUE)
httr::stop_for_status(res, paste0("complete operation. Message:\n",
sub("\\.$", "", error_message(cont))))
locs <- cont$value
locs$metadata$longitude <- as.numeric(locs$metadata$longitude)
locs$metadata$latitude <- as.numeric(locs$metadata$latitude)
if(info == "partial")
cbind(locs[c("name", "displayName")], locs$metadata[c("longitude", "latitude", "regionType")])
else locs
},
get_provider_api_version=function(provider=NULL, type=NULL, which=1, stable_only=TRUE)
{
select_version <- function(api)
{
versions <- unlist(api$apiVersions)
if(stable_only)
versions <- grep("preview", versions, value=TRUE, invert=TRUE)
if(length(versions) >= which) versions[which] else ""
}
if(is_empty(provider))
{
apis <- named_list(private$sub_op("providers")$value, "namespace")
lapply(apis, function(api)
{
api <- named_list(api$resourceTypes, "resourceType")
sapply(api, select_version)
})
}
else
{
op <- construct_path("providers", provider)
apis <- named_list(private$sub_op(op)$resourceTypes, "resourceType")
if(!is_empty(type))
{
names(apis) <- tolower(names(apis))
select_version(apis[[tolower(type)]])
}
else sapply(apis, select_version)
}
},
get_resource_group=function(name)
{
az_resource_group$new(self$token, self$id, name)
},
list_resource_groups=function(filter=NULL, top=NULL)
{
opts <- list(`$filter`=filter, `$top`=top)
cont <- private$sub_op("resourcegroups", options=opts)
lst <- lapply(
if(is.null(top))
get_paged_list(cont, self$token)
else cont$value,
function(parms) az_resource_group$new(self$token, self$id, parms=parms)
)
named_list(lst)
},
create_resource_group=function(name, location, ...)
{
az_resource_group$new(self$token, self$id, name, location=location, ...)
},
delete_resource_group=function(name, confirm=TRUE)
{
if(name == "")
stop("Must supply a resource group name", call.=FALSE)
self$get_resource_group(name)$delete(confirm=confirm)
},
resource_group_exists=function(name)
{
res <- private$sub_op(construct_path("resourceGroups", name),
http_verb="HEAD", http_status_handler="pass")
httr::status_code(res) < 300
},
list_resources=function(filter=NULL, expand=NULL, top=NULL)
{
opts <- list(`$filter`=filter, `$expand`=expand, `$top`=top)
cont <- private$sub_op("resources", options=opts)
lst <- lapply(
if(is.null(top))
get_paged_list(cont, self$token)
else cont$value,
function(parms) az_resource$new(self$token, self$id, deployed_properties=parms)
)
names(lst) <- sapply(lst, function(x) sub("^.+providers/(.+$)", "\\1", x$id))
lst
},
do_operation=function(..., options=list(), http_verb="GET")
{
private$sub_op(..., options=options, http_verb=http_verb)
},
print=function(...)
{
cat("<Azure subscription ", self$id, ">\n", sep="")
cat(format_public_fields(self, exclude="id"))
cat(format_public_methods(self))
invisible(self)
}
),
private=list(
sub_op=function(op="", ...)
{
call_azure_rm(self$token, self$id, op, ...)
}
)) |
filen <- tempfile(pattern = "ggplot")
library(ggplot2)
library(datasets)
x=qplot(Sepal.Length, Petal.Length, data = iris,
color = Species, size = Petal.Width, alpha = I(0.7))
plot.fun <- function(){
print(qplot(Sepal.Length, Petal.Length, data = iris,
color = Species, size = Petal.Width, alpha = 0.7))
}
graph2svg(x=x, file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
graph2pdf(x=x, file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2eps(x=x, file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
\donttest{
x
graph2svg(file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2pdf(file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
graph2eps(file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
}
\donttest{
graph2svg(file=filen, fun = plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2pdf(file=filen, fun=plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2eps(file=filen, fun=plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
} |
library(readabs)
wpi_url <- "http://ausstats.abs.gov.au/servlet/TSSearchServlet?catno=6345.0&pg=1&ttitle=1"
test_that("WPI XML page is a data.frame with expected column names", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
wpi_1_xml <- get_xml_dfs(wpi_url)
expect_is(wpi_1_xml, "data.frame")
expect_equal(colnames(wpi_1_xml)[1], "ProductNumber")
expect_length(wpi_1_xml, 18)
expect_gt(nrow(wpi_1_xml), 26)
})
test_that("read_abs() downloads, imports, and tidies a data frame", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
wpi_1 <- read_abs("6345.0",
tables = "1", retain_files = FALSE,
check_local = FALSE, path = tempdir()
)
expect_is(wpi_1, "tbl")
expect_length(wpi_1, 12)
expect_gt(nrow(wpi_1), 2400)
expect_is(wpi_1$date, "Date")
expect_is(wpi_1$series, "character")
expect_is(wpi_1$value, "numeric")
expect_lt(Sys.Date() - max(wpi_1$date), 180)
})
test_that("read_abs() gets a whole catalogue number", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
wpi <- read_abs("6345.0", retain_files = FALSE, check_local = FALSE, path = tempdir())
expect_is(wpi, "tbl")
expect_length(wpi, 12)
expect_gt(nrow(wpi), 34000)
})
test_that("read_abs() works when retain_files = FALSE", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
wpi_7 <- read_abs("6345.0",
tables = "7a", retain_files = FALSE, check_local = F,
path = tempdir()
)
expect_is(wpi_7, "tbl")
})
test_that("read_abs() works with series ID(s)", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
cpi_2 <- read_abs(series_id = c("A2325846C", "A2325841T"), retain_files = FALSE, check_local = F, path = tempdir())
expect_is(cpi_2, "tbl")
expect_length(unique(cpi_2$series), 2)
expect_match(unique(cpi_2$series)[1], "Index Numbers ; All groups CPI ; Canberra ;")
expect_match(unique(cpi_2$series)[2], "Index Numbers ; All groups CPI ; Australia ;")
expect_length(cpi_2, 12)
cpi_wrapper <- read_abs_series(series_id = c("A2325846C", "A2325841T"), retain_files = FALSE, check_local = F, path = tempdir())
expect_identical(cpi_2, cpi_wrapper)
})
test_that("read_abs() returns appropriate errors and messages when given invalid input", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
expect_error(read_abs(cat_no = NULL))
expect_error(read_abs("6202.0", 1, retain_files = NULL, check_local = FALSE))
expect_error(read_abs(cat_no = "6345.0", metadata = 1, check_local = FALSE))
expect_error(read_abs(cat_no = "6345.0", series_id = "foo", check_local = FALSE),
regexp = "either.*cat_no.*series_id"
)
})
test_that("read_abs() works with 'table 01' as well as 'table 1' filename structures", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
const_df <- read_abs("8755.0", 1, retain_files = FALSE, check_local = FALSE, path = tempdir())
const_df_2 <- read_abs("8755.0", "1", retain_files = FALSE, check_local = FALSE, path = tempdir())
expect_is(const_df, "data.frame")
expect_equal(const_df, const_df_2)
expect_length(const_df, 12)
})
test_that("read_abs() returns an error when requesting non-existing cat_no", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
expect_error(read_abs("9999.0"))
})
test_that("read_cpi() function downloads CPI index numbers", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
cpi <- read_cpi()
expect_is(cpi, "tbl")
expect_length(cpi, 2)
expect_is(cpi$date, "Date")
expect_is(cpi$cpi, "numeric")
latest_cpi_date <- cpi$date[cpi$date == max(cpi$date)]
total_cpi_ratio <- cpi$cpi[cpi$date == latest_cpi_date] / cpi$cpi[cpi$date == min(cpi$date)]
expect_gt(total_cpi_ratio, 30)
inflation_99_to_19 <- cpi$cpi[cpi$date == as.Date("2019-09-01")] /
cpi$cpi[cpi$date == as.Date("1999-09-01")]
expect_gt(inflation_99_to_19, 1.675)
expect_lt(inflation_99_to_19, 1.685)
date_12m_before_latest <- as.POSIXlt(latest_cpi_date)
date_12m_before_latest$year <- date_12m_before_latest$year - 1
date_12m_before_latest <- as.Date(date_12m_before_latest)
latest_annual_inflation <- (cpi$cpi[cpi$date == latest_cpi_date] /
cpi$cpi[cpi$date == date_12m_before_latest]) - 1
expect_gt(latest_annual_inflation, -.005)
expect_lt(latest_annual_inflation, 0.05)
})
test_that("read_cpi() returns appropriate errors", {
skip_on_cran()
skip_if_offline()
check_abs_connection()
expect_error(read_cpi(retain_files = NULL))
expect_error(read_cpi(show_progress_bars = NULL))
expect_error(read_cpi(retain_files = TRUE, path = 1))
}) |
ProductDistribution <- R6Class("ProductDistribution",
inherit = VectorDistribution,
lock_objects = FALSE,
public = list(
initialize = function(distlist = NULL, distribution = NULL, params = NULL,
shared_params = NULL,
name = NULL, short_name = NULL,
decorators = NULL,
vecdist = NULL, ids = NULL) {
if (!is.null(vecdist)) {
checkmate::assertClass(vecdist, "VectorDistribution")
if (!is.null(decorators)) {
suppressMessages(decorate(self, decorators))
}
private$.modelTable <- vecdist$modelTable
private$.distlist <- vecdist$distlist
private$.univariate <- vecdist$.__enclos_env__$private$.univariate
private$.pdf <- vecdist$.__enclos_env__$private$.pdf
private$.cdf <- vecdist$.__enclos_env__$private$.cdf
private$.quantile <- vecdist$.__enclos_env__$private$.quantile
private$.rand <- vecdist$.__enclos_env__$private$.rand
parameters <- vecdist$parameters()
if (checkmate::testClass(vecdist, "MixtureDistribution")) {
parameters$remove(prefix = "mix")
}
super$.__enclos_env__$super$initialize(
distlist = if (vecdist$distlist) vecdist$wrappedModels() else NULL,
name = vecdist$name,
short_name = vecdist$short_name,
description = vecdist$description,
support = vecdist$properties$support,
type = vecdist$traits$type,
valueSupport = vecdist$traits$valueSupport,
variateForm = "multivariate",
parameters = parameters
)
} else {
super$initialize(
distlist = distlist,
distribution = distribution,
params = params,
shared_params = shared_params,
decorators = decorators,
name = name,
short_name = short_name,
ids = ids
)
}
if (is.null(name)) self$name <- gsub("Vector|Mixture", "Product", self$name)
if (is.null(short_name)) self$short_name <- gsub("Vec|Mix", "Prod", self$short_name)
self$description <- gsub("Vector|Mixture", "Product", self$description)
invisible(self)
},
strprint = function(n = 10) {
str <- super$strprint(n = n)
paste0(str, collapse = " X ")
},
pdf = function(..., log = FALSE, simplify = TRUE, data = NULL) {
product_dpqr_returner(
dpqr = super$pdf(..., log = log, data = data),
univariate = private$.univariate
)
},
cdf = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) {
product_dpqr_returner(
dpqr = super$cdf(..., lower.tail = lower.tail, log.p = log.p, data = data),
univariate = private$.univariate
)
},
quantile = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) {
stop("Quantile is currently unavailable for product distributions.")
}
)
)
.distr6$wrappers <- append(.distr6$wrappers, list(ProductDistribution = ProductDistribution))
`*.Distribution` <- function(x, y) {
ProductDistribution$new(list(x, y))
}
as.ProductDistribution <- function(object) {
if (checkmate::testClass(object, "VectorDistribution")) {
ProductDistribution$new(vecdist = object)
} else {
stop("Object must inherit from VectorDistribution.")
}
} |
sar_linear <- function(data, normaTest = "none", homoTest = "none",
homoCor = "spearman", verb = TRUE){
if (!(is.matrix(data) | is.data.frame(data)))
stop('data must be a matrix or dataframe')
if (is.matrix(data)) data <- as.data.frame(data)
if (anyNA(data)) stop('NAs present in data')
if (!is.logical(verb)) stop('verb should be logical')
data <- data[order(data[,1]),]
colnames(data) <- c('A','S')
mod <- lm(S ~ A, data = data)
fit <- list()
fit$par <- mod$coefficients
names(fit$par) <- c("c", "m")
res <- as.vector(mod$residuals)
squ_res <- res^2
fit$value <- sum(res^2)
fit$verge <- TRUE
fit$data <- data
fit$model$name <- "Linear model"
fit$model$formula <- "S == c + m*A"
fit$model$parNames <- c("c", "m")
fit$calculated <- as.vector(mod$fitted.values)
fit$residuals <- res
n <- dim(data)[1]
value <- sum(mod$residuals^2)
P <- 3
val <- -n * (log(2 * pi) + 1 - log(n) + log(value))/2
fit$AIC <- (2 * P) - (2 * val)
fit$AICc <- -2 * val + 2 * P * (n / (n - P - 1))
fit$BIC <- (-2 * val) + (P * log(n))
fit$R2 <- 1 - ( (value) / sum((data$S - mean(data$S))^2) )
fit$R2a <- 1 - ( ((n-1)*(value)) /
((n-P)*sum((data$S - mean(data$S))^2)))
fit$sigConf <- cbind(summary(mod)$coefficients, confint(mod))
fit$observed_shape <- "linear"
fit$asymptote <- FALSE
normaTest <- match.arg(normaTest, c("none", "shapiro", "kolmo", "lillie"))
homoTest <- match.arg(homoTest, c("none","cor.area","cor.fitted"))
if (homoTest != "none"){
homoCor <- match.arg(homoCor, c("spearman","pearson",
"kendall"))
}
if (normaTest == "shapiro") {
normaTest <- list("test" = "shapiro",
tryCatch(shapiro.test(res), error = function(e)NA))
} else if (normaTest == "lillie"){
normaTest <- list("test" = "lillie",
tryCatch(lillie.test(res), error = function(e)NA))
} else if (normaTest == "kolmo"){
normaTest <- list("test" = "kolmo",
tryCatch(ks.test(res, "pnorm"), error = function(e)NA))
} else{
normaTest <- list("test" = "none", "none")
}
if (homoTest == "cor.area"){
homoTest <- list("test" = "cor.area",
tryCatch(suppressWarnings(cor.test(squ_res,data$A,
method = homoCor)),
error = function(e)list(estimate=NA,p.value=NA)))
} else if (homoTest == "cor.fitted"){
homoTest <- list("test" = "cor.fitted",
tryCatch(suppressWarnings(cor.test(squ_res,
as.vector(mod$fitted.values),
method = homoCor)),
error = function(e)list(estimate=NA,p.value=NA)))
} else {
homoTest <- list("test" = "none", "none")
}
fit$normaTest <- normaTest
fit$homoTest <- homoTest
fit$model$exp <- expression(c + m*A)
fit$model$mod.fun <- function(A = A, par = par, model = model) {
eval(model$exp,list(A=A,c=par[1],m=par[2]))}
fit$model$rss.fun <- function(par,data, model, opt = TRUE){
S <- data$S
A <- data$A
res <- sum((S - model$mod.fun(A,par, model = model))^2)
res
}
fit$neg_check <- any(fit$calculated < 0)
class(fit) <- 'sars'
attr(fit, 'type') <- 'fit'
return(fit)
} |
gs_delete <- function(ss, verbose = TRUE) {
if (!inherits(ss, "googlesheet")) {
spf("Input must be a 'googlesheet'.\n",
"Trying to delete by title? See gs_grepdel() and gs_vecdel().")
}
key <- gs_get_alt_key(ss)
the_url <- file.path(.state$gd_base_url_files_v2, key)
req <- httr::DELETE(the_url, google_token()) %>%
httr::stop_for_status()
status <- httr::status_code(req)
if (verbose) {
if (status == 204L) {
mpf("Success. \"%s\" moved to trash in Google Drive.", ss$sheet_title)
} else {
mpf("Oops. \"%s\" was NOT deleted.", ss$sheet_title)
}
}
if(status == 204L) invisible(TRUE) else invisible(FALSE)
}
gs_grepdel <- function(regex, ..., verbose = TRUE) {
stopifnot(is.character(regex))
delete_me <- gs_ls(regex, ..., verbose = verbose)
if(is.null(delete_me)) {
invisible(NULL)
} else {
lapply(delete_me$sheet_key, function(x) {
gs_delete(gs_key(x, verbose = verbose), verbose = verbose)
}) %>%
unlist()
}
}
gs_vecdel <- function(vec, verbose = TRUE) {
stopifnot(is.character(vec))
delete_me <- gs_ls(verbose = FALSE) %>%
dplyr::filter_(~ sheet_title %in% vec)
if(nrow(delete_me)) {
lapply(delete_me$sheet_key, function(x) {
gs_delete(gs_key(x, verbose = verbose), verbose = verbose)
}) %>%
unlist()
} else {
invisible(NULL)
}
} |
coef.glmnot <- function(object, ...) {
coef(object$model, ...)
}
predict.glmnot <- function(object, newdata,
sparse = TRUE,
lambda = 'lambda.min',
type = 'response') {
if (is.data.frame(newdata)) {
if (is.null(object$xlev)) {
stop('Cannot predict from a dataframe using a glmnot object which was trained on a matrix - train using a data frame, or predict from a matrix of the same form')
}
design_matrix_method <- if (sparse) sparse.model.matrix else model.matrix
no_response_formula <- delete.response(terms(object$formula))
for (column in all.vars(no_response_formula)) {
column_data <- newdata[[column]]
if(!is.numeric(column_data)) {
column_data <- as.character(column_data)
reference_level <- object$xlev[[column]][1]
newdata[[column]] <- ifelse(column_data %in% object$xlev[[column]],
column_data, reference_level)
}
}
newdata <- design_matrix_method(no_response_formula, newdata,
xlev = object$xlev)
}
predict(object$model, newx = newdata,
s = lambda, type = type)
}
glmnot <- function(object, ...) {
UseMethod('glmnot', object)
}
glmnot.default <- function(X, y, family,
alpha = 1,
formula = NULL,
xlev = NULL,
glm_control = list()
) {
cv.glmnet.args <- list(X, y, family = family,
alpha = alpha)
cv.glmnet.args <- append(cv.glmnet.args, glm_control)
m <- do.call(cv.glmnet, cv.glmnet.args)
m$call[["x"]] <- quote(x)
m$call[["y"]] <- quote(y)
m$call[[1]] <- quote(glmnet)
structure(list(model = m,
formula = formula,
xlev = xlev), class = 'glmnot')
}
glmnot.formula <- function(formula, data, family,
alpha = 1,
type.measure = 'auc',
sparse = TRUE,
glm_control
) {
constant_factors <- colnames(
data %>%
select_if(function(column) {
if(!is.numeric(column)) {
return(n_distinct(column) < 2)
}
else {
return(FALSE)
}
})
)
final_formula <- terms(formula, data = data)
constant_factors_in_formula <- intersect(constant_factors, all.vars(final_formula))
terms_matrix <- attr(final_formula, "factors")
for (column in colnames(terms_matrix)) {
if (sum(terms_matrix[constant_factors_in_formula, column]) > 0) {
final_formula <- update(final_formula, paste('. ~ . -', column))
}
}
stopifnot(length(all.vars(final_formula)) > 1)
response_variable <- get_response(final_formula)
columns <- get_predictors(final_formula)
factor_column_indicator <- sapply(columns, function(column) {
!is.numeric(data[[column]]) && column != response_variable
})
factor_columns <- columns[factor_column_indicator]
xlev <- lapply(data %>% select(factor_columns), function(x) {
if(is.factor(x)) levels(x) else as.character(unique(x))
})
model_mat_method <- if (sparse) sparse.model.matrix else model.matrix
X <- model_mat_method(final_formula, data, xlev = xlev)
y <- data[[response_variable]]
stopifnot(nrow(X) == length(y))
glmnot(X, y, family,
alpha = alpha,
formula = final_formula,
xlev = xlev,
glm_control = glm_control)
} |
frequencies_to_stop_times <- function(gtfs) {
if (class(gtfs)[1] != "gtfs")
stop ("selected object does not appear to be a GTFS file")
if (!("frequencies" %in% names (gtfs)))
stop ("selected gtfs does not contain frequencies")
if (nrow (gtfs$frequencies) == 0)
stop ("frequencies table is empty")
need_these_columns <- c("trip_id",
"start_time",
"end_time",
"headway_secs")
checks <- vapply (need_these_columns, function (i)
any (grepl (i, names(gtfs$frequencies))), logical (1))
arrival_time <- departure_time <- end_time <-
start_time <- stop_sequence <- trip_id <- trip_id_f <- NULL
if (!all (checks))
stop ("frequencies must contain all required columns:\n ",
paste (need_these_columns, collapse = ", "))
gtfs_cp <- data.table::copy (gtfs)
gtfs_cp$frequencies[, start_time := rcpp_time_to_seconds (start_time)]
gtfs_cp$frequencies[, end_time := rcpp_time_to_seconds (end_time)]
gtfs_cp$stop_times [, trip_id_f := trip_id]
stop_times <- gtfs_cp$stop_times [0]
trips <- unique (gtfs_cp$frequencies [, trip_id])
for (trip in trips) {
n <- 1
frequencies_trip <-
gtfs_cp$frequencies [order (trip_id, start_time)] [trip_id == trip]
frequencies_trip [end_time ==
data.table::shift (start_time, 1,
type = "lead"),
end_time := end_time - 1]
stop_times_trip <-
gtfs_cp$stop_times [order (stop_sequence)] [trip_id == trip]
if (stop_times_trip [1] [["arrival_time"]] > 0) {
stop_times_trip [, c ("arrival_time", "departure_time") :=
list(
arrival_time - stop_times_trip [1] [["arrival_time"]],
departure_time - stop_times_trip [1] [["arrival_time"]]
)]
}
start_t <- min (frequencies_trip$start_time)
headway <- headway_old <- frequencies_trip [1] [["headway_secs"]]
for (i in row (frequencies_trip)) {
end_t <- frequencies_trip [i] [["end_time"]]
headway <- frequencies_trip [i] [["headway_secs"]]
ifelse (
headway_old - start_t +
frequencies_trip [i] [["start_time"]] < headway,
start_t <- start_t - headway_old + headway,
start_t <- frequencies_trip [i] [["start_time"]]
)
while (start_t < end_t) {
stop_times_trip_i <-
data.table::copy (stop_times_trip) [, c ("arrival_time",
"departure_time",
"trip_id_f") :=
list ((arrival_time + start_t),
(departure_time + start_t),
paste (trip_id, n, sep = "_"))]
n <- n + 1
stop_times <- rbind (stop_times, stop_times_trip_i)
start_t <- start_t + headway
}
headway_old <- headway
}
}
gtfs_cp$stop_times <-
rbind (gtfs_cp$stop_times [!(trip_id) %in%
gtfs_cp$frequencies$trip_id], stop_times)
trip_id_mapping <- unique(gtfs_cp$stop_times [, c("trip_id", "trip_id_f")])
gtfs_cp$trips <- merge (gtfs_cp$trips,
trip_id_mapping,
by = "trip_id",
all.y = T)
gtfs_cp$trips$trip_id <- gtfs_cp$trips$trip_id_f
gtfs_cp$trips <- subset (gtfs_cp$trips,
select = names(gtfs_cp$trips) != "trip_id_f")
gtfs_cp$stop_times$trip_id <- gtfs_cp$stop_times$trip_id_f
gtfs_cp$stop_times <- subset (gtfs_cp$stop_times,
select = names(gtfs_cp$stop_times) != "trip_id_f")
return (gtfs_cp)
} |
univariate_regression = function (X, y, Z = NULL, center = TRUE,
scale = FALSE, return_residuals = FALSE) {
y_na = which(is.na(y))
if (length(y_na)) {
X = X[-y_na,]
y = y[-y_na]
}
if (center) {
y = y - mean(y)
X = scale(X,center = TRUE,scale = scale)
} else
X = scale(X,center = FALSE,scale = scale)
X[is.nan(X)] = 0
if (!is.null(Z)) {
if (center)
Z = scale(Z,center = TRUE,scale = scale)
y = .lm.fit(Z,y)$residuals
}
output = try(do.call(rbind,
lapply(1:ncol(X), function (i) {
g = .lm.fit(cbind(1,X[,i]),y)
return(c(coef(g)[2],calc_stderr(cbind(1,X[,i]),
g$residuals)[2]))
})),
silent = TRUE)
if (inherits(output,"try-error")) {
output = matrix(0,ncol(X),2)
for (i in 1:ncol(X)) {
fit = summary(lm(y ~ X[,i]))$coef
if (nrow(fit) == 2)
output[i,] = as.vector(summary(lm(y ~ X[,i]))$coef[2,1:2])
else
output[i,] = c(0,0)
}
}
if (return_residuals && !is.null(Z))
return(list(betahat = output[,1],sebetahat = output[,2],residuals = y))
else
return(list(betahat = output[,1],sebetahat = output[,2]))
}
calc_z = function (X, Y, center = FALSE, scale = FALSE) {
univariate_z = function(X,Y,center,scale) {
out = univariate_regression(X,Y,center = center,scale = scale)
return(out$betahat/out$sebetahat)
}
if (is.null(dim(Y)))
return(univariate_z(X,Y,center,scale))
else
return(do.call(cbind,lapply(1:ncol(Y),
function(i) univariate_z(X,Y[,i],
center = center,
scale = scale))))
} |
QueryBuilder <- function(query.params.list) {
kMaxDimensions <- 4
kMaxMetrics <- 10
end.date <- query.params.list$end.date
metrics <- query.params.list$metrics
start.date <- query.params.list$start.date
title <- query.params.list$title
dimensions <- query.params.list$dimensions
filters <- query.params.list$filters
segment <- query.params.list$segment
SetQueryParams <- function() {
EndDate(end.date)
Metrics(metrics)
StartDate(start.date)
Title(title)
Dimensions(dimensions)
Filters(filters)
Segment(segment)
Title(title)
Validate()
return(invisible())
}
StartDate <- function(start.date.param = NA) {
if (is.null(start.date.param)) {
start.date <<- NULL
return(invisible())
}
if (is.na(start.date.param)) {
return(start.date)
}
if (is.na(as.Date(start.date.param, "%Y-%m-%d"))) {
stop("A start date must be specified of the form YYYY-MM-DD")
}
start.date <<- start.date.param
return(invisible())
}
EndDate <- function(end.date.param = NA) {
if (is.null(end.date.param)) {
end.date <<- NULL
return(invisible())
}
if (is.na(end.date.param)) {
return(end.date)
}
if (is.na(as.Date(end.date.param, "%Y-%m-%d"))) {
stop("An end date must be specified of the form YYYY-MM-DD")
}
end.date <<- end.date.param
return(invisible())
}
Dimensions <- function(dimensions.param = NA) {
if (is.null(dimensions.param)) {
dimensions <<- NULL
return(invisible())
}
if (is.na(dimensions.param[1])) {
return(dimensions)
}
if (!is.vector(dimensions.param)) {
stop(paste("dimensions must be a vector of string variables"))
}
if (length(dimensions.param) > kMaxDimensions) {
stop(paste("Google Analytics can only handle up to", kMaxDimensions,
"dimensions parameters"))
}
if (!is.character(dimensions.param)) {
stop(paste("dimensions must be character, please refer to the",
"Google Analytics API documentation for more information"))
}
dimensions <<- paste(dimensions.param, collapse = ",")
return(invisible())
}
Metrics <- function(metrics.param = NA) {
if (is.null(metrics.param)) {
metrics <<- NULL
return(invisible())
}
if (is.na(metrics.param[1])) {
return(metrics)
}
if (!is.vector(metrics.param)) {
stop("metrics must be a vector of string variables")
}
if (length(metrics.param) > kMaxMetrics) {
stop(paste("Google Analytics can only handle up to", kMaxMetrics,
"metrics parameters"))
}
if (!is.character(metrics.param)) {
stop(paste("metrics must be character string, please refer to the",
"Google Analytics API documentation for more information"))
}
metrics <<- paste(metrics.param, collapse = ",")
return(invisible())
}
Segment <- function(segment.param = NA) {
if (is.null(segment.param)) {
segment <<- NULL
return(invisible())
}
if (is.na(segment.param[1])) {
return(segment)
}
segment <<- segment.param
return(invisible())
}
Filters <- function(filters.param = NA) {
if (is.null(filters.param)) {
filters <<- NULL
return(invisible())
}
if (is.na(filters.param[1])) {
return(filters)
}
filters <<- filters.param
return(invisible())
}
Validate <- function() {
missing.params <- c()
if (is.null(start.date)) {
missing.params <- append(missing.params, "start.date")
}
if (is.null(end.date)) {
missing.params <- append(missing.params, "end.date")
}
if (is.null(metrics)) {
missing.params <- append(missing.params, "metrics")
}
if (is.null(title)) {
missing.params <- append(missing.params, "title")
}
if (length(missing.params) == 0) {
return(TRUE)
}
missing.string <- paste(missing.params, collapse = ", ")
stop(paste("All GA queries must have", missing.string, "parameters.",
sep = " "))
if ((as.numeric(difftime(ymd(start.date),ymd(end.date),units="days"))) < 0) {
stop("Start Date must precede End date. Please correct the dates and re-initialize the query")
}
}
ClearData <- function() {
start.date <<- NULL
end.date <<- NULL
dimensions <<- NULL
metrics <<- NULL
segment <<- NULL
filters <<- NULL
title <<- NULL
return(invisible())
}
Title <- function(title.param = NA) {
if (is.null(title.param)) {
title <<- NULL
return(invisible())
}
if (is.na(title.param[1])) {
return(title)
}
if (!is.character(title.param)) {
stop("title must be a string")
}
title <<- title.param
return(invisible())
}
SetStartDate <- function(start.date) {
StartDate(start.date)
}
GetStartDate <- function() {
return(start.date)
}
SetEndDate <- function(end.date) {
EndDate(end.date)
}
GetEndDate <- function() {
return(end.date)
}
return(list("end.date" = EndDate,
"metrics" = Metrics,
"start.date" = StartDate,
"title" = Title,
"dimensions" = Dimensions,
"filters" = Filters,
"segments" = Segment,
"clear.data" = ClearData,
"Validate" = Validate,
"GetStartDate" = GetStartDate,
"GetEndDate" = GetEndDate,
"SetEndDate" = SetEndDate,
"SetStartDate" = SetStartDate,
"SetQueryParams" = SetQueryParams))
} |
[
{
"title": "Introducing passivetotal – R Package To Work With the PassiveTotal API",
"href": "http://datadrivensecurity.info/blog/posts/2015/Jun/introducing-passivetotal/"
},
{
"title": "Deploying Shiny apps with shinyapps.io",
"href": "http://brooksandrew.github.io/simpleblog/articles/deploying-apps-with-shinyapps-io/"
},
{
"title": "drat 0.0.4: Yet more features and documentation",
"href": "http://dirk.eddelbuettel.com/blog/2015/05/27/"
},
{
"title": "Big Data and Chess: What are the Predictive Point Values of Chess Pieces?",
"href": "http://www.sumsar.net/blog/2015/06/big-data-and-chess/"
},
{
"title": "R for Quants, Part I.A",
"href": "https://cartesianfaith.com/2012/02/12/r-for-quants-part-i-a/"
},
{
"title": "An R package for Smith-Wilson yield curves",
"href": "http://www.not-normal-consulting.co.uk/2013/06/an-r-package-for-smith-wilson-yield.html"
},
{
"title": "On the acceptance of R",
"href": "http://www.burns-stat.com/on-the-acceptance-of-r/?utm_source=rss&utm_medium=rss&utm_campaign=on-the-acceptance-of-r"
},
{
"title": "R/Python Web Apps",
"href": "https://web.archive.org/web/http://notebookonthewebs.tumblr.com/post/24844687471"
},
{
"title": "Learning R — Installing Packages",
"href": "http://mazamascience.com/WorkingWithData/?p=728"
},
{
"title": "Floating Point Arithmetic and The Descent into Madness",
"href": "http://www.johnmyleswhite.com/notebook/2012/04/13/floating-point-arithmetic-and-the-descent-into-madness/"
},
{
"title": "OECD Statistics",
"href": "https://web.archive.org/web/http://www.cybaea.net/Blogs/Data/OECD-Statistics.html"
},
{
"title": "Reference semantics in R",
"href": "http://ipub.com/reference-semantics/"
},
{
"title": "Pacific Decadal Oscillation and Brazilian Hydroelectricity generation",
"href": "http://random-miner.blogspot.com/2013/01/pacific-decadal-oscillation-and.html"
},
{
"title": "Overlay of design matrices in genetic analysis",
"href": "http://www.quantumforest.com/2012/10/overlay-of-design-matrices-in-genetic-analysis/"
},
{
"title": "Converting an R object to text, with dput()",
"href": "http://is-r.tumblr.com/post/31918894953/converting-an-r-object-to-text-with-dput"
},
{
"title": "Paired t-test in R Exercises",
"href": "http://r-exercises.com/2016/09/21/paired-t-test-in-r/"
},
{
"title": "New package \"dplyrr\" – Utilities for comfortable use of dplyr with databases",
"href": "http://mockquant.blogspot.com/2015/08/new-package-dplyrr-utilities-for.html"
},
{
"title": "What’s new in futile.matrix 1.1.2",
"href": "https://cartesianfaith.com/2012/02/07/whats-new-in-futile-matrix-1-1-2/"
},
{
"title": "Translating Weird R Errors",
"href": "http://rforpublichealth.blogspot.com/2013/01/translating-weird-r-errors.html"
},
{
"title": "Textual Healing Part II",
"href": "http://is-r.tumblr.com/post/35769073499/textual-healing-part-ii"
},
{
"title": "KEGG enrichment analysis with latest online data using clusterProfiler",
"href": "https://web.archive.org/web/http://ygc.name/2015/02/01/kegg-enrichment-analysis-with-latest-online-data-using-clusterprofiler/"
},
{
"title": "Wickham R short course",
"href": "http://andrewgelman.com/2011/11/14/wickham-r-short-course/"
},
{
"title": "ExCytR Concept",
"href": "https://imdevsoftware.wordpress.com/2012/12/01/excytr-concept/"
},
{
"title": "Age-Period-Cohort models and the decline of violence",
"href": "https://blog.diegovalle.net/2012/10/age-period-cohort-models-and-decline-of.html"
},
{
"title": "Tracking the Frequency of Twitter Hashtags with R",
"href": "http://www.michaelbommarito.com/2011/02/21/tracking-the-frequency-of-twitter-hashtags-with-r/"
},
{
"title": "Visualizing Bikeshare Data",
"href": "http://mazamascience.com/WorkingWithData/?p=1670"
},
{
"title": "Principal Components Regression in R: Part 2",
"href": "http://blog.revolutionanalytics.com/2016/05/principal-components-regression-part-2.html"
},
{
"title": "Rmathlib and kdb+ part 3: Utility Functions",
"href": "http://www.theresearchkitchen.com/archives/896"
},
{
"title": "High Performing Predictive Analytics with R and Hadoop",
"href": "http://blog.revolutionanalytics.com/2013/07/high-performing-predictive-analytics-with-r-and-hadoop.html"
},
{
"title": "New R User Group – Manchester R",
"href": "https://web.archive.org/web/http://www.oddbar.co.uk/odder"
},
{
"title": "Bayesian Modeling of Anscombe’s Quartet",
"href": "http://www.sumsar.net/blog/2013/06/bayesian-modeling-of-anscombes-quartet/"
},
{
"title": "hmm: implementation of viterbi algorithm (Durbin, 1998) Part 1",
"href": "https://mintgene.wordpress.com/2012/01/28/hmm-implementation-of-viterbi-algorithm-durbin-1998-part-1/"
},
{
"title": "Visualizing asylum statistics",
"href": "https://web.archive.org/web/http://re-design.dimiter.eu/2014/05/30/visualizing-asylum-statistics/"
},
{
"title": "Basic R: rows that contain the maximum value of a variable",
"href": "https://nsaunders.wordpress.com/2013/02/13/basic-r-rows-that-contain-the-maximum-value-of-a-variable/"
},
{
"title": "Embedding a time series with time delay in R — Part II",
"href": "http://www.fromthebottomoftheheap.net/2011/06/14/embedding-a-time-series-with-time-delay-in-r-part-ii/"
},
{
"title": "We keep breaking records ? so what ?… Get statistical perspective….",
"href": "http://blog.free.fr/"
},
{
"title": "Oracle R Enterprise 1.3 released",
"href": "https://blogs.oracle.com/R/entry/oracle_r_enterprise_1_3"
},
{
"title": "Another great year together. Have a good vacation!",
"href": "http://www.milanor.net/blog/another-great-year-together-have-a-nice-holiday/"
},
{
"title": "How does Practical Data Science with R stand out?",
"href": "http://www.win-vector.com/blog/2014/06/how-does-practical-data-science-with-r-stand-out/?utm_source=rss&utm_medium=rss&utm_campaign=how-does-practical-data-science-with-r-stand-out"
},
{
"title": "The stupidest R code ever",
"href": "https://kbroman.wordpress.com/2011/08/17/the-stupidest-r-code-ever/"
},
{
"title": "R Tutorial Series: Labeling Data Points on a Plot",
"href": "https://feedproxy.google.com/~r/RTutorialSeries/~3/QjNHdDrfhwM/r-tutorial-series-labeling-data-points.html"
},
{
"title": "Why an inverse-Wishart prior may not be such a good idea",
"href": "https://dahtah.wordpress.com/2012/03/07/why-an-inverse-wishart-prior-may-not-be-such-a-good-idea/"
},
{
"title": "Why you need version control",
"href": "http://ellisp.github.io/blog/2016/09/16/version-control"
},
{
"title": "New book release: Data Mining Applications with R",
"href": "https://rdatamining.wordpress.com/2013/12/23/new-book-release-data-mining-applications-with-r/"
},
{
"title": "Updating to R 2.15, warnings in R and an updated function list for Serious Stats",
"href": "https://seriousstats.wordpress.com/2012/05/27/updating-to-r-2-15/"
},
{
"title": "R/Finance 2014 Call for Papers",
"href": "http://blog.fosstrading.com/2013/10/rfinance-2014-call-for-papers.html"
},
{
"title": "Only Load Data If Not Already Open in R",
"href": "http://blog.mollietaylor.com/2013/09/only-load-data-if-not-already-open-in-r.html"
},
{
"title": "Generate MP3 waveforms with Ruby and R",
"href": "https://blog.saush.com/2011/03/24/generate-mp3-waveforms-with-ruby-and-r/"
},
{
"title": "Inferring the community structure of networks",
"href": "https://sieste.wordpress.com/2012/05/21/inferring-the-community-structure-of-networks/"
},
{
"title": "A surprising(?) prediction about the S&P 500",
"href": "http://blog.revolutionanalytics.com/2011/07/a-surprising-prediction-about-the-sp-500.html"
}
] |
percent.table=function(x,y=NULL){
if (is.null(y)) {
100*table(x)/length(x)
} else {
100*table(x,y)/length(x)
}
} |
ARCokrig <- function(formula=list(~1,~1), output, input, cov.model="matern_5_2", nugget.est=FALSE,
input.new, prior=list(), opt=list(), NestDesign=TRUE, tuning=list(), info=list()){
.check.arg.ARCokrig(formula=formula, output=output, input=input,
input.new=input.new, prior=prior, opt=opt,
NestDesign=NestDesign, tuning=tuning)
obj = cokm(formula=formula, output=output, input=input, cov.model=cov.model,
nugget.est=nugget.est, prior=prior, opt=opt, NestDesign=NestDesign,
tuning=tuning, info=info)
obj = cokm.fit(obj)
pred = cokm.predict(obj=obj, input.new=input.new)
return(list(obj=obj, cokrig=pred))
}
.check.arg.ARCokrig <- function(formula, output, input, input.new,
prior, opt, NestDesign, tuning){
if(!is(formula, "list")){
stop("\n\n formula should be a list contaning the regressors at each code level.\n\n")
}
if(!is(output, "list")){
stop("\n\noutput should be a list of responses. Each element in a list should
contain output from a code level. The first level should contain
output from the code with the lowest fidelity.\n\n")
}
s = length(output)
if(!is(input, "list")){
stop("\n\ninput should be a list of inputs in computer models.\n\n")
}
for(t in 1:s){
if(!is(input[[t]], "matrix")){
message("\n\n coerce input to a matrix format.\n\n")
input[[t]] = as.matrix(input[[t]])
}
}
if(!is(input.new, "matrix")){
stop("\n\ninput.new should be a matrix.\n\n")
}
if(!is(prior, "list")){
stop("\n\nhyperparam should be a list containing parameters
to setup the prior distributions.\n\n")
}
if(!is(opt, "list")){
stop("\n\nopt should be a list with each element containing optimization arguments
at each code level.\n\n")
}
if(!is(NestDesign, "logical")){
stop("NestDesign should be a logical value indicating whether the design is
hierarchically nested.")
}
if(!is(tuning, "list")){
stop("\n\n tuning should be a list containing tuning parameters to setup the
MCEM algorithm in non-nested design.\n")
}
} |
tree_a <- rtree(100)
tree_b <- rtree(100)
n <- 10
trees <- rmtree(n,100)
l <- runif(1)
test_that("treeVec calculated at lambda equals treeVec function evaluated at lambda", {
expect_equal(treeVec(tree_a,l),treeVec(tree_a,return.lambda.function=TRUE)(l))
})
test_that("treeDist calculated at lambda equals treeDist function evaluated at lambda", {
expect_equal(treeDist(tree_a,tree_b,l),treeDist(tree_a,tree_b,return.lambda.function=TRUE)(l))
})
test_that("multiDist calculated at lambda equals multiDist function evaluated at lambda", {
expect_equal(multiDist(trees,l),multiDist(trees,return.lambda.function=TRUE)(l))
})
test_that("refTreeDist calculated at lambda equals refTreeDist function evaluated at lambda", {
expect_equal(refTreeDist(tree_a,trees,l),refTreeDist(tree_a,trees,return.lambda.function=TRUE)(l))
})
test_that("treeDist equals Euclidean distance between corresponding vectors", {
expect_equal(treeDist(tree_a,tree_b), sqrt(sum((treeVec(tree_a) - treeVec(tree_b))^2)))
expect_equal(treeDist(tree_a,tree_b,emphasise.tips = c("t1","t2")), sqrt(sum((treeVec(tree_a,emphasise.tips = c("t1","t2")) - treeVec(tree_b,emphasise.tips = c("t1","t2")))^2)))
})
test_that("treeDist equals corresponding entry of multiDist", {
expect_equal(treeDist(trees[[1]],trees[[2]]), multiDist(trees)[1])
expect_equal(treeDist(trees[[1]],trees[[2]],emphasise.tips = c("t1","t2")), multiDist(trees,emphasise.tips = c("t1","t2"))[1])
})
test_that("treeDist equals corresponding entry of refTreeDist", {
expect_equal(treeDist(tree_a,trees[[1]]), refTreeDist(tree_a,trees)[[1]])
expect_equal(treeDist(tree_a,trees[[1]],emphasise.tips = c("t1","t2")), refTreeDist(tree_a,trees,emphasise.tips = c("t1","t2"))[[1]])
})
test_that("multiDist equals the distance matrix from treespace", {
treedistMatrix <- treespace(trees,nf=2)$D
treedistMatrix0.5 <- treespace(trees,nf=2,lambda=l)$D
multidistMatrixFunction <- multiDist(trees,return.lambda.function=TRUE)
expect_equal(multidistMatrixFunction(0)[n],treedistMatrix[n])
expect_equal(multidistMatrixFunction(l)[n],treedistMatrix0.5[n])
expect_equal(treespace(trees,nf=2,emphasise.tips=c("t1","t2"))$D[n],multiDist(trees,emphasise.tips=c("t1","t2"))[n])
})
test_that("medTree results are consistent with treeVec", {
geom <- medTree(trees)
expect_equal(geom$mindist,sqrt(sum((geom$centre - treeVec(geom$trees[[1]]))^2)))
expect_equal(geom$mindist,min(geom$distances))
})
test_that("medTree results are consistent whether the trees or their vectors are supplied", {
expect_equal(medTree(trees)$mindist,medTree(treespace(trees,nf=2, return.tree.vectors = TRUE)$vectors)$mindist)
})
catTree <- rtree(5)
indTree1 <- simulateIndTree(catTree, permuteTips = FALSE)
indTree2 <- simulateIndTree(catTree, permuteTips = FALSE)
df <- cbind(sort(rep(catTree$tip.label,5)),sort(indTree1$tip.label))
test_that("indTrees are fully concordant with catTree", {
expect_equal(treeConcordance(catTree,indTree1,df),1)
expect_equal(treeConcordance(catTree,indTree2,df),1)
})
test_that("indTree and catTree should be identical by relatedTreeDist measure", {
expect_equal(relatedTreeDist(list(indTree1,indTree2),df)[1],0)
})
test_that("collapsing indTrees gets catTree back", {
expect_equal(treeDist(makeCollapsedTree(indTree1,df),catTree),0)
expect_equal(treeDist(makeCollapsedTree(indTree2,df),catTree),0)
})
test_that("save_memory version of multiDist equals normal multiDist", {
expect_equal(multiDist(trees,save.memory=TRUE), multiDist(trees))
expect_equal(multiDist(trees,l,save.memory=TRUE), multiDist(trees,l))
})
test_that("save_memory version of medTree equals normal medTree", {
expect_equal(medTree(trees,save.memory=TRUE)$centre, as.numeric(medTree(trees)$centre))
})
test_that("error is given if lambda is outside of [0,1]", {
expect_error(treeVec(tree_a,-1))
expect_error(treeVec(tree_a,2))
expect_error(treeDist(tree_a,tree_b,-1))
expect_error(treeDist(tree_a,tree_b,2))
expect_error(multiDist(trees,-1))
expect_error(multiDist(trees,2))
expect_error(medTree(trees,-1))
expect_error(medTree(trees,2))
})
test_that("error is given if input is not of class phylo / multiphylo", {
expect_error(treeVec(trees))
expect_error(treeDist(trees))
expect_error(multiDist(tree_a))
expect_error(medTree(tree_a))
expect_error(findGroves(tree_a))
})
test_that("error is given if input tree is unrooted", {
unrootedtree <- read.tree(text="(A:1,B:1,C:1);")
expect_error(treeVec(unrootedtree))
})
test_that("warning is given if tree edge lengths are not defined and lambda>0 or return.lambda.function=T, then they are set to 1", {
newicktree <- read.tree(text="((A,B),C);")
expect_warning(treeVec(newicktree, lambda=0.5))
expect_warning(treeVec(newicktree, return.lambda.function = TRUE))
})
test_that("error is given if trees have different tip labels", {
tree_c <- rtree(99)
tree_d <- tree_a
tree_d$tip.label <- 1:100
expect_error(treeDist(tree_a,tree_c))
expect_error(treeDist(tree_a,tree_d))
})
test_that("error is given if weights vector is not of length n", {
expect_error(medTree(trees,weights=rep(1,n+1)))
expect_error(medTree(trees,weights=rep(1,n+1),return.lambda.function=TRUE))
})
test_that("warning is given for the combination return.lambda.function=TRUE, save.memory=TRUE", {
expect_warning(multiDist(trees,return.lambda.function=TRUE, save.memory=TRUE))
expect_warning(medTree(trees,return.lambda.function=TRUE, save.memory=TRUE))
})
tree1 <- cbind(Infector=1:6, Infectee=2:7)
tree2 <- tree1[sample(1:6),]
matList <- list(findMRCIs(tree1)$mrciDepths, findMRCIs(tree2)$mrciDepths)
test_that("transmission tree distances are independent of the node naming order", {
expect_equal(0, wiwTreeDist(matList, sampled=1:7)[1])
}) |
.pseudoCluster <- function(x, size=3L, distance=1.00235, tolerance=1e-4) {
if (size < 2L) {
stop("The ", sQuote("size"), " of a cluster has to be at least 2!")
}
mm <- matrix(x, nrow=size, ncol=length(x) * length(distance), byrow=TRUE)
ms <- mm + (rep(distance, each=size) * 0L:(size - 1L))
i <- match.closest(ms, x, tolerance=mm * tolerance)
dim(i) <- dim(ms)
i[, !is.na(colSums(i)), drop=FALSE]
}
.F <- function(x)0.000594 * x + 0.03091
.P <- function(x, isotopes)dpois(isotopes, .F(x))
.Psum <- function(x, isotopes) {
ni <- length(isotopes)
nx <- length(x)
p <- .P(rep.int(x, rep.int(ni, nx)), isotopes)
dim(p) <- c(ni, nx)
t(t(p) / colSums(p))
}
.monoisotopicPattern <- function(x, y, minCor=0.95, tolerance=1e-4,
distance=1.00235, size=3L) {
pc <- .pseudoCluster(x, size=size, distance=distance, tolerance=tolerance)
y <- y[pc]
dim(y) <- dim(pc)
y <- t(t(y)/colSums(y))
p <- .Psum(x[pc[1L,]], isotopes=0L:(size-1L))
cr <- .colCors(y, p)
pc <- pc[, cr > minCor, drop=FALSE]
pc[duplicated(as.vector(pc))] <- NA_real_
pc[, !is.na(colSums(pc)), drop=FALSE]
}
.monoisotopic <- function(x, y, size=3L:10L, ...) {
if (length(x) && length(x) == length(y)) {
pattern <- lapply(sort.int(size, decreasing=TRUE),
function(s).monoisotopicPattern(x=x, y=y, size=s, ...))
upattern <- .unlist(pattern)
upattern[duplicated(upattern)] <- NA_real_
upattern <- relist(upattern, pattern)
sort.int(.unlist(lapply(upattern,
function(p)p[1L, !is.na(colSums(p))])))
} else {
double()
}
} |
designScore <- function ( genotype, array.allocation, condition.allocation,
nEnvFactors, nLevels, Level, nConditions, weight=1,
optimality="A", bTwoColorArray, envFactorNames )
{
genotype.level <- NULL
if( bTwoColorArray )
{
genotype <- as.matrix(genotype)
for( i in 1:nrow(array.allocation) )
{
RIL.red <- which(array.allocation[i,] == 1)
RIL.green <- which(array.allocation[i,] == -1)
genotype.level <- cbind(genotype.level,
genotype[,c(RIL.red,RIL.green)])
}
}else{
ril.all <- NULL
for( i.cond in 1:nrow(condition.allocation) )
{
ril <- which(condition.allocation[i.cond,]!=0)
ril.all <- c(ril.all,ril)
}
genotype.level <- genotype[,ril.all]
}
genotype.level[is.na(genotype.level)] <- 0.5
ril.names1 <- colnames(genotype.level)
if( nEnvFactors == 0 )
{
genotype.matrix <- pairLevel( t(genotype.level),ril.names1 )
sc <- apply(genotype.matrix, 2,
function(x) (length(x)+sum(x^2))/(length(x)*sum(x^2)-sum(x)^2) )
sc.temp <- sum(sc)
if(sc.temp==0) sc.temp <- 1e-20
SC <- 1/ sc.temp
}else{
condition.combination <- conditionCombination ( nEnvFactors, nLevels,
Level,envFactorNames)
condition.level <- conditionLevel ( array.allocation,
condition.allocation, condition.combination,
nEnvFactors)
SC <- 0
for( markerIndex in 1:nrow(genotype.level) )
{
interact.level <- interactionLevel ( genotype.level,
condition.level, markerIndex, nEnvFactors)
if( bTwoColorArray )
{
ril.names1 <- colnames(condition.allocation)
genotype.matrix <- pairLevel(genotype.level[markerIndex
,], ril.names1)
env.matrix <- pairLevel( condition.level,
ril.names1 )
colnames(env.matrix) <- colnames(condition.level)
interact.matrix <- pairLevel( interact.level,
ril.names1)
colnames(interact.matrix)<- colnames(interact.level)
}else{
genotype.matrix <- t(as.matrix( genotype.level[markerIndex,] ))
env.matrix <- as.matrix(condition.level)
interact.matrix <- as.matrix(interact.level)
}
design.matrix <- cbind( rep(1,nrow(genotype.matrix)),
genotype.matrix, env.matrix, interact.matrix )
colnames(design.matrix)[1:2] <- c("Intercept","Q")
rownames(design.matrix) <- paste(rownames(genotype.matrix),
"onArray",seq(1,nrow(genotype.matrix)),
sep="" )
if( optimality == "A" )
{
X <- as.matrix(design.matrix)
xtx <- t(X) %*% X
singular <- function (x)
{
return (sum(round(eigen(x, TRUE, TRUE)$values, 5) == 0) > 0)
}
if( singular(xtx) )
{
sc <- 0
}else{
sc.temp <- sum( weight*diag(solve(xtx)) )
if( sc.temp==0 ) { sc.temp <- 1e-20}
sc <- 1/sc.temp
}
}
if( optimality == "D" )
{
x <- as.matrix(design.matrix)
xtx <- t(x) %*% x
sc <- det(xtx)
}
SC <- SC + sc
}
}
return(SC)
} |
print.ipcwcompetingrisksSeSpPPVNPV <- function(x,No.lines=5,digits=2,...){
if(x$iid==TRUE){
tab_ou_print<-round(cbind(x$Stats[,1:4],
x$TP*100,x$inference$vect_se_Se*100,
(1-x$FP_1)*100,x$inference$vect_se_Sp1*100,
(1-x$FP_2)*100,x$inference$vect_se_Sp2*100,
x$PPV*100,x$inference$vect_se_PPV*100,
x$NPV_1*100,x$inference$vect_se_NPV1*100,
x$NPV_2*100,x$inference$vect_se_NPV2*100
),digits=digits)
colnames(tab_ou_print)<-c("Cases","Survivors","Other events","Censored",
"Se","se_Se","Sp_1","se_Sp1","Sp_2","se_Sp_2",
"PPV (%)","se_PPV","NPV_1","se_NPV_1","NPV_2","se_NPV_2")
}
else{
tab_ou_print<-round(cbind(x$Stats[,1:4],
x$TP*100,
(1-x$FP_1)*100,
(1-x$FP_2)*100,
x$PPV*100,
x$NPV_1*100,
x$NPV_2*100
),digits=digits)
colnames(tab_ou_print)<-c("Cases","Survivors","Other events","Censored",
"Se","Sp_1","Sp_2",
"PPV (%)","NPV_1","NPV_2"
)
}
cat(paste("Predictive accuracy measures at cutpoint c=",x$cutpoint," estimated using IPCW (n=",x$n, ", with competing risks). \n",sep=""))
cat(paste("No. of positive (X>c) =",x$Stats[1,5],", \n",sep=""))
cat(paste("No. of negative (X<=c) =",x$Stats[1,6],". \n",sep=""))
l<-length(x$times)
if(l<=No.lines){ print(tab_ou_print) }
else{print(tab_ou_print[unique(round(quantile(1:length(x$times),probs=seq(0,1,length.out=No.lines)),0)),])}
cat("\n")
cat("Method used for estimating IPCW:")
cat(paste(x$weights$method,"\n"))
cat("\n")
cat("Total computation time :",round(x$computation_time,2)," secs.")
cat("\n")
} |
NULL
CDProtocol <- R6::R6Class(
"CDProtocol",
public = list(
initialize = function(host = "localhost", port = 9222, secure = FALSE, local = TRUE) {
protocol <- fetch_protocol(host = host, port = port, secure = secure, local = local)
protocol <- add_names_to_protocol(protocol)
protocol <- rlist2env(protocol)
private$.protocol <- protocol
},
domain_description = function(domain) {
desc <- rlang::env_get(env = private$.protocol$domains, nm = domain)$description
if(is.null(desc)) {
desc <- ""
}
desc
},
is_domain_experimental = function(domain) {
isTRUE(private$.protocol$domains[[domain]]$experimental)
},
list_commands = function(domain) {
private$.list_objects(domain, "commands")
},
get_formals_for_command = function(domain, command) {
params_env <- private$.protocol$domains[[domain]]$commands[[command]]$parameters
if(is.null(params_env)) {
params_names <- character(0)
} else {
params_names <- purrr::set_names(ls(params_env))
}
stopifnot(!("callback" %in% params_names))
params_optional <- purrr::map_lgl(params_names, ~ isTRUE(params_env[[.x]]$optional))
if(length(params_optional) > 0) {
params_optional <- sort(params_optional)
}
params_optional <- c(params_optional, callback = TRUE)
text <- paste0(
"alist(",
paste(names(params_optional), ifelse(params_optional, "NULL", ""), sep = " = ", collapse = ", "),
")"
)
eval(parse(text = text))
},
list_events = function(domain) {
private$.list_objects(domain, "events")
},
get_formals_for_event = function(domain, event) {
params_env <- private$.protocol$domains[[domain]]$events[[event]]$parameters
if(is.null(params_env)) {
params_names <- character(0)
} else {
params_names <- ls(params_env)
}
stopifnot(!("callback" %in% params_names))
params_names <- c(params_names, "callback")
res <- vector("list", length(params_names))
names(res) <- params_names
res
},
list_types = function(domain) {
private$.list_objects(domain, "types")
}
),
active = list(
domains = function() {
ls(private$.protocol$domains)
}
),
private = list(
.protocol = "environment",
.list_objects = function(domain, cl) {
specs <- rlang::env_get(env = private$.protocol$domains, nm = domain)[[cl]]
if(is.null(specs)) return(list())
obj_names <- ls(specs)
l <- as.list(paste(domain, obj_names, sep = "."))
names(l) <- obj_names
l
}
)
)
rlist2env <- function(.l) {
if (!is.list(.l)) return(.l)
list2env(purrr::map(.l, rlist2env), parent = emptyenv())
}
add_names_to_protocol <- function(protocol) {
protocol$domains <- purrr::map(protocol$domains, add_names_to_domain)
names(protocol$domains) <- purrr::map_chr(protocol$domains, "domain")
protocol
}
add_names_to_domain <- function(domain) {
if(!is.null(domain$dependencies)) {
domain$dependencies <- unlist(domain$dependencies)
}
if(!is.null(domain$types)) {
domain$types <- purrr::map(domain$types, add_names_to_type)
names(domain$types) <- purrr::map_chr(domain$types, "id")
}
if(!is.null(domain$commands)) {
domain$commands <- purrr::map(domain$commands, add_names_to_method)
names(domain$commands) <- purrr::map_chr(domain$commands, "name")
}
if(!is.null(domain$events)) {
domain$events <- purrr::map(domain$events, add_names_to_method)
names(domain$events) <- purrr::map_chr(domain$events, "name")
}
domain
}
add_names_to_type <- function(type) {
if(!is.null(type$properties)) {
names(type$properties) <- purrr::map_chr(type$properties, "name")
}
type
}
add_names_to_method <- function(method) {
if(!is.null(method$parameters)) {
names(method$parameters) <- purrr::map_chr(method$parameters, "name")
}
if(!is.null(method$returns)) {
names(method$returns) <- purrr::map_chr(method$returns, "name")
}
method
}
renv2list <- function(e, discard = NULL) {
if(!rlang::is_environment(e)) return(e)
names <- purrr::discard(ls(e), ~ .x %in% discard)
names <- rlang::set_names(names)
purrr::map(names, ~ renv2list(e[[.x]], discard))
} |
kink_estimator <- function(earnings, zstar, t1, t2,
cf_start = NA, cf_end = NA,
exclude_before = 2, exclude_after = 2, binw = 10,
poly_size = 7, convergence = 0.01, max_iter = 100,
correct = TRUE, select = TRUE, draw = TRUE,
title = "Bunching Visualization", varname = "Earnings") {
if (is.na(cf_start)) {
cf_start <- 20
warning("cf_start not specified, using 20 bins as default")
}
if (is.na(cf_end)) {
cf_end <- 20
warning("cf_end not specified, using 20 bins as default")
}
if (t1 > t2) {
stop("This function only analyzes convex kinks. Set t1 < t2.")
}
if (t1 == t2) {
stop("No change in marginal tax rate - can't calculate elasticity!")
}
useful_calc <- ceiling( (zstar - min(earnings)) / binw )
bunch_hist <- graphics::hist(earnings,
breaks=seq(from=floor((zstar - useful_calc * binw)) - binw / 2,
to=(ceiling(max(earnings) + binw)), by = binw),
plot=FALSE)
if(!zstar %in% bunch_hist$mids) {
stop("Problem with histogram")
}
remove(useful_calc)
reg_data <- as.data.frame(bunch_hist$mids)
reg_data$counts <- bunch_hist$counts
reg_data$cf_counts <- bunch_hist$counts
colnames(reg_data) <- c("mid","counts","cf_counts")
saved_data <- reg_data[reg_data$mid < zstar - cf_start * binw |
reg_data$mid > zstar + cf_end * binw,]
saved_data$cf_counts <- NA
saved_data$excluded <- NA
reg_data <- reg_data[reg_data$mid >= zstar - cf_start * binw &
reg_data$mid <= zstar + cf_end * binw,]
excluded_list <- reg_data$mid[(reg_data$mid >= zstar - exclude_before * binw) &
(reg_data$mid <= zstar + exclude_after * binw)]
reg_data$excluded <- as.numeric(!reg_data$mid %in% excluded_list)
for (i in excluded_list) {
reg_data$excluded[reg_data$mid == i] <- 1 + which(excluded_list == i)
}
reg_data$excluded <- as.factor(reg_data$excluded)
cheat_excluded <- data.frame(as.factor(c(rep("1",dim(reg_data)[1]))))
colnames(cheat_excluded) <- "excluded"
vars <- "~ excluded"
for (i in 1:poly_size) {
vars <- paste0(vars," + I(mid^",i,")" )
}
null <- stats::lm(counts ~ excluded, data=reg_data)
full <- stats::lm(stats::as.formula(paste0("counts ",vars)), data=reg_data)
if (select == TRUE) {
reg_naive <- stats::step(full, scope = list(lower = null, upper = full),
direction = "backward",trace = 0)
} else {reg_naive <- full}
remove(null,full)
naive_B <- sum(reg_naive$coefficients[2:(length(excluded_list) + 1)])
reg_data$cf_counts <- stats::predict(reg_naive,cbind(reg_data[,c(1,2)],cheat_excluded))
counter <- 1
if (correct == TRUE) {
old_B <- naive_B
new_B <- 0
reg_data$extra <- reg_data$counts *
as.numeric(reg_data$mid > zstar + exclude_after * binw) *
old_B /
sum(bunch_hist$counts[bunch_hist$mids > zstar + exclude_after * binw])
while( (abs(new_B - old_B)) / old_B > convergence &
counter < max_iter) {
if (!counter == 1) {
old_B <- new_B
reg_data$extra <- reg_data$counts *
as.numeric(reg_data$mid > zstar + exclude_after * binw) *
old_B /
sum(bunch_hist$counts[bunch_hist$mids > zstar + exclude_after * binw])
}
null <- stats::lm(counts + extra ~ excluded, data = reg_data)
full <- stats::lm(stats::as.formula(paste0("counts + extra ",vars)), data = reg_data)
if (select==TRUE) {
temp_reg <- stats::step(full, scope=list(lower=null, upper=full),
direction="backward",trace=0)
} else {temp_reg <- full}
new_B <- sum((temp_reg)$coefficients[2:(length(excluded_list) + 1)])
reg_data$cf_counts <- stats::predict(temp_reg,cbind(reg_data[,c(1,2)],cheat_excluded))
counter <- counter + 1
}
}
if (draw==TRUE) {
graphics::plot(bunch_hist, freq=TRUE,ylim=c(0,1.1 *
stats::quantile(bunch_hist$counts,
probs=c(0.99))),
main = paste(title),
xlab= paste(varname) ,ylab="Counts (bunch not to scale)")
graphics::lines(x=reg_data$mid, y=reg_data$cf_counts,col="purple",lwd=2)
graphics::abline(v=c(zstar - binw / 2 - exclude_before * binw,
zstar + binw / 2 + exclude_after * binw),
col="green4", lty=2, lwd=2)
graphics::abline(v=c(zstar - binw / 2 - cf_start * binw,
zstar + binw / 2 + cf_end * binw), col="red",
lty=2, lwd=2)
graphics::legend("topright",col=c("red","green","purple"),lty=c(2,2,1),
legend=c("CF calc range","Excluded bins","CF distribution"))
}
return_data <- saved_data[saved_data$mid < zstar - cf_start * binw, ]
return_data <- rbind(return_data, reg_data[,c(1:4)])
return_data <- rbind(return_data,
saved_data[saved_data$mid > zstar + cf_start * binw, ])
if (correct == TRUE) {
est_b <- new_B/(sum(reg_data$cf_counts[!reg_data$excluded == 1] /
(length(excluded_list) * binw)))
est_e <- est_b/(zstar * log( (1 - t1) / (1 - t2) ))
results <- list("e" = est_e,
"Bn" = new_B,
"b" = est_b,
"data" = return_data )
return(results)
} else {
est_b <- naive_B/(sum(reg_data$cf_counts[!reg_data$excluded == 1] /
(length(excluded_list) * binw)))
est_e <- est_b/(zstar * log( (1 - t1)/(1 - t2) ))
results <- list("e" = est_e,
"Bn" = naive_B,
"b" = est_b,
"data" = return_data )
return(results)
}
} |
test_that("joining metrics works", {
simulations_df <- data.frame(
idx=rep(1:10, 100),
idx2=sample(c("a", "b"), replace=T, 1000),
p_value=runif(1000),
est=rnorm(n=1000),
conf.ll= rnorm(n=1000, mean=-20),
conf.ul= rnorm(n=1000, mean=20)
)
expect_silent({
res <- join_metrics(
data=simulations_df,
id_cols=c("idx", "idx2"),
metrics=c("rejection", "coverage", "mse"),
true_value=0,
ll_col="conf.ll",
ul_col="conf.ul",
estimates_col="est",
p_col="p_value",
)
})
expect_equal(nrow(res), 20)
})
test_that("warns when given incorrect metrics", {
simulations_df <- data.frame(
idx=rep(1:10, 100),
idx2=sample(c("a", "b"), replace=T, 1000),
p_value=runif(1000),
est=rnorm(n=1000),
conf.ll= rnorm(n=1000, mean=-20),
conf.ul= rnorm(n=1000, mean=20)
)
expect_warning({
join_metrics(
data=simulations_df,
id_cols=c("idx", "idx2"),
metrics=c("rejection", "coverage", "mse", "bad_metric_name"),
true_value=0,
ll_col="conf.ll",
ul_col="conf.ul",
estimates_col="est",
p_col="p_value",
)
})
}) |
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL |
fglasso <- function(S, model, tp, p, ...){
this.call <- match.call()
if(!is.element(class(model)[1L], c("list", "matrix")))
stop("model must be a list or a matrix")
if(is.list(model)){
check <- unlist(lapply(model, function(x) length(x) != 2))
if(any(check)) stop("wrong model specification")
check <- unlist(lapply(model, function(x) !is.element(x, c("c", "u", "t", "ut", "."))))
if(any(check)) stop("wrong model specification")
model <- matrix(unlist(model), length(model), 2, byrow = TRUE)
}
if(is.matrix(model)){
if(dim(model)[1] > tp)
stop("dim(model)[1] > tp")
if(dim(model)[2] != 2)
stop("dim(model)[2] != 2")
}
if(model[1, 1] == ".")
stop("model[1, 1] is equal to zero")
if(dim(S)[1] != tp * p | dim(S)[2] != tp * p)
stop("dim(S) != dim(mask)")
mask <- fglasso_model2mask(model, tp, p)
out_fglasso <- sglasso(S = S, mask = mask, ...)
out_fglasso$call <- this.call
out_fglasso$model <- model
out_fglasso$p <- p
out_fglasso$tp <- tp
class(out_fglasso) <- c("fglasso", class(out_fglasso))
out_fglasso
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.