code
stringlengths 1
13.8M
|
---|
neon_db <- function (dir = neon_db_dir(),
read_only = TRUE,
memory_limit = getOption("duckdb_memory_limit", NA),
...) {
if (!dir.exists(dir)){
dir.create(dir, FALSE, TRUE)
}
dbname <- file.path(dir, "database")
if (!file.exists(dbname) && read_only) {
db <- DBI::dbConnect(duckdb::duckdb(),
dbdir = dbname, read_only = FALSE)
DBI::dbWriteTable(db, "init", data.frame(NEON="NEON"))
DBI::dbDisconnect(db, shutdown=TRUE)
}
db <- mget("neon_db", envir = neonstore_cache, ifnotfound = NA)[[1]]
if (inherits(db, "DBIConnection")) {
if (DBI::dbIsValid(db)) {
dir_matches <- db@driver@dbdir == dbname
if (read_only & dir_matches) {
return(db)
} else {
dbDisconnect(db, shutdown = TRUE)
}
}
}
db <- DBI::dbConnect(duckdb::duckdb(),
dbdir = dbname,
read_only = read_only,
...)
if(!is.na(memory_limit)){
pragma <- paste0("PRAGMA memory_limit='", memory_limit, "GB'")
DBI::dbExecute(db, pragma)
}
if (read_only) {
assign("neon_db", db, envir = neonstore_cache)
}
db
}
neon_disconnect <- function (db = neon_db()) {
if (inherits(db, "DBIConnection")) {
DBI::dbDisconnect(db, shutdown = TRUE)
}
if (exists("neon_db", envir = neonstore_cache)) {
suppressWarnings(
rm("neon_db", envir = neonstore_cache)
)
}
}
neonstore_cache <- new.env()
neon_delete_db <- function(db_dir = neon_db_dir(), ask = interactive()){
continue <- TRUE
if(ask){
continue <- utils::askYesNo(paste("Delete local DB in", db_dir, "?"))
}
if(continue){
db_files <- list.files(db_dir, "^database.*", full.names = TRUE)
lapply(db_files, unlink, TRUE)
}
if (exists("neon_db", envir = neonstore_cache)) {
suppressWarnings(
rm("neon_db", envir = neonstore_cache)
)
}
return(invisible(continue))
}
|
`sr.loc.test` <-
function(X,Y=NULL,g=NULL,score=c("sign","rank"),nullvalue=NULL,cond=FALSE,cond.n=1000,na.action=na.fail,...)
{
if (all(is.null(Y),is.null(g))) {
DNAME<-deparse(substitute(X))
X<-na.action(X)
X<-as.matrix(X)
g<-as.factor(rep(1,dim(X)[1]))
}
else if(!is.null(Y)) {
X<-as.matrix(X)
Y<-as.matrix(Y)
if(dim(X)[2]!=dim(Y)[2]) stop("X and Y must have the same number of columns")
DNAME<-paste(deparse(substitute(X)),"and",deparse(substitute(Y)))
X<-na.action(X)
Y<-na.action(Y)
g<-factor(c(rep(1,dim(X)[1]),rep(2,dim(Y)[1])))
X<-rbind(X,Y)
}
else if(!is.factor(g))
stop("g must be a factor or NULL")
else {
DNAME<-paste(deparse(substitute(X)),"by",deparse(substitute(g)))
X<-as.matrix(X)
Xandg<-cbind(g,X)
Xandg<-na.action(Xandg)
g<-factor(Xandg[,1])
X<-as.matrix(Xandg[,-1])
rm(Xandg)
}
n<-dim(X)[1]
p<-dim(X)[2]
c<-nlevels(g)
if(!is.null(nullvalue)) {
if(length(nullvalue)!=p)
stop("'nullvalue' must have length equal to the number of columns of 'X'")
}
else nullvalue<-rep(0,p)
X<-sweep(X,2,nullvalue)
NVAL<-paste("c(",paste(nullvalue,collapse=","),")",sep="")
if(c==1) names(NVAL)<-"location"
else if(c==2) names(NVAL)<-"difference between group locations"
else names(NVAL)<-"difference between some group locations"
score=match.arg(score)
switch(score,
"sign"=
{
if (c==1)
{
METHOD<-"One sample location test using spatial signs"
scoremat<-spatial.signs(X,center=F)
}
else
{
METHOD<-"Several samples location test using spatial signs"
scoremat<-spatial.signs(X)
}
},
"rank"=
{
if (c==1)
{
METHOD<-"One sample location test using spatial signed ranks"
if (p>1) V<-signrank.shape(X)
}
else
{
METHOD<-"Several samples location test using spatial ranks"
if (p>1) V<-rank.shape(X)
}
if (p==1) V<-diag(1)
scoremat<-spatial.rank(X%*%solve(mat.sqrt(V)),shape=FALSE)
c2<-mean(norm(scoremat)^2)
})
if (c==1) {
STATISTIC<-switch(score,
"sign"=
{
n*p*sum(apply(scoremat,2,mean)^2)
},
"rank"=
{
sums<-pairsum(X)%*%mat.sqrt(solve(V))
ave<-apply(spatial.signs(rbind(sums,X),center=F,shape=F),2,mean)
rm(sums)
n*p*sum(ave^2)/(4*c2)
})
}
else {
bar<-numeric(0)
sizes<-numeric(0)
for (i in 1:c) {
bar<-rbind(bar,apply(scoremat[g==levels(g)[i],,drop=F],2,mean))
sizes<-c(sizes,sum(g==levels(g)[i]))
}
STATISTIC<-p*sum(sizes*(norm(bar)^2))/switch(score,"sign"=1,"rank"=c2)
}
if (all(cond,score=="sign"))
{
Qd<-numeric(0)
if(c==1) {
for (i in 1:cond.n) {
d<-sample(c(-1,1),n,replace=T)
Qd<-c(Qd,n*p*sum(apply(sweep(scoremat,1,d,"*"),2,mean)^2))
}
}
else {
for (i in 1:cond.n) {
gd<-sample(g)
bar<-numeric(0)
for (j in 1:c)
bar<-rbind(bar,apply(scoremat[gd==levels(gd)[j],,drop=F],2,mean))
Qd<-c(Qd,p*sum(sizes*(norm(bar)^2)))
}
}
PARAMETER<-cond.n
names(PARAMETER)<-"replications"
PVAL<-mean(Qd>=STATISTIC)
}
else
{
PVAL<-1-pchisq(STATISTIC,(df<-p*max(1,c-1)))
PARAMETER<-df
names(PARAMETER)<-"df"
}
ALTERNATIVE<-"two.sided"
names(STATISTIC)<-"Q.2"
res<-c(list(statistic=STATISTIC,parameter=PARAMETER,p.value=PVAL,null.value=NVAL,alternative=ALTERNATIVE,method=METHOD,data.name=DNAME))
class(res)<-"htest"
return(res)
}
|
EEpre = function(A, B, d, seed = NULL, AB_dist = NULL){
n.A = dim(A)[1];
n.B = dim(B)[1];
outa = apply(A, 1, sum);
outb = apply(B, 1, sum);
if(!isSymmetric(A)) stop("Error! A is not symmetric!");
if(!isSymmetric(B)) stop("Error! B is not symmetric!");
if(d %% 1 != 0) stop("Error! d is not an integer!")
if(d <= 0) stop("Error! Nonpositive d!")
if(!is.null(seed)){
if(dim(seed)[1] == 1) stop("Error! Only one pair of seeds!")
}
if(!is.null(AB_dist)){
if(min(AB_dist) < 0) stop("Error! Negative elements in distance matrix!")
if(dim(AB_dist)[1] != n.A | dim(AB_dist)[2] != n.B) stop("Error! Matrices are not conformable!")
}
if (!is.null(seed)){
seedmatch1 = apply(seed, 1, sum);
seedmatch2 = apply(seed, 2, sum);
if(max(seedmatch1, seedmatch2) > 1) stop("Error: no perfect matching for the seed")
else{
W = seeded.match(A, B, seed);
Z = matrix(0, nrow = n.A, ncol = n.B);
for (i in 1: n.A){
tmp = sort(W[i,], decreasing = T)
ind = which(W[i,] >= tmp[d])
Z[i, ind] = 1
}
AB_dist = W;
}
}
else{
if (is.null(AB_dist)){
AB_dist = DPdistance(A, B);
}
tmp = apply(AB_dist, 1, min);
grid1 = c(0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8); grid2 = c(0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5);
seed_list = array(0, dim=c(n.A, n.B, length(grid1)*length(grid2)));
seed_match1 = rep(0, length(grid1)*length(grid2)); seed_match2 = rep(0, length(grid1)*length(grid2));
for (j in 1: length(grid1)){
tau1 = quantile(outa, grid1[j]);
for (i in 1: length(grid2)){
tau2 = quantile(tmp, grid2[i]);
seed = seed.generate(A, B, tau1, tau2);
seedmatch1 = apply(seed, 1, sum);
seedmatch2 = apply(seed, 2, sum);
seed_match1[(j-1)*length(grid2) + i] = max(seedmatch1);
seed_match2[(j-1)*length(grid2) + i] = max(seedmatch2);
seed_list[, , (j-1)*length(grid2) + i] = seed;
}
}
temp1 = seed_match1 + seed_match2;
if (2 %in% temp1 == TRUE){
temp2 = which(temp1 == 2);
perm_num = c();
for (i in 1: length(temp2)){
seed = seed_list[, , temp2[i]];
gseed <- graph.incidence(seed);
perm <- as_edgelist(gseed);
perm_num[i] = dim(perm)[1];
}
seed = seed_list[, , temp2[which.max(perm_num)]];
if (max(perm_num) == 1){
warning("Warning: Only one pair of seeds. Run EE instead.")
Z = matrix(0, nrow = n.A, ncol = n.B);
for (i in 1: n.A){
tmp = sort(AB_dist[i,], decreasing = F)
ind = which(AB_dist[i,] <= tmp[d])
Z[i, ind] = 1
}
}
else{
W = seeded.match(A, B, seed);
Z = matrix(0, nrow = n.A, ncol = n.B);
for (i in 1: n.A){
tmp = sort(W[i,], decreasing = T)
ind = which(W[i,] >= tmp[d])
Z[i, ind] = 1
}
}
}
if (2 %in% temp1 == FALSE){
warning("Warning: No perfect matching for the seed. Run EE instead.")
Z = matrix(0, nrow = n.A, ncol = n.B);
for (i in 1: n.A){
tmp = sort(AB_dist[i,], decreasing = F)
ind = which(AB_dist[i,] <= tmp[d])
Z[i, ind] = 1
}
}
}
return(list(Dist = AB_dist, Z = Z))
}
seed.generate <- function(A, B, tau1, tau2){
n.A = dim(A)[1]
n.B = dim(B)[1]
outa = apply(A, 1, sum);
outb = apply(B, 1, sum);
seed = matrix(0, nrow = n.A, ncol = n.B);
seedA = which(outa >= tau1); seedB = which(outb >= tau1);
for(i in seedA){
temp_a = outa[A[i, ] != 0];
temp = rep(tau2+1, n.B);
temp[seedB] = apply(B[seedB, ], 1, function(x) wasserstein1d(temp_a, outb[x!=0]));
seed[i,] = 1*(temp <= tau2);
}
return(seed)
}
seeded.match <- function(A, B, seed, n, tau3 = NULL){
colnames(seed) = 1:dim(B)[1]; rownames(seed) = 1:dim(A)[1]
gseed <- graph.incidence(seed)
perm <- as_edgelist(gseed)
rownames(A) = 1:dim(A)[1]; rownames(B) = 1:dim(B)[1];
Acomp = A[-as.integer(perm[,1]), as.integer(perm[,1])];
Bcomp = t(B[-as.integer(perm[,2]), as.integer(perm[,2])])
H1 = Acomp%*%Bcomp;
H = H1;
H[H != 0] = 0;
if (is.null(tau3)){
temp = as.vector(H1);
tau3 = quantile(temp, 1-1/max(dim(A)[1], dim(B)[1]));
}
H[H1 >= tau3] <- 1;
gH <- graph.incidence(H, weighted = TRUE);
match1 <- max_bipartite_match(gH);
matcha <- match1$matching[1:dim(Acomp)[1]]
matchb <- match1$matching[-c(1:dim(Acomp)[1])];
matcha[is.na(matcha)] <- names(matchb)[is.na(matchb)];
permformat = as.vector(perm[,2]); names(permformat) = perm[,1];
perm1 = c(matcha, permformat);
A1 = A[,as.integer(names(perm1))]; B1 = B[as.integer(perm1),];
w = A1%*%B1;
return(w)
}
|
check.1 <- function(data, id.var, time.var, x.vars, y.vars, w.vars, p.vars) {
if (!(is.data.frame(data)))
stop("data must be a dataframe")
names.var <- names(data)
if (missing(id.var)) {
stop("Missing id variable (id.var)", call. = FALSE)
} else {
if (length(id.var) > 1)
stop("Too many id variables (id.var). Only one can be defined", call. = FALSE)
if (is.numeric(id.var)) {
id.var.1 <- names.var[id.var]
} else {
id.var.1 <- id.var
}
var_logical <- id.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in id.var: ", paste(id.var), call. = FALSE)
}
if (missing(time.var)) {
stop("Missing time variable (time.var)", call. = FALSE)
} else {
if (length(time.var) > 1)
stop("Too many time variables (time.var). Only one can be defined", call. = FALSE)
if (is.numeric(time.var)) {
time.var.1 <- names.var[time.var]
} else {
time.var.1 <- time.var
}
var_logical <- time.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in time.var:", paste(time.var), call. = FALSE)
}
if (missing(x.vars)) {
stop("Missing x variables (x.vars)", call. = FALSE)
} else {
if (is.numeric(x.vars)) {
x.vars.1 <- names.var[x.vars]
} else {
x.vars.1 <- x.vars
}
var_logical <- x.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in x.vars:", paste(x.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (missing(y.vars)) {
stop("Missing y variables (y.vars)", call. = FALSE)
} else {
if (is.numeric(y.vars)) {
y.vars.1 <- names.var[y.vars]
} else {
y.vars.1 <- y.vars
}
var_logical <- y.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in y.vars:", paste(y.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (is.null(w.vars) & is.null(p.vars)) {
list(id.var = id.var.1, time.var = time.var.1, x.vars = x.vars.1, y.vars = y.vars.1)
} else {
if (!(is.null(w.vars)) & !(is.null(p.vars))) {
if (length(w.vars) != length(x.vars))
stop("x.vars and w.vars must be of the same length", call. = FALSE)
if (length(p.vars) != length(y.vars))
stop("y.vars and p.vars must be of the same length", call. = FALSE)
if (is.numeric(w.vars)) {
w.vars.1 <- names.var[w.vars]
} else {
w.vars.1 <- w.vars
}
var_logical <- w.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in w.vars:", paste(w.vars[var_logical == F],
collapse = ","), call. = FALSE)
if (is.numeric(p.vars)) {
p.vars.1 <- names.var[p.vars]
} else {
p.vars.1 <- p.vars
}
var_logical <- p.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in p.vars:", paste(p.vars[var_logical == F],
collapse = ","), call. = FALSE)
list(id.var = id.var.1, time.var = time.var.1, x.vars = x.vars.1, y.vars = y.vars.1,
w.vars = w.vars.1, p.vars = p.vars.1)
} else {
if (!(is.null(w.vars)) & is.null(p.vars)) {
stop("Output prices p.vars must also be supplied", call. = FALSE)
} else {
stop("Input prices w.vars must also be supplied", call. = FALSE)
}
}
}
}
check.2 <- function(data, id.var, time.var, x.vars, y.vars, w.vars, p.vars) {
if (!(is.data.frame(data)))
stop("data must be a dataframe")
names.var <- names(data)
if (missing(id.var)) {
stop("Missing id variable (id.var)", call. = FALSE)
} else {
if (length(id.var) > 1)
stop("Too many id variables (id.var). Only one can be defined", call. = FALSE)
if (is.numeric(id.var)) {
id.var.1 <- names.var[id.var]
} else {
id.var.1 <- id.var
}
var_logical <- id.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in id.var: ", paste(id.var), call. = FALSE)
}
if (missing(time.var)) {
stop("Missing time variable (time.var)", call. = FALSE)
} else {
if (length(time.var) > 1)
stop("Too many time variables (time.var). Only one can be defined", call. = FALSE)
if (is.numeric(time.var)) {
time.var.1 <- names.var[time.var]
} else {
time.var.1 <- time.var
}
var_logical <- time.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in time.var:", paste(time.var), call. = FALSE)
}
if (missing(x.vars)) {
stop("Missing x variables (x.vars)", call. = FALSE)
} else {
if (is.numeric(x.vars)) {
x.vars.1 <- names.var[x.vars]
} else {
x.vars.1 <- x.vars
}
var_logical <- x.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in x.vars:", paste(x.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (missing(y.vars)) {
stop("Missing y variables (y.vars)", call. = FALSE)
} else {
if (is.numeric(y.vars)) {
y.vars.1 <- names.var[y.vars]
} else {
y.vars.1 <- y.vars
}
var_logical <- y.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in y.vars:", paste(y.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (missing(w.vars)) {
stop("Missing w variables (w.vars)", call. = FALSE)
} else {
if (is.numeric(w.vars)) {
w.vars.1 <- names.var[w.vars]
} else {
w.vars.1 <- w.vars
}
var_logical <- w.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in w.vars:", paste(w.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (missing(p.vars)) {
stop("Missing p variables (p.vars)", call. = FALSE)
} else {
if (is.numeric(p.vars)) {
p.vars.1 <- names.var[p.vars]
} else {
p.vars.1 <- p.vars
}
var_logical <- p.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in p.vars:", paste(p.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (length(w.vars) != length(x.vars))
stop("x.vars and w.vars must be of the same length", call. = FALSE)
if (length(p.vars) != length(y.vars))
stop("y.vars and p.vars must be of the same length", call. = FALSE)
list(id.var = id.var.1, time.var = time.var.1, x.vars = x.vars.1, y.vars = y.vars.1, w.vars = w.vars.1,
p.vars = p.vars.1)
}
check.3 <- function(data, id.var, time.var, x.vars, y.vars) {
if (!(is.data.frame(data)))
stop("data must be a dataframe")
names.var <- names(data)
if (missing(id.var)) {
stop("Missing id variable (id.var)", call. = FALSE)
} else {
if (length(id.var) > 1)
stop("Too many id variables (id.var). Only one can be defined", call. = FALSE)
if (is.numeric(id.var)) {
id.var.1 <- names.var[id.var]
} else {
id.var.1 <- id.var
}
var_logical <- id.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in id.var: ", paste(id.var), call. = FALSE)
}
if (missing(time.var)) {
stop("Missing time variable (time.var)", call. = FALSE)
} else {
if (length(time.var) > 1)
stop("Too many time variables (time.var). Only one can be defined", call. = FALSE)
if (is.numeric(time.var)) {
time.var.1 <- names.var[time.var]
} else {
time.var.1 <- time.var
}
var_logical <- time.var.1 %in% names.var
if (!var_logical)
stop("Unrecognizable variable in time.var:", paste(time.var), call. = FALSE)
}
if (missing(x.vars)) {
stop("Missing x variables (x.vars)", call. = FALSE)
} else {
if (is.numeric(x.vars)) {
x.vars.1 <- names.var[x.vars]
} else {
x.vars.1 <- x.vars
}
var_logical <- x.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in x.vars:", paste(x.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
if (missing(y.vars)) {
stop("Missing y variables (y.vars)", call. = FALSE)
} else {
if (is.numeric(y.vars)) {
y.vars.1 <- names.var[y.vars]
} else {
y.vars.1 <- y.vars
}
var_logical <- y.vars.1 %in% names.var
if (!(all(var_logical)))
stop("Unrecognizable variables in y.vars:", paste(y.vars[var_logical == F], collapse = ","),
call. = FALSE)
}
list(id.var = id.var.1, time.var = time.var.1, x.vars = x.vars.1, y.vars = y.vars.1)
}
DO.teseme <- function(XOBS, YOBS, XREF, YREF, PRICESO, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_x + n_y, 1 + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(0, XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(-YOBS[j], YREF[j, ]))
}
set.objfn(built.lp, c(1, rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.bounds(built.lp, lower = -Inf, upper = Inf, columns = 1)
set.rhs (built.lp, c(XOBS, rep(0, n_y)))
lp.control(built.lp, sense = "max")
solve(built.lp)
ote_crs <- 1/get.objective(built.lp)
if (rts != "crs") {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(0, rep(1, n_t)), type = ctyp, rhs = 1)
}
solve(built.lp)
OTE <- 1/get.objective(built.lp)
OSE <- ote_crs/OTE
built.lp <- make.lp(n_x + n_y, n_y + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(rep(0, n_y), XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(-diag(1, ncol = n_y, nrow = n_y)[j, ], YREF[j, ]))
}
set.objfn(built.lp, c(PRICESO/sum(YOBS * PRICESO), rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.rhs (built.lp, c(XOBS, rep(0, n_y)))
if (rts != "crs") {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(rep(0, n_y), rep(1, n_t)), type = ctyp, rhs = 1)
}
lp.control(built.lp, sense = "max")
solve(built.lp)
OME <- 1/(get.objective(built.lp) * OTE)
c(OTE = OTE, OSE = OSE, OME = OME)
}
DO.sh <- function(XOBS, YOBS, XREF, YREF, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_x + n_y, 1 + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(0, XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(-YOBS[j], YREF[j, ]))
}
set.objfn(built.lp, c(1, rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.bounds(built.lp, lower = -Inf, upper = Inf, columns = 1)
set.rhs (built.lp, c(XOBS, rep(0, n_y)))
lp.control(built.lp, sense = "max")
if (rts == "crs") {
solve(built.lp)
DO <- 1/get.objective(built.lp)
} else {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(0, rep(1, n_t)), type = ctyp, rhs = 1)
solve(built.lp)
DO <- 1/get.objective(built.lp)
}
DO
}
DI.teseme <- function(XOBS, YOBS, XREF, PRICESI, YREF, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_x + n_y, 1 + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(-XOBS[i], XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(0, YREF[j, ]))
}
set.objfn(built.lp, c(1, rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.rhs (built.lp, c(rep(0, n_x), YOBS))
set.bounds(built.lp, lower = -Inf, upper = Inf, columns = 1)
lp.control(built.lp, sense = "min")
solve(built.lp)
ite_crs <- get.objective(built.lp)
if (rts != "crs") {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(0, rep(1, n_t)), type = ctyp, rhs = 1)
}
solve(built.lp)
ITE <- get.objective(built.lp)
ISE <- ite_crs/ITE
built.lp <- make.lp(n_x + n_y , n_x + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(-diag(1, nrow = n_x, ncol = n_x)[i, ], XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(rep(0, n_x), YREF[j, ]))
}
set.objfn(built.lp, c(PRICESI/sum(XOBS * PRICESI), rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.rhs (built.lp, c(rep(0, n_x), YOBS))
if (rts != "crs") {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(rep(0, n_x), rep(1, n_t)), type = ctyp, rhs = 1)
}
lp.control(built.lp, sense = "min")
solve(built.lp)
IME <- get.objective(built.lp)/ITE
c(ITE = ITE, ISE = ISE, IME = IME)
}
DI.sh <- function(XOBS, YOBS, XREF, YREF, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_x + n_y, 1 + n_t)
for (i in 1:n_x) {
set.row(built.lp, i, c(-XOBS[i], XREF[i, ]))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(0, YREF[j, ]))
}
set.objfn(built.lp, c(1, rep(0, n_t)))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y)))
set.rhs (built.lp, c(rep(0, n_x), YOBS))
set.bounds(built.lp, lower = -Inf, upper = Inf, columns = 1)
lp.control(built.lp, sense = "min")
if (rts == "crs") {
solve(built.lp)
DI <- 1/get.objective(built.lp)
} else {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(0, rep(1, n_t)), type = ctyp, rhs = 1)
solve(built.lp)
DI <- 1/get.objective(built.lp)
}
DI
}
D.tfp <- function(XOBS, YOBS, XREF, YREF, PRICESO, PRICESI, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_x + n_y + 1, n_y + n_x + n_t + 1)
for (i in 1:n_x) {
set.row(built.lp, i, c(rep(0, n_y), diag(-1, nrow = n_x, ncol = n_x)[i, ], XREF[i, ], 0))
}
for (j in 1:n_y) {
set.row(built.lp, n_x + j, c(diag(-1, ncol = n_y, nrow = n_y)[j, ], rep(0, n_x), YREF[j, ], 0))
}
set.row(built.lp, n_x + n_y + 1, c(rep(0, n_y), PRICESI, rep(0, n_t + 1)))
set.objfn(built.lp, c(PRICESO, rep(0, n_x), rep(0, n_t), 0))
set.constr.type(built.lp, c(rep("<=", n_x), rep(">=", n_y), "="))
set.rhs (built.lp, c(rep(0, n_x), rep(0, n_y), 1))
if (rts != "crs") {
ctyp <- if (rts == "vrs") {
"="
} else {
if (rts == "nirs") {
"<="
} else {
if (rts == "ndrs") {
">="
}
}
}
add.constraint(built.lp, c(rep(0, n_x + n_y), rep(1, n_t), -1), type = ctyp, rhs = 0)
}
lp.control(built.lp, sense = "max")
solve(built.lp)
return(get.objective(built.lp))
}
DO.shdu <- function(XOBS, YOBS, XREF, YREF, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_t + 1, n_y + n_x)
for (i in 1:n_y) {
set.column(built.lp, i, c(-YREF[i, ], YOBS[i]))
}
for (j in 1:n_x) {
set.column(built.lp, n_y + j, c(XREF[j, ], 0))
}
if (rts %in% c("vrs", "nirs")) {
add.column(built.lp, c(rep(1, n_t), 0))
} else {
if (rts == "ndrs") {
add.column(built.lp, c(rep(-1, n_t), 0))
}
}
obj <- if (rts == "crs") {
c(rep(0, n_y), XOBS)
} else {
if (rts %in% c("vrs", "nirs")) {
c(rep(0, n_y), XOBS, 1)
} else {
if (rts == "ndrs") {
c(rep(0, n_y), XOBS, -1)
}
}
}
set.objfn(built.lp, obj)
set.constr.type(built.lp, c(rep(">=", n_t), "="))
set.rhs (built.lp, c(rep(0, n_t), 1))
if (rts == "vrs") set.bounds(built.lp, lower = -Inf, upper = Inf, columns = n_x + n_y + 1)
lp.control(built.lp, sense = "min")
solve(built.lp)
prices_o <- get.variables(built.lp)[1:n_y]/(sum(get.variables(built.lp)[(1 + n_y):(n_y + n_x)] * XOBS) +
if (rts == "crs") {
0
} else {
if (rts %in% c("vrs", "nirs")) {
get.variables(built.lp)[n_y + n_x + 1]
} else {
if (rts == "ndrs") {
-get.variables(built.lp)[n_y + n_x + 1]
}
}
})
names(prices_o) <- paste("U", 1:n_y, sep = "")
prices_o
}
DI.shdu <- function(XOBS, YOBS, XREF, YREF, rts) {
n_x <- dim(XREF)[1]
n_y <- dim(YREF)[1]
n_t <- dim(XREF)[2]
built.lp <- make.lp(n_t + 1, n_y + n_x)
for (i in 1:n_y) {
set.column(built.lp, i, c(YREF[i, ], 0))
}
for (j in 1:n_x) {
set.column(built.lp, n_y + j, c(-XREF[j, ], XOBS[j]))
}
if (rts %in% c("vrs", "ndrs")) {
add.column(built.lp, c(rep(1, n_t), 0))
} else {
if (rts == "nirs") {
add.column(built.lp, c(rep(-1, n_t), 0))
}
}
obj <- if (rts == "crs") {
c(YOBS, rep(0, n_x))
} else {
if (rts %in% c("vrs", "ndrs")) {
c(YOBS, rep(0, n_x), 1)
} else {
if (rts == "nirs") {
c(YOBS, rep(0, n_x), -1)
}
}
}
set.objfn(built.lp, obj)
set.constr.type(built.lp, c(rep("<=", n_t), "="))
set.rhs (built.lp, c(rep(0, n_t), 1))
if (rts == "vrs") set.bounds(built.lp, lower = -Inf, upper = Inf, columns = n_x + n_y + 1)
lp.control(built.lp, sense = "max")
solve(built.lp)
prices_i <- get.variables(built.lp)[(n_y + 1):(n_y + n_x)]/
(sum(get.variables(built.lp)[1:n_y] * YOBS) +
if (rts == "crs") {
0
} else {
if (rts %in% c("vrs", "ndrs")) {
get.variables(built.lp)[n_x + n_y + 1]
} else {
if (rts == "nirs") {
-get.variables(built.lp)[n_x + n_y + 1]
}
}
})
names(prices_i) <- paste("V", 1:n_x, sep = "")
prices_i
}
fdiv <- function(x) x[, 1]/x[, 2]
balanced <- function(data, id.var, time.var) {
x <- data[, id.var]
y <- data[, time.var]
if (length(x) != length(y)) stop(paste0("The length of the two vectors (i.e. ", id.var, " and ", time.var, ") differs\n"))
x <- data[, id.var][drop = TRUE]
y <- data[, time.var][drop = TRUE]
z <- table(x, y)
if (any(as.vector(z) == 0)) {
balanced <- FALSE
} else {
balanced <- TRUE
}
return(balanced)
}
Levels <- function(object, ...) {
if (!is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Malmquist", "Paasche", "HicksMoorsteen"))) {
stop("Function 'Levels' can not be applied to an object of class \"", class(object), "\"")
}
if (is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Malmquist", "Paasche")) | (is(object, "HicksMoorsteen") & (length(object) == 2))) {
return(object$Levels)
}
if (is(object, "HicksMoorsteen") & (length(object) > 2)) {
return(lapply(object, function(x) x$Levels))
}
}
Changes <- function(object, ...) {
if (!is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Malmquist", "Paasche", "HicksMoorsteen"))) {
stop("Function 'Changes' can not be applied to an object of class \"", class(object), "\"")
}
if (is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Malmquist", "Paasche")) | (is(object, "HicksMoorsteen") & (length(object) == 2))) {
return(object$Changes)
}
if (is(object, "HicksMoorsteen") & (length(object) > 2)) {
return(lapply(object, function(x) x$Changes))
}
}
Shadowp <- function(object, ...) {
if (is(object, c("Malmquist"))) {
stop("Function 'Shadowp' can not be applied to an object of class \"", class(object)[2], "\"")
}
if (!is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Paasche", "HicksMoorsteen"))) {
stop("Function 'Shadowp' can not be applied to an object of class \"", class(object), "\"")
}
if (is(object, c("FarePrimont", "Fisher", "Laspeyres", "Lowe", "Paasche")) & is.null(object$Shadowp)) {
stop("No shadow prices are returned in your \"", class(object)[2], "\"", " object.
Specifying 'shadow = TRUE' should be considered in the function generating the \"", class(object)[2], "\"", " object.")
}
if (is(object, "HicksMoorsteen")) {
if (length(object) == 2) {
stop("No shadow prices are returned in your \"", class(object)[2], "\"", " object.
Specifying 'components = TRUE' should be considered in the function generating the \"", class(object)[2], "\"", " object.")
} else {
List <- lapply(object, function(x) x$Shadowp)
return(List[!sapply(List,is.null)])
}
}
return(object$Shadowp)
}
|
TOL <- 1e-4
x_bool <- Variable(boolean=TRUE)
y_int <- Variable(integer=TRUE)
A_bool <- Variable(3, 2, boolean=TRUE)
B_int <- Variable(2, 3, integer=TRUE)
MIP_SOLVERS <- c("ECOS_BB", "GUROBI", "MOSEK")
solvers <- intersect(MIP_SOLVERS, installed_solvers())
bool_prob <- function(solver) {
test_that("Test Boolean problems", {
obj <- Minimize((x_bool - 0.2)^2)
p <- Problem(obj, list())
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0.04, tolerance = TOL)
expect_equal(result$getValue(x_bool), 0, tolerance = TOL)
t <- Variable()
obj <- Minimize(t)
p <- Problem(obj, list(x_bool^2 <= t))
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0, tolerance = TOL)
expect_equal(result$getValue(x_bool), 0, tolerance = 1e-4)
C <- cbind(c(0,1,0), c(1,1,1))
obj <- Minimize(sum_squares(A_bool - C))
p <- Problem(obj, list())
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0, tolerance = TOL)
expect_equal(result$getValue(A_bool), C, tolerance = 1e-4)
t <- Variable()
obj <- Minimize(t)
p <- Problem(obj, list(sum_squares(A_bool - C) <= t))
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0, tolerance = TOL)
expect_equal(result$getValue(A_bool), C, tolerance = 1e-4)
})
}
int_prob <- function(solver) {
test_that("Test Integer problems", {
obj <- Minimize((y_int - 0.2)^2)
p <- Problem(obj, list())
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0.04, tolerance = TOL)
expect_equal(result$getValue(y_int), 0, tolerance = TOL)
obj <- Minimize(0)
p <- Problem(obj, list(y_int == 0.5))
result <- solve(p, solver = solver, verbose = TRUE)
expect_true(result$status %in% CVXR:::INF_OR_UNB)
})
}
int_socp <- function(solver) {
test_that("Test SOCP problems", {
t <- Variable()
obj <- Minimize(t)
p <- Problem(obj, list(square(y_int - 0.2) <= t))
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0.04, tolerance = TOL)
expect_equal(result$getValue(y_int), 0, tolerance = TOL)
})
}
bool_socp <- function(solver) {
test_that("Test Bool SOCP problems", {
t <- Variable()
obj <- Minimize(t)
p <- Problem(obj, list(square(x_bool - 0.2) <= t))
result <- solve(p, solver = solver, verbose = TRUE)
expect_equal(result$value, 0.04, tolerance = TOL)
expect_equal(result$getValue(x_bool), 0, tolerance = TOL)
})
}
test_all_solvers <- function() {
for (solver in solvers) {
bool_prob(solver)
int_prob(solver)
bool_socp(solver)
int_socp(solver)
}
}
test_all_solvers()
|
context("testing of export to image")
test_that("Function fails for wrong inputs", {
skip_on_cran()
skip_on_os('windows')
expect_error(
mtcars %>%
tableHTML() %>%
add_theme('scientific') %>%
tableHTML_to_image(type = 'abc'),
'should be one of'
)
expect_error(
mtcars %>%
tableHTML() %>%
tableHTML_to_image(add = 2),
"add must be TRUE or FALSE"
)
expect_true({
myfile <- tempfile(fileext = '.jpeg')
mtcars %>%
tableHTML() %>%
tableHTML_to_image(type = 'jpeg', file = myfile)
out <- file.size(myfile) > 1
file.remove(myfile)
out
})
expect_true({
myfile <- tempfile(fileext = '.png')
mtcars %>%
tableHTML() %>%
tableHTML_to_image(type = 'png', file = myfile)
out <- file.size(myfile) > 1
file.remove(myfile)
out
})
expect_true({
myfile <- tempfile(fileext = '.png')
mtcars %>%
tableHTML() %>%
add_theme('rshiny-blue') %>%
tableHTML_to_image(type = 'png', file = myfile)
out <- file.size(myfile) > 1
file.remove(myfile)
out
})
expect_true({
par_1 <- par()
mtcars %>%
tableHTML() %>%
tableHTML_to_image(add = TRUE)
par_2 <- par()
identical(par_1, par_2)
})
expect_false({
plot(1:5)
par_1 <- par()
mtcars %>%
tableHTML() %>%
tableHTML_to_image(add = FALSE)
par_2 <- par()
identical(par_1, par_2)
})
})
|
bnc_aode <- function(models, class_var, features) {
stopifnot(length(models) > 0, identical(names(models), unname(features)))
stopifnot(all(vapply(models, is_ode, FUN.VALUE = logical(1))))
bnc <- bnc_base(class = class_var, features = features)
bnc$.models <- models
class(bnc) <- c('bnc_aode', class(bnc))
bnc
}
bnc_aode_bns <- function(x, fit_models) {
stopifnot(inherits(x, 'bnc_aode'))
x$.models <- fit_models
class(x) <- c('bnc_aode_bns', class(x), 'bnc_fit')
x
}
is_aode <- function(x) {
if (!inherits(x, c('bnc_aode'))) return (FALSE)
if (length(x$.models) < 2) return (FALSE)
all(sapply(x$.models, is_ode))
}
nmodels <- function(x) {
stopifnot(inherits(x, 'bnc_aode'))
length(x$.models)
}
models <- function(x) {
stopifnot(inherits(x, 'bnc_aode'))
x$.models
}
|
tsea.expression.decode <-
function(query_mat_normalized_score, score, ratio = 0.05, p.adjust.method = "BH"){
query.tsea_t.mat = matrix(1, nrow = ncol(score), ncol = ncol(query_mat_normalized_score));
rownames(query.tsea_t.mat) = colnames(score);
colnames(query.tsea_t.mat) = colnames(query_mat_normalized_score);
for(k.tissue in 1:ncol(score)){
which(as.numeric(as.vector(score[,k.tissue])) > quantile(as.numeric(as.vector(score[,k.tissue])), probs = (1 - ratio), na.rm = TRUE )) -> ii
genes.for.test = rownames(score)[ii]
match(genes.for.test,rownames(query_mat_normalized_score)) -> idx
idx = idx[!is.na(idx)]
for(k.query in 1:ncol(query_mat_normalized_score)){
p1 = t.test(query_mat_normalized_score[idx, k.query], query_mat_normalized_score[-idx, k.query ], alternative= "greater")$p.value
query.tsea_t.mat[k.tissue, k.query] = p1
}
query.tsea_t.mat[k.tissue,] = p.adjust(query.tsea_t.mat[k.tissue,], p.adjust.method)
cat(".", sep="")
}
return(query.tsea_t.mat)
}
|
cond_N <- function(j, Sigma, Z , Z_new, diag_element, lower_upper)
{
p <- ncol(Sigma)
tmp <- matrix(Sigma[j, -j], 1, p-1)
tmp1 <- solve(Sigma[-j, -j])
mu <- tmp %*% tmp1 %*% t(Z[, -j])
mu <- as.vector(mu)
sigma <- Sigma[j, j] - tmp %*% tmp1 %*% t(tmp)
sigma <- sqrt(sigma)
obj <- element_S( lower= lower_upper$lower[ ,j], upper= lower_upper$upper[ ,j], mu=mu, sigma=sigma)
Z_new <- obj$EX
diag_element <- mean(obj$EXX)
rm(tmp, tmp1, mu, sigma, obj )
gc()
return(list(Z_new=Z_new, diag_element=diag_element))
}
|
bprobgHsContUnivBIN <- function(params, respvec, VC, ps, AT = FALSE){
p1 <- p2 <- pdf1 <- pdf2 <- c.copula.be2 <- c.copula.be1 <- c.copula2.be1be2 <- NA
weights <- VC$weights
l.lnun <- NULL
eta2 <- VC$X1%*%params
pd <- probm(eta2, VC$margins[1], only.pr = FALSE, tau = VC$gev.par, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)
y <- respvec$y1
tauetaIND <- pd$tauetaIND == FALSE
pr <- pd$pr[tauetaIND]
d.n <- pd$d.n[tauetaIND]
der2p.dereta <- pd$der2p.dereta[tauetaIND]
X1 <- VC$X1[tauetaIND,]
y <- y[tauetaIND]
weights <- weights[tauetaIND]
l.par <- weights*( y*log(pr) + (1-y)*log(1-pr) )
res <- -sum(l.par)
dl.dbe <- weights*( ( y/pr - (1-y)/(1-pr) )*d.n )
d2l.be.be <- weights*( ( y/pr - (1-y)/(1-pr) )*der2p.dereta + d.n^2*( -y/pr^2 - (1-y)/(1-pr)^2 ) )
G <- -c( colSums( c(dl.dbe)*X1 ) )
H <- -crossprod(X1*c(d2l.be.be),X1)
if(VC$extra.regI == "pC") H <- regH(H, type = 1)
S.h <- ps$S.h
if( length(S.h) != 1 ){
S.h1 <- 0.5*crossprod(params,S.h)%*%params
S.h2 <- S.h%*%params
} else S.h <- S.h1 <- S.h2 <- 0
S.res <- res
res <- S.res + S.h1
G <- G + S.h2
H <- H + S.h
if(VC$extra.regI == "sED") H <- regH(H, type = 2)
list(value=res, gradient=G, hessian=H, S.h=S.h, S.h1=S.h1, S.h2=S.h2, l=S.res, l.lnun = l.lnun,
l.par=l.par, ps = ps, sigma2.st = NULL,
etas1 = NULL, eta1 = eta2,
BivD=VC$BivD, eta2 = eta2, sigma2 = NULL, nu = NULL, tauetaIND = tauetaIND,
p1 = pr, p2 = d.n, pdf1 = pdf1, pdf2 = pdf2,
c.copula.be2 = c.copula.be2,
c.copula.be1 = c.copula.be1,
c.copula2.be1be2 = c.copula2.be1be2)
}
|
Err_exp <-function(X){
J <- colnames(X)
n <- nrow(X)
K <- ncol(X)
p <- apply(X,2,sum) / n
EO<-array(rep(0,K*K*K),dim=c(K,K,K),dimnames=list(J,J,J))
for (i in 1 : K) for (j in 1 : K) for(k in 1 : K) {
EO[i,j,k]<- p[i]*(1- p[j])*p[k]*n
}
dimnames(EO) <- list(J,J,J)
return(EO)
}
|
"cantidades"
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(Select)
library(lattice)
library(FD)
Spp <- 5
trait <- as.matrix(data.frame(trait = c(1:Spp)))
rownames(trait) <- c(letters[1:nrow(trait)])
result1 <- selectSpecies(t2c = trait, constraints = c(trait=3.5), t2d = trait, obj = "H")
plotProbs(result1, trait, xlab = "Species")
round(FD::maxent(constr = c(3.5), states = trait)$prob, 5)
round(t(result1$prob), 5)
result2 <- selectSpecies(t2c = trait, constraints = c(trait=3.5), t2d = trait, obj = "Q")
plotProbs(result2, trait, xlab = "Species")
result3 <- selectSpecies(t2c = trait, constraints = c(trait=3.5), t2d = trait, obj="QH")
plotProbs(result3, trait, xlab = "Species")
result4 <- selectSpecies(t2d = trait, obj = "QH")
plotProbs(result4, trait, xlab = "Species")
trait.matrix <- as.matrix(cbind(traitX = c(rep(1,4), rep(2,4), rep(3,4), rep(4,4)), traitY = c(rep(c(1,2,3,4),4))))
rownames(trait.matrix) <- c(letters[1:16])
traitX <- matrix(c(rep(1,4), rep(2,4), rep(3,4), rep(4,4)))
traitY <- matrix(c(rep(c(1,2,3,4),4)))
rownames(traitX) <- c(letters[1:16]); colnames(traitX) <- c("traitX")
rownames(traitY) <- c(letters[1:16]); colnames(traitY) <- c("traitY")
result5 <- selectSpecies(t2c = traitX, constraints = c(traitX=3.5), t2d = traitY, obj = "Q", capd = FALSE)
trait.matrix <- cbind(traitX, traitY)
plotProbs(result5, trait.matrix, cex.lab = 0.7)
result6 <- selectSpecies(t2c = traitX, constraints = c(traitX=3.5), t2d = traitY, obj = "QH", capd = TRUE)
plotProbs(result6, trait.matrix, cex.lab = 0.7)
serpentine <- read.csv("traits.serpentine.california.csv", header = TRUE, row.names = 1)
wue <- data.frame(wue = scale(log(serpentine$wue)))
rootdepth <- data.frame(rootdepth = scale(log(serpentine$rootdepth)))
rownames(wue) <- rownames(serpentine)
rownames(rootdepth) <- rownames(serpentine)
wue.constraint <- c(quantile(wue$wue, 0.67))
names(wue.constraint) <- c("wue")
result7 <- selectSpecies(t2c = as.matrix(wue), constraints = c(wue.constraint), t2d = as.matrix(rootdepth), capd = TRUE, obj = "QH")
plotProbs(result7, traits = cbind(wue,rootdepth), xlab = "Water use efficiency", ylab = "Rooting depth", colors = c("darkolivegreen4", "gold2"), cex.lab = 0.7)
|
write.GisticSummary = function(gistic, basename = NULL){
if(is.null(basename)){
stop('Please provide a basename for output files.')
}
write.table(x = gistic@data, file = paste(basename,'_gisticData.txt', sep=''), sep='\t', quote = FALSE, row.names = FALSE)
write.table(x = [email protected], file = paste(basename,'_gisticCNVSummary.txt', sep=''), sep='\t', quote = FALSE, row.names = FALSE)
write.table(x = [email protected], file = paste(basename,'_gisticCytobandSummary.txt', sep=''), sep='\t', quote = FALSE, row.names = FALSE)
write.table(x = [email protected], file = paste(basename,'_gisticGeneSummary.txt', sep=''), sep='\t', quote = FALSE, row.names = FALSE)
}
|
EffectiveNumberSamplesMLE=function(FstVect, Fstbar, NumberOfSamples, SmallestFstInTrimmedList, LargestFstInTrimmedList){
sortedFst=FstVect[order(FstVect)]
LowTrimPoint=max(Fstbar/100,SmallestFstInTrimmedList)
trimmedFstVect =FstVect[which((FstVect>=LowTrimPoint)&(FstVect<=LargestFstInTrimmedList))]
trimmedFstArray=as.array(trimmedFstVect)
localNLLAllData=function(dfInferred){
localNLLOneLocus=function(Fst){
negLLdfFstTrim(Fst,dfInferred,Fstbar,LowTrimPoint,LargestFstInTrimmedList)
}
sum(localNLLOneLocus(trimmedFstVect))
}
stats::optim(NumberOfSamples, localNLLAllData, lower=2, method="L-BFGS-B")$par
}
IncompleteGammaFunction=function(a, z) {
stats::pgamma(z,a,lower.tail=FALSE)*gamma(a)
}
negLLdfFstTrim=function(Fst, dfInferred, Fstbar, LowTrimPoint, HighTrimPoint){
df=dfInferred
1/(2*Fstbar)*(df * Fst +df * Fstbar * log(2) - df * Fstbar *log(df)-(df-2)*Fstbar * log(Fst)+df * Fstbar * log(Fstbar) + 2*Fstbar * log(-IncompleteGammaFunction(df/2,df*HighTrimPoint/(2*Fstbar))+IncompleteGammaFunction(df/2,df*LowTrimPoint/(2*Fstbar))))
}
|
get_edgelist <- function(dat, network) {
if (get_control(dat, "tergmLite")) {
el <- dat[["el"]][[network]]
} else {
at <- get_current_timestep(dat)
if (!is.null(dat[["temp"]][["nw_list"]])) {
if (!get_control(dat, "resimulate.network")) {
el <- network::as.edgelist(dat[["temp"]][["nw_list"]][[at]])
} else {
el <- network::as.edgelist(dat[["nw"]][[network]])
}
} else {
el <- networkDynamic::get.dyads.active(dat[["nw"]][[network]], at = at)
}
}
return(el)
}
get_cumulative_edgelist <- function(dat, network) {
if (length(dat[["el.cuml"]]) < network) {
el_cuml <- NULL
} else {
el_cuml <- dat[["el.cuml"]][[network]]
}
if (is.null(el_cuml)) {
el_cuml <- tibble::tibble(
head = numeric(0),
tail = numeric(0),
start = numeric(0),
stop = numeric(0)
)
}
return(el_cuml)
}
update_cumulative_edgelist <- function(dat, network, truncate = 0) {
el <- get_edgelist(dat, network)
el_cuml <- get_cumulative_edgelist(dat, network)
el <- tibble::tibble(
head = get_unique_ids(dat, el[, 1]),
tail = get_unique_ids(dat, el[, 2]),
current = TRUE
)
el_cuml <- dplyr::full_join(el_cuml, el, by = c("head", "tail"))
at <- get_current_timestep(dat)
new_edges <- is.na(el_cuml[["start"]])
if (any(new_edges)) {
el_cuml[new_edges, ][["start"]] <- at
}
terminated_edges <- is.na(el_cuml[["current"]]) & is.na(el_cuml[["stop"]])
if (any(terminated_edges)) {
el_cuml[terminated_edges, ][["stop"]] <- at - 1
}
if (truncate != Inf) {
rel.age <- at - el_cuml[["stop"]]
rel.age <- ifelse(is.na(rel.age), 0, rel.age)
el_cuml <- el_cuml[rel.age <= truncate, ]
}
dat[["el.cuml"]][[network]] <- el_cuml[, c("head", "tail", "start", "stop")]
return(dat)
}
get_cumulative_edgelists_df <- function(dat, networks = NULL) {
networks <- if (is.null(networks)) seq_along(dat[["nwparam"]]) else networks
el_cuml_list <- lapply(networks, get_cumulative_edgelist, dat = dat)
el_cuml_df <- dplyr::bind_rows(el_cuml_list)
el_sizes <- vapply(el_cuml_list, nrow, numeric(1))
el_cuml_df[["network"]] <- rep(networks, el_sizes)
return(el_cuml_df)
}
get_partners <- function(dat, index_posit_ids, networks = NULL,
truncate = Inf, only.active.nodes = FALSE) {
el_cuml_df <- get_cumulative_edgelists_df(dat, networks)
index_unique_ids <- get_unique_ids(dat, index_posit_ids)
partner_head_df <- el_cuml_df[el_cuml_df[["head"]] %in% index_unique_ids, ]
partner_tail_df <- el_cuml_df[
el_cuml_df[["tail"]] %in% index_unique_ids,
c(2, 1, 3:5)
]
colnames(partner_head_df) <- c("index", "partner", "start", "stop", "network")
colnames(partner_tail_df) <- colnames(partner_head_df)
partner_df <- dplyr::bind_rows(partner_head_df, partner_tail_df)
if (only.active.nodes) {
active_partners <- is_active_unique_ids(dat, partner_df[["partner"]])
partner_df <- partner_df[active_partners, ]
}
if (truncate != Inf) {
at <- get_current_timestep(dat)
rel.age <- at - partner_df[["stop"]]
rel.age <- ifelse(is.na(rel.age), 0, rel.age)
partner_df <- partner_df[rel.age <= truncate, ]
}
return(partner_df)
}
|
radf_sb_ <- function(data, minw, lag, nboot, seed = NULL) {
y <- parse_data(data)
assert_na(y)
minw <- minw %||% psy_minw(data)
assert_positive_int(minw, greater_than = 2)
assert_positive_int(lag, strictly = FALSE)
assert_positive_int(nboot, greater_than = 2)
nc <- ncol(y)
nr <- nrow(y)
snames <- colnames(y)
pointer <- nr - minw - lag
initmat <- matrix(0, nc, 1 + lag)
resmat <- matrix(0, nr - 2 - lag, nc)
coefmat <- matrix(0, nc, 2 + lag)
set_rng(seed)
for (j in 1:nc) {
ys <- y[, j]
dy <- ys[-1] - ys[-nr]
ym <- embed(dy, lag + 2)
lr_dy <- lm(ym[, 1] ~ ym[, -1])
res <- as.vector(lr_dy$residuals)
coef <- as.vector(lr_dy$coefficients)
initmat[j, ] <- ym[1, -1]
coefmat[j, ] <- coef
resmat[, j] <- res
}
nres <- NROW(resmat)
show_pb <- getOption("exuber.show_progress")
pb <- set_pb(nboot)
pb_opts <- set_pb_opts(pb)
do_par <- getOption("exuber.parallel")
if (do_par) {
cl <- parallel::makeCluster(getOption("exuber.ncores"), type = "PSOCK")
registerDoSNOW(cl)
on.exit(parallel::stopCluster(cl))
}
set_rng(seed)
`%fun%` <- if (do_par) `%dorng%` else `%do%`
edf_bsadf_panel <- foreach(
i = 1:nboot,
.export = c("rls_gsadf", "unroot"),
.combine = "cbind",
.options.snow = pb_opts,
.inorder = FALSE
) %fun% {
boot_index <- sample(1:nres, replace = TRUE)
if (show_pb && !do_par)
pb$tick()
for (j in 1:nc) {
boot_res <- resmat[boot_index, j]
dboot_res <- boot_res - mean(boot_res)
dy_boot <- c(
initmat[j, lag:1],
stats::filter(coefmat[j, 1] + dboot_res,
coefmat[j, -1], "rec",
init = initmat[j, ]
)
)
y_boot <- cumsum(c(y[1, j], dy_boot))
yxmat_boot <- unroot(x = y_boot, lag)
aux_boot <- rls_gsadf(yxmat_boot, minw, lag)
bsadf_boot <- aux_boot[-c(1:(pointer + 3))]
}
bsadf_boot / nc
}
bsadf_crit <- unname(edf_bsadf_panel)
gsadf_crit <- apply(edf_bsadf_panel, 2, max) %>% unname()
list(bsadf_panel = bsadf_crit,
gsadf_panel = gsadf_crit) %>%
add_attr(
index = attr(y, "index"),
series_names = snames,
method = "Sieve Bootstrap",
n = nr,
minw = minw,
lag = lag,
iter = nboot,
seed = get_rng_state(seed),
parallel = do_par)
}
radf_sb_cv <- function(data, minw = NULL, lag = 0L,
nboot = 500L, seed = NULL) {
results <- radf_sb_(data, minw, nboot = nboot, lag = lag, seed = seed)
pcnt <- c(0.9, 0.95, 0.99)
bsadf_crit <- apply(results$bsadf_panel, 1, quantile, probs = pcnt) %>% t()
gsadf_crit <- quantile(results$gsadf_panel, probs = pcnt)
list(gsadf_panel_cv = gsadf_crit,
bsadf_panel_cv = bsadf_crit) %>%
inherit_attrs(results) %>%
add_class("radf_cv", "sb_cv")
}
radf_sb_distr <- function(data, minw = NULL, lag = 0L, nboot = 500L, seed = NULL) {
results <- radf_sb_(data, minw, nboot = nboot, lag = lag, seed = seed)
c(results$gsadf_panel) %>%
inherit_attrs(results) %>%
add_class("radf_distr", "sb_distr")
}
|
"check.matrix" <-
function(X, Z=NULL)
{
if(is.null(X)) return(NULL)
n <- nrow(X)
if(is.null(n)) { n <- length(X); X <- matrix(X, nrow=n) }
X <- as.matrix(X)
if(!is.null(Z)) {
Z <- as.vector(as.matrix(Z))
if(length(Z) != n) stop("mismatched row dimension in X and Z")
nna <- (1:n)[!is.na(Z) == 1]
nnan <- (1:n)[!is.nan(Z) == 1]
ninf <- (1:n)[!is.infinite(Z) == 1]
if(length(nna) < n) warning(paste(n-length(nna), "NAs removed from input vector"))
if(length(nnan) < n) warning(paste(n-length(nnan), "NaNs removed from input vector"))
if(length(ninf) < n) warning(paste(n-length(ninf), "Infs removed from input vector"))
neitherZ <- intersect(nna, intersect(nnan, ninf))
} else neitherZ <- (1:n)
nna <- (1:n)[apply(!is.na(X), 1, prod) == 1]
nnan <- (1:n)[apply(!is.nan(X), 1, prod) == 1]
ninf <- (1:n)[apply(!is.infinite(X), 1, prod) == 1]
if(length(nna) < n) warning(paste(n-length(nna), "NAs removed from input matrix"))
if(length(nnan) < n) warning(paste(n-length(nnan), "NaNs removed from input matrix"))
if(length(ninf) < n) warning(paste(n-length(ninf), "Infs removed from input matrix"))
neitherX <- intersect(nna, intersect(nnan, ninf))
if(length(neitherX) == 0)
stop("no valid (non-NA NaN or Inf) data found")
neither <- intersect(neitherZ, neitherX)
X <- matrix(X[neither,], nrow=length(neither))
Z <- Z[neither]
return(list(X=X, Z=Z))
}
"framify.X" <-
function(X, Xnames, d)
{
X <- data.frame(t(matrix(X, nrow=d)))
if(is.null(Xnames)) {
nms <- c();
for(i in 1:d) { nms <- c(nms, paste("x", i, sep="")) }
names(X) <- nms
} else { names(X) <- Xnames }
return(X)
}
|
getDistArg <- function(dist) {
if (exists(paste0('d', dist))) {
x <- unlist(strsplit(deparse(args(paste0('q', dist)))[1], ','))
out <- gsub(' |= [0-9]+',
'',
x[grep('function|lower.tail|log.p = FALSE|/',
x,
invert = TRUE)])
return(out)
} else {
message('Distribution in not defined')
}
}
getACSArg <- function(id) {
if (exists(paste0('acf', id))) {
x <- unlist(strsplit(deparse(args(paste0('acf', id)))[1], ','))
out <- gsub(' |= [0-9]+|)',
'',
x[grep('function',
x,
invert = TRUE)])
return(out)
} else {
message('ACS in not defined')
}
}
|
ATA.Decomposition <- function(input, s.model, s.type, s.frequency, seas_attr_set)
{
tsp_input <- tsp(input)
last_seas_type <- s.type
if (s.model == "none" | min(s.frequency)==1){
if (s.type=="A"){
adjX <- input
SeasActual <- rep(0,times=length(input))
SeasActual <- ts(SeasActual, frequency = tsp_input[3], start = tsp_input[1])
s.frequency <- frequency(input)
SeasIndex <- rep(0,times=s.frequency)
}else {
adjX <- input
SeasActual <- rep(1,times=length(input))
SeasActual <- ts(SeasActual, frequency = tsp_input[3], start = tsp_input[1])
s.frequency <- frequency(input)
SeasIndex <- rep(1,times=s.frequency)
}
}else {
if (class(input)[1]!="ts" & class(input)[1]!="msts"){
return("The data set must be time series object (ts or msts) ATA Method was terminated!")
}
input <- forecast::msts(input, start=tsp_input[1], seasonal.periods = s.frequency)
tsp_input <- tsp(input)
if (s.model=="decomp"){
if (s.type=="A"){
desX <- stats::decompose(input, type = c("additive"))
adjX <- forecast::seasadj(desX)
SeasActual <- desX$seasonal
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else {
desX <- stats::decompose(input, type = c("multiplicative"))
adjX <- forecast::seasadj(desX)
SeasActual <- desX$seasonal
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}
}else if (s.model=="stl"){
if (length(s.frequency)==1){
stldesX <- stats::stl(input, s.window = "per", robust=TRUE)
adjX <- forecast::seasadj(stldesX)
SeasActual <- forecast::seasonal(stldesX)
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else {
stldesX <- forecast::mstl(input, lambda = NULL, s.window = "per")
nameCol <- colnames(stldesX)
nameCol <- grep('Season', nameCol, value=TRUE)
if (length(nameCol)==0){
if (s.type=="A"){
adjX <- input
SeasActual <- forecast::msts(rep(0,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(0,times=max(s.frequency))
}else {
adjX <- input
SeasActual <- forecast::msts(rep(1,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(1,times=max(s.frequency))
}
}else {
adjX <- forecast::seasadj(stldesX)
if (length(s.frequency)==1){
SeasActual <- stldesX[,nameCol]
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else {
SeasActual <- rowSums(stldesX[,nameCol],na.rm=TRUE)
SeasActual <- forecast::msts(SeasActual, start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(NA,times=max(s.frequency))
for (s in 1:max(s.frequency)){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}
}
}
}else if (s.model=="stlplus"){
stlplusdesX <- stlplus::stlplus(input, s.window = "per", robust=TRUE)
adjX <- input - stlplusdesX$data$seasonal
SeasActual <- stlplusdesX$data$seasonal
SeasActual <- forecast::msts(SeasActual, start=tsp_input[1], seasonal.periods = s.frequency)
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else if (s.model=="stR"){
if (length(input)>1600){
stRdesX <- stR::AutoSTR(input)
}else {
stRdesX <- stR::AutoSTR(input, robust=TRUE)
}
stRcomp <- stR_components(stRdesX)
nameCol <- colnames(stRcomp)
nameCol <- grep('Seasonal', nameCol, value=TRUE)
if (length(nameCol)==0){
if (s.type=="A"){
adjX <- input
SeasActual <- forecast::msts(rep(0,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(0,times=max(s.frequency))
}else {
adjX <- input
SeasActual <- forecast::msts(rep(1,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(1,times=max(s.frequency))
}
}else {
adjX <- stR_seasadj(stRdesX)
if (length(s.frequency)==1){
SeasActual <- stRcomp[,nameCol]
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else {
SeasActual <- rowSums(stRcomp[,nameCol],na.rm=TRUE)
SeasActual <- forecast::msts(SeasActual, start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(NA,times=max(s.frequency))
for (s in 1:max(s.frequency)){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}
}
}else if (s.model=="tbats"){
tbatsdesX <- forecast::tbats(input, use.box.cox = FALSE)
tbatscomp <- forecast::tbats.components(tbatsdesX)
nameCol <- colnames(tbatscomp)
nameCol <- grep('season', nameCol, value=TRUE)
if (length(nameCol)==0){
if (s.type=="A"){
adjX <- input
SeasActual <- forecast::msts(rep(0,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(0,times=max(s.frequency))
}else {
adjX <- input
SeasActual <- forecast::msts(rep(1,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(1,times=max(s.frequency))
}
}else {
adjX <- forecast::seasadj(tbatsdesX)
if (length(s.frequency)==1){
SeasActual <- tbatscomp[,nameCol]
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(SeasActual[cycle(SeasActual)==s][1])
}
}else {
SeasActual <- rowSums(tbatscomp[,nameCol],na.rm=TRUE)
SeasActual <- forecast::msts(SeasActual, start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(NA,times=max(s.frequency))
for (s in 1:max(s.frequency)){
SeasIndex[s] <- as.numeric(mean(SeasActual[cycle(SeasActual)==s]))
}
}
}
}else if (s.model=="x13"){
x13desX <- seasonal::seas(input, transform.function="none", estimate.maxiter=seas_attr_set$x13.estimate.maxiter, estimate.tol=seas_attr_set$x13.estimate.tol)
SeasActual <- seasonal::series(x13desX,"seats.adjustfac")
ifelse(seasonal::udg(x13desX, stats = "finmode")=="additive", s.type <- "A", s.type <- "M")
if (is.null(SeasActual)) {
if (s.type=="A"){
adjX <- input
SeasActual <- forecast::msts(rep(0,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(0,times=max(s.frequency))
}else {
adjX <- input
SeasActual <- forecast::msts(rep(1,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(1,times=max(s.frequency))
}
}else {
adjX <- seasonal::series(x13desX,"seats.seasonaladj")
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(mean(SeasActual[cycle(SeasActual)==s]))
}
}
}else if (s.model=="x11"){
x11desX <- seasonal::seas(input, x11 = "", transform.function="none", estimate.maxiter=seas_attr_set$x11.estimate.maxiter, estimate.tol=seas_attr_set$x11.estimate.tol)
SeasActual <- seasonal::series(x11desX,"x11.adjustfac")
ifelse(seasonal::udg(x11desX, stats = "finmode")=="additive", s.type <- "A", s.type <- "M")
if (is.null(SeasActual)) {
if (s.type=="A"){
adjX <- input
SeasActual <- forecast::msts(rep(0,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(0,times=max(s.frequency))
}else {
adjX <- input
SeasActual <- forecast::msts(rep(1,times=length(input)), start=tsp_input[1], seasonal.periods = tsp_input[3])
SeasIndex <- rep(1,times=max(s.frequency))
}
}else {
adjX <- seasonal::series(x11desX,"x11.seasadj")
SeasIndex <- rep(NA,times=s.frequency)
for (s in 1:s.frequency){
SeasIndex[s] <- as.numeric(mean(SeasActual[cycle(SeasActual)==s]))
}
}
}else {
}
}
my_list <- list("AdjustedX" = adjX, "SeasIndex" = SeasIndex, "SeasActual" = SeasActual, "SeasType" = s.type)
return(my_list)
gc()
}
stR_components <- function(object)
{
len_y <- length(object$input$data)
len_x <- length(object$output$predictors) + 2
str_cmp <- matrix(0, len_y, len_x)
str_cmp[, 1] <- as.vector(object$input$data)
str_cmp[, ncol(str_cmp)] <- as.vector(object$output$random$data)
names <- rep("", ncol(str_cmp))
names[c(1, ncol(str_cmp))] = c("Data", "Random")
for(i in seq_along(object$output$predictors)) {
str_cmp[, i+1] <- object$output$predictors[[i]]$data
names[i+1] <- object$input$predictors[[i]]$name
}
colnames(str_cmp) <- names
str_cmp <- ts(str_cmp)
if("ts" %in% class(object$input$data))
tsp(str_cmp) <- tsp(object$input$data)
return(str_cmp)
}
stR_seasadj <- function(object, include = c("Trend", "Random"))
{
str_cmp <- stR_components(object)
nameTrend <- colnames(str_cmp)[2]
if(is.null(nameTrend) || is.na(nameTrend) || nchar(nameTrend) == 0) {
warning("Trend component is not specified by name, using the first component as the Trend component.")
colnames(str_cmp)[2] <- "Trend"
}
for(cmpname in include[!(include %in% colnames(str_cmp))]) {
warning(paste(cmpname, "is not one of the components of the decomposion, skipping..."))
}
result <- NULL
for(i in include[include %in% colnames(str_cmp)]) {
if(is.null(result)) {
result <- str_cmp[,i]
} else {
result <- result + str_cmp[,i]
}
}
return(result)
}
|
read_fwf <- function(file, col_positions = fwf_empty(file, skip, n = guess_max), col_types = NULL,
col_select = NULL,
id = NULL,
locale = default_locale(), na = c("", "NA"),
comment = "", trim_ws = TRUE, skip = 0, n_max = Inf,
guess_max = min(n_max, 1000), progress = show_progress(),
name_repair = "unique",
num_threads = readr_threads(),
show_col_types = should_show_types(),
lazy = should_read_lazy(), skip_empty_rows = TRUE) {
if (edition_first()) {
ds <- datasource(file, skip = skip, skip_empty_rows = skip_empty_rows)
if (inherits(ds, "source_file") && empty_file(file)) {
return(tibble::tibble())
}
tokenizer <- tokenizer_fwf(col_positions$begin, col_positions$end, na = na, comment = comment, trim_ws = trim_ws, skip_empty_rows = skip_empty_rows)
spec <- col_spec_standardise(
file,
skip = skip,
guess_max = guess_max,
tokenizer = tokenizer,
locale = locale,
col_names = col_positions$col_names,
col_types = col_types,
drop_skipped_names = TRUE
)
if (is.null(col_types) && !inherits(ds, "source_string") && !is_testing()) {
show_cols_spec(spec)
}
out <- read_tokens(datasource(file, skip = spec$skip, skip_empty_rows = skip_empty_rows), tokenizer, spec$cols, names(spec$cols),
locale_ = locale, n_max = if (n_max == Inf) -1 else n_max,
progress = progress
)
out <- name_problems(out, names(spec$cols), source_name(file))
attr(out, "spec") <- spec
return(warn_problems(out))
}
vroom::vroom_fwf(file,
col_positions = col_positions,
col_types = col_types,
col_select = {{col_select}},
id = id,
.name_repair = name_repair,
locale = locale,
na = na,
comment = comment,
skip_empty_rows = skip_empty_rows,
trim_ws = trim_ws,
skip = skip,
n_max = n_max,
guess_max = guess_max,
show_col_types = show_col_types,
progress = progress,
altrep = lazy,
num_threads = num_threads
)
}
fwf_empty <- function(file, skip = 0, skip_empty_rows = FALSE, col_names = NULL, comment = "", n = 100L) {
if (edition_first()) {
ds <- datasource(file, skip = skip, skip_empty_rows = skip_empty_rows)
out <- whitespaceColumns(ds, comment = comment, n = n)
out$end[length(out$end)] <- NA
col_names <- fwf_col_names(col_names, length(out$begin))
out$col_names <- col_names
return(out)
}
if (!missing(skip_empty_rows)) {
lifecycle::deprecate_soft("2.0.0", "readr::fwf_empty(skip_empty_rows = )")
}
vroom::fwf_empty(file = file, skip = skip, col_names = col_names, comment = comment, n = n)
}
fwf_widths <- function(widths, col_names = NULL) {
if (edition_first()) {
pos <- cumsum(c(1L, abs(widths)))
return(fwf_positions(pos[-length(pos)], pos[-1] - 1L, col_names))
}
vroom::fwf_widths(widths = widths, col_names = col_names)
}
fwf_positions <- function(start, end = NULL, col_names = NULL) {
if (edition_first()) {
stopifnot(length(start) == length(end))
col_names <- fwf_col_names(col_names, length(start))
return(tibble(
begin = start - 1L,
end = end,
col_names = as.character(col_names)
))
}
vroom::fwf_positions(start = start, end = end, col_names = col_names)
}
fwf_cols <- function(...) {
if (edition_first()) {
x <- lapply(list(...), as.integer)
names(x) <- fwf_col_names(names(x), length(x))
x <- tibble::as_tibble(x)
if (nrow(x) == 2) {
res <- fwf_positions(as.integer(x[1, ]), as.integer(x[2, ]), names(x))
} else if (nrow(x) == 1) {
res <- fwf_widths(as.integer(x[1, ]), names(x))
} else {
stop("All variables must have either one (width) two (start, end) values.",
call. = FALSE
)
}
return(res)
}
vroom::fwf_cols(...)
}
fwf_col_names <- function(nm, n) {
nm <- nm %||% rep("", n)
nm_empty <- (nm == "")
nm[nm_empty] <- paste0("X", seq_len(n))[nm_empty]
nm
}
|
predictL.lcmm <- function(x,newdata,var.time,na.action=1,confint=FALSE,...)
{
if(missing(newdata)) stop("The argument newdata should be specified")
if(missing(x)) stop("The argument x should be specified")
if (!inherits(x, "lcmm")) stop("use only with \"lcmm\" objects")
if (!all(x$Xnames2 %in% c(colnames(newdata),"intercept"))) {
stop(paste(c("newdata should at least include the following covariates: ","\n",x$Xnames2[-1]),collapse=" "))}
if (!inherits(newdata, "data.frame")) stop("newdata should be a data.frame object")
call_fixed <- x$call$fixed[3]
if(is.null(x$call$random)) {call_random <- -1} else call_random <- x$call$random[2]
if(is.null(x$call$classmb)) {call_classmb <- -1} else call_classmb <- x$call$classmb[2]
if(is.null(x$call$mixture)) {call_mixture <- -1} else call_mixture <- x$call$mixture[2]
if(x$conv==1|x$conv==2|x$conv==3) {
if(x$Xnames2[1]!="intercept"){
newdata1 <- newdata[,x$Xnames2]
colnames(newdata1) <- x$Xnames
newdata1 <- data.frame(newdata1)
}else{
newdata1 <- cbind(rep(1,length=length(newdata[,1])),newdata[,x$Xnames2[-1]])
colnames(newdata1) <- c("intercept",x$Xnames2[-1])
newdata1 <- data.frame(newdata1)
}
X1 <- NULL
X2 <- NULL
b1 <- NULL
b2 <- NULL
if(!(na.action%in%c(1,2)))stop("only 1 for 'na.omit' or 2 for 'na.fail' are required in na.action argument")
if(na.action==1){
na.action=na.omit
}else{
na.action=na.fail
}
if(!is.null(x$data))
{
olddata <- x$data
}
else
{
olddata <- eval(x$call$data)
}
for(v in x$Xnames2[-1])
{
if (is.factor(olddata[,v]) & !(is.factor(newdata[,v])))
{
mod <- levels(olddata[,v])
if (!(levels(as.factor(newdata1[,v])) %in% mod)) stop(paste("invalid level in factor", v))
newdata1[,v] <- factor(newdata1[,v], levels=mod)
}
}
z <- all.names(call_fixed)
ind_factor <- which(z=="factor")
if(length(ind_factor))
{
nom.factor <- z[ind_factor+1]
for (v in nom.factor)
{
mod <- levels(as.factor(olddata[,v]))
if (!all(levels(as.factor(newdata1[,v])) %in% mod)) stop(paste("invalid level in factor", v))
newdata1[,v] <- factor(newdata1[,v], levels=mod)
}
}
call_fixed <- gsub("factor","",call_fixed)
z <- all.names(call_random)
ind_factor <- which(z=="factor")
if(length(ind_factor))
{
nom.factor <- z[ind_factor+1]
for (v in nom.factor)
{
mod <- levels(as.factor(olddata[,v]))
if (!all(levels(as.factor(newdata1[,v])) %in% mod)) stop(paste("invalid level in factor", v))
newdata1[,v] <- factor(newdata1[,v], levels=mod)
}
}
call_random <- gsub("factor","",call_random)
z <- all.names(call_classmb)
ind_factor <- which(z=="factor")
if(length(ind_factor))
{
nom.factor <- z[ind_factor+1]
for (v in nom.factor)
{
mod <- levels(as.factor(olddata[,v]))
if (!all(levels(as.factor(newdata1[,v])) %in% mod)) stop(paste("invalid level in factor", v))
newdata1[,v] <- factor(newdata1[,v], levels=mod)
}
}
call_classmb <- gsub("factor","",call_classmb)
z <- all.names(call_mixture)
ind_factor <- which(z=="factor")
if(length(ind_factor))
{
nom.factor <- z[ind_factor+1]
for (v in nom.factor)
{
mod <- levels(as.factor(olddata[,v]))
if (!all(levels(as.factor(newdata1[,v])) %in% mod)) stop(paste("invalid level in factor", v))
newdata1[,v] <- factor(newdata1[,v], levels=mod)
}
}
call_mixture <- gsub("factor","",call_mixture)
mcall <- match.call()[c(1,match(c("data","subset","na.action"),names(match.call()),0))]
mcall$na.action <- na.action
mcall$data <- newdata1
m <- mcall
m$formula <- formula(paste("~",call_fixed,sep=""))
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
na.fixed <- attr(m,"na.action")
if(!is.null(x$call$mixture)){
m <- mcall
m$formula <- formula(paste("~",call_mixture,sep=""))
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
na.mixture <- attr(m,"na.action")
}else{
na.mixture <- NULL
}
if(!is.null(x$call$random)){
m <- mcall
m$formula <- formula(paste("~",call_random,sep=""))
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
na.random <- attr(m,"na.action")
}else{
na.random <- NULL
}
if(!is.null(x$call$classmb)){
m <- mcall
m$formula <- formula(paste("~",call_classmb,sep=""))
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
na.classmb <- attr(m,"na.action")
}else{
na.classmb <- NULL
}
if(!missing( var.time))
{
if(!(var.time %in% colnames(newdata))) stop("'var.time' should be included in newdata")
if(var.time %in% colnames(newdata1))
{
times <- newdata1[,var.time,drop=FALSE]
}
else
{
times <- newdata[,var.time,drop=FALSE]
}
}
else
{
times <- newdata[,1,drop=FALSE]
}
na.action <- unique(c(na.fixed,na.mixture,na.random,na.classmb))
if(!is.null(na.action)){
newdata1 <- newdata1[-na.action,]
times <- times[-na.action]
}
X_fixed <- model.matrix(formula(paste("~",call_fixed,sep="")),data=newdata1)
if(colnames(X_fixed)[1]=="(Intercept)"){
colnames(X_fixed)[1] <- "intercept"
int.fixed <- 1
}
if(!is.null(x$call$mixture)){
X_mixture <- model.matrix(formula(paste("~",call_mixture,sep="")),data=newdata1)
if(colnames(X_mixture)[1]=="(Intercept)"){
colnames(X_mixture)[1] <- "intercept"
int.mixture <- 1
}
id.X_mixture <- 1
}else{
id.X_mixture <- 0
}
if(!is.null(x$call$random)){
X_random <- model.matrix(formula(paste("~",call_random,sep="")),data=newdata1)
if(colnames(X_random)[1]=="(Intercept)"){
colnames(X_random)[1] <- "intercept"
int.random <- 1
}
id.X_random <- 1
}else{
id.X_random <- 0
}
if(!is.null(x$call$classmb)){
X_classmb <- model.matrix(formula(paste("~",call_classmb,sep="")),data=newdata1)
colnames(X_classmb)[1] <- "intercept"
id.X_classmb <- 1
}else{
id.X_classmb <- 0
}
if(x$N[6]>0)
{
z <- which(x$idcor0==1)
var.cor <- newdata1[,x$Xnames[z]]
}
newdata1 <- X_fixed
colX <- colnames(X_fixed)
if(id.X_mixture == 1){
for(i in 1:length(colnames(X_mixture))){
if((colnames(X_mixture)[i] %in% colnames(newdata1))==F){
newdata1 <- cbind(newdata1,X_mixture[,i])
colnames(newdata1) <- c(colX,colnames(X_mixture)[i])
colX <- colnames(newdata1)
}
}
}
if(id.X_random == 1){
for(i in 1:length(colnames(X_random))){
if((colnames(X_random)[i] %in% colnames(newdata1))==F){
newdata1 <- cbind(newdata1,X_random[,i])
colnames(newdata1) <- c(colX,colnames(X_random)[i])
colX <- colnames(newdata1)
}
}
}
if(id.X_classmb == 1){
for(i in 1:length(colnames(X_classmb))){
if((colnames(X_classmb)[i] %in% colnames(newdata1))==F){
newdata1 <- cbind(newdata1,X_classmb[,i])
colnames(newdata1) <- c(colX,colnames(X_classmb)[i])
colX <- colnames(newdata1)
}
}
}
if(x$N[6]>0)
{
if( x$idg0[z]==0 & x$idea0[z]==0 & x$idprob0[z]==0)
{
newdata1 <- cbind(newdata1,var.cor)
colnames(newdata1) <- c(colX,x$Xnames[z])
colX <- colnames(newdata1)
}
}
placeV <- list()
placeV$commun <- NA
for(i in 1:x$ng)
{
placeV[paste("class",i,sep="")] <- NA
}
kk<-0
for(k in 1:length(x$idg0))
{
if(x$idg0[k]==1)
{
X1 <- cbind(X1,newdata1[,k])
if (k==1) b1 <- c(b1,0)
if (k>1)
{
place <- x$N[1]+kk
b1 <- c(b1,x$best[place+1])
placeV$commun <- c(placeV$commun,place+1)
kk <- kk+1
}
}
if(x$idg0[k]==2)
{
X2 <- cbind(X2,newdata1[,k])
if (k==1)
{
place1 <- x$N[1]+kk+1
place2 <- x$N[1]+kk+x$ng-1
b2 <- rbind(b2,c(0,x$best[place1:place2]))
for(i in 2:x$ng)
{
placeV[[paste("class",i,sep="")]] <- c(placeV[[paste("class",i,sep="")]],x$N[1]+kk+i-1)
}
kk <- kk+x$ng-1
}
if (k>1)
{
place1 <- x$N[1]+kk+1
place2 <- x$N[1]+kk+x$ng
b2 <- rbind(b2,x$best[place1:place2])
for(i in 1:x$ng)
{
placeV[[paste("class",i,sep="")]] <- c(placeV[[paste("class",i,sep="")]],x$N[1]+kk+i)
}
kk <- kk+x$ng
}
}
}
Y<-matrix(0,length(newdata1[,1]),x$ng)
colnames(Y) <- paste("class",1:x$ng,sep="")
for(g in 1:x$ng){
if(length(b1) != 0){
Y[,g]<- X1 %*% b1
}
if(length(b2) != 0){
Y[,g]<- Y[,g] + X2 %*% b2[,g]
}
}
Vbeta <- matrix(0,x$N[2],x$N[2])
npm <- length(x$best)
indice <- 1:npm * (1:npm+1) /2
indtmp <- indice[(x$N[1]+1):(x$N[1]+x$N[2])]
indtmp <- cbind(indtmp-0:(length(indtmp)-1),indtmp)
indV <- NULL
for(i in 1:nrow(indtmp))
{
indV <- c(indV,seq(indtmp[i,1],indtmp[i,2]))
}
Vbeta[upper.tri(Vbeta, diag=TRUE)] <- x$V[indV]
Vbeta <- t(Vbeta)
Vbeta[upper.tri(Vbeta, diag=TRUE)] <- x$V[indV]
lower <- matrix(0,nrow(Y),ncol(Y))
upper <- matrix(0,nrow(Y),ncol(Y))
colnames(lower) <- paste("lower.class",1:x$ng,sep="")
colnames(upper) <- paste("upper.class",1:x$ng,sep="")
if(x$ng==1)
{
varpred <- apply(X1[,-1,drop=FALSE],1,function(x) matrix(x,nrow=1) %*% Vbeta %*% matrix(x,ncol=1))
lower[,1] <- Y[,1] -1.96 * sqrt(varpred)
upper[,1] <- Y[,1] +1.96 * sqrt(varpred)
}
else
{
for(g in 1:x$ng)
{
ind <- na.omit(c(placeV[["commun"]],placeV[[paste("class",g,sep="")]]))
if(g==1)
{
if(x$idg0[1]==1)
{
X12 <- X12 <- cbind(X1[,-1,drop=FALSE],X2)
}
if(x$idg0[1]==2)
{
X12 <- X12 <- cbind(X1,X2[,-1,drop=FALSE])
}
}
else
{
X12 <- cbind(X1,X2)
}
X12 <- X12[,order(ind),drop=FALSE]
varclass <- Vbeta[sort(ind)-x$N[1],sort(ind)-x$N[1]]
varpred <- apply(X12,1,function(x) matrix(x,nrow=1) %*% varclass %*% matrix(x,ncol=1))
lower[,g] <- Y[,g] -1.96 * sqrt(varpred)
upper[,g] <- Y[,g] +1.96 * sqrt(varpred)
}
}
if(confint==TRUE)
{
res <- cbind(Y,lower,upper)
if(x$ng==1) colnames(res) <- c("pred","lower.pred","upper.pred")
if(x$ng>1) colnames(res) <- c(paste("pred_class",1:x$ng,sep=""),paste("lower.pred_class",1:x$ng,sep=""),paste("upper.pred_class",1:x$ng,sep=""))
res.list <- NULL
res.list$pred <- res
res.list$times <- times
}
if(confint==FALSE)
{
if(x$ng==1) colnames(Y) <- "pred"
if(x$ng>1) colnames(Y) <- paste("pred_class",1:x$ng,sep="")
res.list <- NULL
res.list$pred <- Y
res.list$times <- times
}
}
else{
cat("Output can not be produced since the program stopped abnormally.")
res.list <- list(pred=NA,times=NA)
}
class(res.list) <- "predictL"
return(res.list)
}
predictL <- function(x,newdata,var.time,na.action=1,confint=FALSE,...) UseMethod("predictL")
|
"realdata_covariates"
"realdata_alpha"
|
hanning <- function(n){
generate_window(n, 1L)
}
hamming <- function(n){
generate_window(n, 2L)
}
blackman <- function(n){
generate_window(n, 3L)
}
bartlett <- function(n){
generate_window(n, 4L)
}
welch <- function(n){
generate_window(n, 5L)
}
flattop <- function(n){
generate_window(n, 6L)
}
bharris <- function(n){
generate_window(n, 7L)
}
bnuttall <- function(n){
generate_window(n, 8L)
}
sine <- function(n){
generate_window(n, 9L)
}
nuttall <- function(n){
generate_window(n, 10L)
}
bhann <- function(n){
generate_window(n, 11L)
}
lanczos <- function(n){
generate_window(n, 12L)
}
gauss <- function(n){
generate_window(n, 13L)
}
tukey <- function(n){
generate_window(n, 14L)
}
dolph <- function(n){
generate_window(n, 15L)
}
cauchy <- function(n){
generate_window(n, 16L)
}
parzen <- function(n){
generate_window(n, 17L)
}
bohman <- function(n){
generate_window(n, 19L)
}
generate_window <- function(n, type){
n <- as.integer(n)
type <- as.integer(type)
assert_range(n)
assert_range(type, max = 19)
.Call(R_generate_window, n, type)
}
assert_range <- function(x, min = 0, max = Inf){
stopifnot(length(x) == 1)
stopifnot(x >= min)
stopifnot(x <= max)
}
|
calculateEllipse <- function(means,
sd,
alpha = 0.05){
if(!is.vector(means, mode = "numeric") | length(means)!= 2){
stop("means must be a length 2 numeric vector.")
}
if(!is.vector(sd, mode = "numeric") | length(sd)!= 2){
stop("sd must be a length 2 numeric vector.")
}
if(!is.vector(alpha, mode = "numeric") | length(alpha)!= 1){
stop("alpha must be a length 1 numeric vector.")
}
if(alpha > 1 | alpha < 0){
stop("alpha must take a value between 0 and 1")
}
p <- (1-alpha) + (alpha/2)
a <- qnorm(p)*sd[1]
b <- qnorm(p)*sd[2]
t <- seq(0, 2*pi, by=pi/100)
xt <- means[1] + a*cos(t)
yt <- means[2] + b*sin(t)
return(list(x = xt, y = yt))
}
|
test_that("calcCohensD produces known result", {
g1 = c(11, 12, 13, 14, 15)
g2 = c(26, 27, 28, 29)
twoGpsVec = c(g1, g2)
grpLabels = rep(c("A", "B"), times=c(length(g1), length(g2)))
freqVec = rep(1, length(twoGpsVec))
lambdas = c(A=1, B=-1)
truth = (mean(g1) - mean(g2)) / bootES:::pooledSD(twoGpsVec, grpLabels)
d.res = bootES:::calcCohensD(twoGpsVec, freq=freqVec, grps=grpLabels,
contrast=lambdas)
expect_equal(truth, d.res, tolerance=1e-4)
d.res.switched = bootES:::calcCohensD(twoGpsVec, freq=freqVec,
grps=grpLabels, contrast=c(A=-1, B=1))
expect_equal(-1 * truth, d.res.switched, tolerance=1e-4)
truth = (mean(g1) - mean(g2)) / bootES:::pooledSD(twoGpsVec, grpLabels,
pop.sd=TRUE)
d.res = bootES:::calcCohensD(twoGpsVec, freq=freqVec, grps=grpLabels,
contrast=lambdas, cohens.d.sigma=TRUE)
expect_equal(truth, d.res, tolerance=1e-4)
truth = (mean(g1) - mean(g2)) / sqrt(sum(((g1 - mean(g1))^2) / length(g1)))
d.res.glass = bootES:::calcCohensD(twoGpsVec, freq=freqVec,
grps=grpLabels, contrast=lambdas, cohens.d.sigma=TRUE, glass.control="A")
expect_equal(truth, d.res.glass, tolerance=1e-4)
truth = (mean(g1) - mean(g2)) / sd(g1)
d.res.glass = bootES:::calcCohensD(twoGpsVec, freq=freqVec,
grps=grpLabels, contrast=lambdas, cohens.d.sigma=FALSE, glass.control="A")
expect_equal(truth, d.res.glass, tolerance=1e-4)
})
|
library(testthat)
test_that('getWFmean works for simple example of linear densities', {
x = seq(0,1,length.out =512)
y = t(sapply(seq(0.5, 1.5, length.out = 4), function(b) b + 2*(1 - b)*x))
y.qd = t(sapply(seq(0.5, 1.5, length.out = 4), function(b) (b^2 + 4*(1-b)*x)^(-1/2)))
expect_equal( getWFmean(dmatrix = y, dSup = x), qd2dens(qd = colMeans(y.qd), qdSup = x, dSup = x) , tol = 1e-2)
})
|
findBottlenecks <- function(file, unit="min", cumulative=TRUE) {
if(length(file)>1 || any(grepl("\n",file))) {
f <- unlist(strsplit(file,"\n"))
} else {
f <- readLines(file)
}
f <- grep("in [0-9.]* seconds",f,value=TRUE)
x <- data.frame(level = nchar(gsub(paste0("^(", getConfig("indentationCharacter"), "*).*$"), "\\1", f)))
x$class <- NA
x$class[grepl("readSource",f)] <- "read"
x$class[grepl("downloadSource",f)] <- "download"
x$class[grepl("calcOutput",f)] <- "calc"
x$class[grepl("retrieveData",f)] <- "retrieve"
if(anyNA(x$class)) {
warning("Some classes could not be properly detected!")
x$class[is.na(x$class)] <- "unknown"
}
x$level[x$class=="retrieve"] <- -1
x$type <- gsub("([\"= ]|type)","",gsub("^[^(]*\\(([^,)]*)[),].*$","\\1",f))
x$"time[s]" <- as.numeric(gsub("^.* in ([0-9.]*) seconds.*$","\\1",f))
x$"net[s]" <- NA
runtime <- rep(0,max(x$level)+3)
for(i in 1:nrow(x)) {
l <- x$level[i]+2
runtime[l] <- runtime[l] + x$time[i]
x$"net[s]"[i] <- x$"time[s]"[i] - runtime[l+1]
runtime[l+1] <- 0
}
if(cumulative) {
out <- NULL
for (cl in unique(x$class)) {
y <- x[x$class==cl,]
for (i in unique(y$type)) {
z <- y[y$type==i,]
z$`time[s]`[1] <- sum(z$`time[s]`)
z$`net[s]`[1] <- sum(z$`net[s]`)
out <- rbind(out,z[1,])
}
}
x <- out
}
if (unit == "min") {
x$"time[min]" <- round(x$"time[s]"/60,2)
x$"net[min]" <- round(x$"net[s]"/60,2)
} else if (unit == "h") {
x$"time[h]" <- round(x$"time[s]"/60/60,2)
x$"net[h]" <- round(x$"net[s]"/60/60,2)
}
totalruntime <- sum(x$"time[s]"[x$level == -1])
th <- floor(totalruntime/3600)
tmin <- floor((totalruntime - th*3600)/60)
ts <- floor(totalruntime - th*3600 - tmin*60)
message("Total runtime: ", th, " hours ", tmin, " minutes ",ts," seconds")
x$"time[%]" <- round(x$"time[s]"/totalruntime*100,2)
x$"net[%]" <- round(x$"net[s]"/totalruntime*100,2)
x <- x[robustOrder(x$"net[s]", decreasing = TRUE),]
if (unit %in% c("min","h")) {
x$"time[s]" <- NULL
x$"net[s]" <- NULL
}
x <- x[c(1:3,grep("time",names(x)),grep("net",names(x)))]
return(x)
}
|
stopifnot(require("dplyr"))
stopifnot(require("testthat"))
stopifnot(require("yaml"))
stopifnot(require("knitr"))
stopifnot(require("readr"))
stopifnot(file.exists("inst/docs/tests.csv"))
test <- read_csv("inst/docs/tests.csv", show_col_types=FALSE)
stories <- yaml.load_file("inst/docs/stories.yaml")
story <- Map(stories, names(stories), f = function(story, storylabel) {
tibble(
STID = storylabel,
STORY = story$summary,
test = story$tests
)
})
story <- bind_rows(story)
all <- left_join(story, test, by = "test")
if(any(is.na(all$failed))) {
warning("some NA found")
}
write_csv(all, "inst/docs/stories-tests.csv")
x <- kable(all, format = "markdown")
writeLines(x, con = "inst/docs/stories.md")
|
setMethod(f=".composeFilename",
signature=signature(x="AbstractMassObject"),
definition=function(x, fileExtension="csv") {
if (!is.null(metaData(x)$fullName)) {
if (length(metaData(x)$fullName) > 1) {
filename <- paste0(metaData(x)$fullName, collapse="_")
} else {
filename <- metaData(x)$fullName
}
} else {
filename <- .withoutFileExtension(metaData(x)$file[1])
}
paste(filename, fileExtension, sep=".")
})
setMethod(f=".composeFilename",
signature=signature(x="list"),
definition=function(x, fileExtension="csv") {
stopifnot(MALDIquant:::.isMassObjectList(x))
filenames <- unlist(lapply(x, .composeFilename, fileExtension=fileExtension))
.uniqueBaseFilenames(filenames, fileExtension)
})
|
print.qanova <-
function(x,...)
{
cat("Call:\n")
print(x$call)
partable <- data.frame(x$p.value)
cat("\n")
print(round(partable, 4))
cat("\n")
}
|
set.seed(290875)
pkgs <- sapply(c("mlt", "survival", "tram", "lme4", "gridExtra",
"lattice", "latticeExtra", "mvtnorm", "ordinalCont"), require, char = TRUE)
if (any(!pkgs))
{
cat(paste("Package(s)", paste(names(pkgs)[!pkgs], collapse = ", "),
"not available, stop processing.",
"\\end{document}\n"))
knitr::knit_exit()
}
if (file.exists("packages.bib")) file.remove("packages.bib")
pkgversion <- function(pkg) {
pkgbib(pkg)
packageDescription(pkg)$Version
}
pkgbib <- function(pkg) {
x <- citation(package = pkg, auto = TRUE)[[1]]
b <- toBibtex(x)
b <- gsub("Buehlmann", "B{\\\\\"u}hlmann", b)
b[1] <- paste("@Manual{pkg:", pkg, ",", sep = "")
if (is.na(b["url"])) {
b[length(b)] <- paste(" URL = {http://CRAN.R-project.org/package=",
pkg, "}", sep = "")
b <- c(b, "}")
}
cat(b, sep = "\n", file = "packages.bib", append = TRUE)
}
pkg <- function(pkg) {
vrs <- try(pkgversion(pkg))
if (inherits(vrs, "try-error")) return(NA)
paste("\\\\pkg{", pkg, "} \\\\citep[version~",
vrs, ",][]{pkg:", pkg, "}", sep = "")
}
pkg("mlt")
pkg("tram")
pkg("SparseGrid")
cat(c("@Manual{vign:mlt.docreg,",
" title = {Most Likely Transformations: The mlt Package},",
" author = {Torsten Hothorn},",
paste(" year = ", substr(packageDescription("mlt.docreg")$Date, 1, 4), ",", sep = ""),
paste(" note = {R package vignette version ", packageDescription("mlt.docreg")$Version, "},", sep = ""),
" url = {https://CRAN.R-project.org/package=mlt.docreg},",
"}"), file = "packages.bib", append = TRUE, sep = "\n")
|
BinUplift <- function(data, treat, outcome, x, n.split = 10, alpha = 0.05, n.min = 30){
if (n.split <= 0 ) {
stop("Number of splits must be positive")
}
if (alpha < 0 | alpha > 1 ) {
stop("alpha must be between 0 and 1")
}
if (sum(is.na(data[[outcome]])) > 0 ) {
stop("Dependent variable contains missing values: remove the observations and proceed")
}
if (sum(is.na(data[[treat]])) > 0 ) {
stop("Treatment variable contains missing values: remove the observations and proceed")
}
if (length(unique(data[[x]])) < 3) {
stop("Independent variable must contain at least 3 different unique values")
}
if (sum(is.na(data[[x]])) > 0 ) {
warning("Independent variable contains missing values: remove the observations and proceed")
}
data <- data[is.na(data[[x]])==FALSE,]
BinUpliftStump <- function(data, outcome, treat, x, n.split){
x.cut <- unique(quantile(data[[x]], seq(0, 1, 1/n.split)))
splits <- matrix(data = NA, nrow = length(x.cut), ncol = 16)
colnames(splits) <- c("x.cut", "n.lt", "n.lc", "p.lt", "p.lc", "u.l",
"n.rt", "n.rc", "p.rt", "p.rc", "u.r", "diff", "p.t", "p.c",
"p.t.n.t", "p.c.n.c")
for(i in 1:length(x.cut)){
index.l <- data[[x]] < x.cut[i]
index.r <- data[[x]] >= x.cut[i]
splits[i,1] <- x.cut[i]
left <- data[index.l,]
right <- data[index.r,]
splits[i, 2] <- sum(left[[treat]]==1)
splits[i, 3] <- sum(left[[treat]]==0)
splits[i, 4] <- sum(left[[treat]]==1 & left[[outcome]]==1)/splits[i, 2]
splits[i, 5] <- sum(left[[treat]]==0 & left[[outcome]]==1)/splits[i, 3]
splits[i, 6] <- splits[i, 4] - splits[i, 5]
splits[i, 7] <- sum(right[[treat]]==1)
splits[i, 8] <- sum(right[[treat]]==0)
splits[i, 9] <- sum(right[[treat]]==1 & right[[outcome]]==1)/splits[i, 7]
splits[i, 10] <- sum(right[[treat]]==0 & right[[outcome]]==1)/splits[i, 8]
splits[i, 11] <- splits[i, 9] - splits[i, 10]
splits[i, 12] <- abs(splits[i, 6] - splits[i, 11])
splits[i, 13] <- sum(data[[treat]]==1 & data[[outcome]]==1)/sum(data[[treat]]==1)
splits[i, 14] <- sum(data[[treat]]==0 & data[[outcome]]==1)/sum(data[[treat]]==0)
splits[i, 15] <- sum(data[[treat]]==1 & data[[outcome]]==1)
splits[i, 16] <- sum(data[[treat]]==0 & data[[outcome]]==1)
}
return(splits)
}
BinUpliftTest <- function(splits, alpha, n.min){
z.a <- qnorm(0.5*alpha, mean = 0, sd = 1, lower.tail = FALSE, log.p = FALSE)
test.splits <- data.frame(splits)
test.splits$sign <- 0
test.splits <- test.splits[complete.cases(test.splits),]
test.splits$n.t <- test.splits$n.lt + test.splits$n.rt
test.splits$n.c <- test.splits$n.lc + test.splits$n.rc
test.splits$z_t <- test.splits$n.lt * test.splits$p.lt
test.splits$z_c <- test.splits$n.lc * test.splits$p.lc
test.splits$odds_ratio_t <- (test.splits$z_t / (test.splits$n.lt - test.splits$z_t)) /
((test.splits$p.t * test.splits$n.t - test.splits$z_t)/(test.splits$n.rt - (test.splits$p.t * test.splits$n.t - test.splits$z_t)))
test.splits$odds_ratio_c <- (test.splits$z_c / (test.splits$n.lc - test.splits$z_c)) /
((test.splits$p.c * test.splits$n.c - test.splits$z_c)/(test.splits$n.rc - (test.splits$p.c * test.splits$n.c - test.splits$z_c)))
test.splits <- test.splits[is.finite(test.splits$odds_ratio_t) == TRUE,]
test.splits <- test.splits[is.finite(test.splits$odds_ratio_c) == TRUE,]
test.splits <- test.splits[test.splits$odds_ratio_t > 0,]
test.splits <- test.splits[test.splits$odds_ratio_c > 0,]
if (nrow(test.splits) == 0) {
return(test.splits)
}
test.splits$esp_t <- 0
test.splits$esp_c <- 0
test.splits$var_t <- 0
test.splits$var_c <- 0
for (i in 1:nrow(test.splits)){
test.splits[i,]$esp_t <- BiasedUrn::meanFNCHypergeo(m1=test.splits[i,]$n.lt,
m2=test.splits[i,]$n.rt,
n=test.splits[i,]$p.t.n.t,
odds=test.splits$odds_ratio_t[i])
test.splits[i,]$esp_c <- BiasedUrn::meanFNCHypergeo(m1=test.splits[i,]$n.lc,
m2=test.splits[i,]$n.rc,
n=test.splits[i,]$p.c.n.c,
odds=test.splits$odds_ratio_c[i])
test.splits[i,]$var_t <- BiasedUrn::varFNCHypergeo(m1=test.splits[i,]$n.lt,
m2=test.splits[i,]$n.rt,
n=test.splits[i,]$p.t.n.t,
odds=test.splits$odds_ratio_t[i])
test.splits[i,]$var_c <- BiasedUrn::varFNCHypergeo(m1=test.splits[i,]$n.lc,
m2=test.splits[i,]$n.rc,
n=test.splits[i,]$p.c.n.c,
odds=test.splits$odds_ratio_c[i])
}
test.splits$z.num <- (test.splits$p.lt - test.splits$p.lc - test.splits$p.rt + test.splits$p.rc)
test.splits$z.den <- sqrt( (test.splits$n.t^2)*test.splits$var_t / ((test.splits$n.lt^2)*(test.splits$n.rt^2)) +
(test.splits$n.c^2)*test.splits$var_c / ((test.splits$n.lc^2)*(test.splits$n.rc^2)) )
test.splits$z.obs <- abs(test.splits$z.num / test.splits$z.den)
test.splits$sign <- 1*(test.splits$z.obs > z.a)
argmax.size <- test.splits[test.splits$n.lt > n.min & test.splits$n.lc > n.min & test.splits$n.rt > n.min & test.splits$n.rc > n.min,]
argmax.cut <- argmax.size[which.max(argmax.size$z.obs),]
argmax.cut$x.pos <- which(test.splits$x.cut == argmax.cut$x.cut)
return(argmax.cut)
}
BinUpliftTree <- function(data, outcome, treat, x, n.split, alpha, n.min){
stump <- BinUpliftStump(data, outcome, treat, x, n.split)
best <- BinUpliftTest(stump, alpha, n.min)
if (best$sign == 0 || nrow(best) == 0) {
return("oups..no significant split")
} else if (best$sign == 1) {
print(paste("The variable", x, "has been cut at:"))
print(best$x.cut)
l.cuts <- best$x.pos - 1
r.cuts <- n.split-best$x.pos + 1
l.index <- data[[x]] < best$x.cut
r.index <- data[[x]] >= best$x.cut
l.create <- data[l.index,]
r.create <- data[r.index,]
l.stump <- BinUpliftStump(l.create, outcome, treat, x, l.cuts)
r.stump <- BinUpliftStump(r.create, outcome, treat, x, r.cuts)
l.best <- BinUpliftTest(l.stump, alpha, n.min)
r.best <- BinUpliftTest(r.stump, alpha, n.min)
if (l.best$sign == 0 || nrow(l.best) == 0) {
if (r.best$sign == 0 || nrow(r.best) == 0) {
return (best)
} else if (r.best$sign == 1) {
return (rbind(best, BinUpliftTree(r.create, outcome, treat, x, r.cuts, alpha, n.min)))
}
} else if (l.best$sign == 1) {
if (r.best$sign == 0 || nrow(r.best) == 0){
return (rbind(BinUpliftTree(l.create, outcome, treat, x, l.cuts, alpha, n.min), best))
} else if (r.best$sign == 1) {
return (rbind(BinUpliftTree(l.create, outcome, treat, x, l.cuts, alpha, n.min), best, BinUpliftTree(r.create, outcome, treat, x, r.cuts, alpha, n.min)))
}
}
}
}
BinUpliftCatRank <- function(data, outcome, treat, x){
splits <- matrix(data = NA, nrow = length(levels(data[[x]])), ncol=6)
colnames(splits) <- c("cat", "n.t", "n.c", "p.t", "p.c", "u")
splits <- as.data.frame(splits)
for(i in 1:nrow(splits)){
splits[i, 1] <- levels(data[[x]])[[i]]
splits[i, 2] <- sum(data[[treat]]==1 & data[[x]]== splits[i, 1])
splits[i, 3] <- sum(data[[treat]]==0 & data[[x]]== splits[i, 1])
splits[i, 4] <- sum(data[[treat]]==1 & data[[x]]== splits[i, 1] & data[[outcome]]==1)/splits[i, 2]
splits[i, 5] <- sum(data[[treat]]==0 & data[[x]]== splits[i, 1] & data[[outcome]]==1)/splits[i, 3]
splits[i, 6] <- splits[i, 4] - splits[i, 5]
}
splits$cat.rank <- rank(splits$u, ties.method = "random")
x.rank <- splits[, c(1,7)]
x.merge <- merge(x.rank, data, by.x = 'cat', by.y = 'x')
names(x.merge)[names(x.merge) == 'cat.rank'] <- 'x'
x.rank <- x.rank[order(x.rank$cat.rank),]
x.rank$cat <- paste0("'", x.rank$cat, "'")
res <- list(x.rank, x.merge)
return(res)
}
if (is.factor(data[[x]])==TRUE) {
out.cat <- BinUpliftCatRank(data, outcome, treat, x)[[2]]
out.link <- BinUpliftCatRank(data, outcome, treat, x)[[1]]
out.tree <- BinUpliftTree(out.cat, outcome, treat, x, length(unique(out.cat$x))-1, alpha, n.min)
out.tree.cat <- list("out.tree" = out.tree, "out.link" = out.link)
return(out.tree.cat)
} else if (is.factor(data[[x]])==FALSE) {
out.tree <- BinUpliftTree(data, outcome, treat, x, n.split, alpha, n.min)
class(out.tree) <- "BinUplift"
return(out.tree)
}
}
|
savit.gol <- function(x, filt, filt_order = 4, der_order = 0) {
if(is.numeric(x)==F)
stop("Argument 'x' must be numeric")
if(is.numeric(filt)==F)
stop("Argument 'filt' must be numeric")
if (filt <= 1 || filt %% 2 == 0)
stop("Argument 'filt' must be a odd integer number, > than 1")
filt_coef <- (filt-1)/2
X <- outer(-filt_coef:filt_coef, 0:filt_order, FUN="^")
s <- svd(X)
ypp = .Machine$double.eps^(2/3)
p <- ( s$d > max(ypp * s$d[1], 0) )
if (all(p)) {
mp <- s$v %*% (1/s$d * t(s$u))
} else if (any(p)) {
mp <- s$v[, p, drop=FALSE] %*% (1/s$d[p] * t(s$u[, p, drop=FALSE]))
} else {
mp <- matrix(0, nrow=ncol(X), ncol=nrow(X))
}
Y<-mp
x2 <- convolve(x, rev(Y[(der_order+1),]), type="o")
len<-length(x2)
x2 <- x2[(filt_coef+1):(len-filt_coef)]
final_val <- ((-1)^der_order * x2)
return(final_val)
}
|
prcomp_irlba <- function(x, n = 3, retx = TRUE, center = TRUE, scale. = FALSE, ...)
{
a <- names(as.list(match.call()))
ans <- list(scale=scale.)
if ("tol" %in% a)
warning("The `tol` truncation argument from `prcomp` is not supported by
`prcomp_irlba`. If specified, `tol` is passed to the `irlba` function to
control that algorithm's convergence tolerance. See `?prcomp_irlba` for help.")
if (is.data.frame(x)) x <- as.matrix(x)
args <- list(A=x, nv=n)
if (is.logical(center))
{
if (center) args$center <- colMeans(x)
} else args$center <- center
if (is.logical(scale.))
{
if (is.numeric(args$center))
{
f <- function(i) sqrt(sum((x[, i] - args$center[i]) ^ 2) / (nrow(x) - 1L))
scale. <- vapply(seq(ncol(x)), f, pi, USE.NAMES=FALSE)
if (ans$scale) ans$totalvar <- ncol(x)
else ans$totalvar <- sum(scale. ^ 2)
} else
{
if (ans$scale)
{
scale. <- apply(x, 2L, function(v) sqrt(sum(v ^ 2) / max(1, length(v) - 1L)))
f <- function(i) sqrt(sum((x[, i] / scale.[i]) ^ 2) / (nrow(x) - 1L))
ans$totalvar <- sum(vapply(seq(ncol(x)), f, pi, USE.NAMES=FALSE) ^ 2)
} else
{
f <- function(i) sum(x[, i] ^ 2) / (nrow(x) - 1L)
ans$totalvar <- sum(vapply(seq(ncol(x)), f, pi, USE.NAMES=FALSE))
}
}
if (ans$scale) args$scale <- scale.
} else
{
args$scale <- scale.
f <- function(i) sqrt(sum((x[, i] / scale.[i]) ^ 2) / (nrow(x) - 1L))
ans$totalvar <- sum(vapply(seq(ncol(x)), f, pi, USE.NAMES=FALSE))
}
if (!missing(...)) args <- c(args, list(...))
s <- do.call(irlba, args=args)
ans$sdev <- s$d / sqrt(max(1, nrow(x) - 1))
ans$rotation <- s$v
colnames(ans$rotation) <- paste("PC", seq(1, ncol(ans$rotation)), sep="")
ans$center <- args$center
if (retx)
{
ans <- c(ans, list(x = sweep(s$u, 2, s$d, FUN=`*`)))
colnames(ans$x) <- paste("PC", seq(1, ncol(ans$rotation)), sep="")
}
class(ans) <- c("irlba_prcomp", "prcomp")
ans
}
summary.irlba_prcomp <- function(object, ...)
{
chkDots(...)
vars <- object$sdev ^ 2
vars <- vars / object$totalvar
importance <- rbind("Standard deviation" = object$sdev,
"Proportion of Variance" = round(vars, 5),
"Cumulative Proportion" = round(cumsum(vars), 5))
k <- ncol(object$rotation)
colnames(importance) <- c(colnames(object$rotation), rep("", length(vars) - k))
object$importance <- importance
class(object) <- "summary.prcomp"
object
}
|
do.lda <- function(X, label, ndim=2){
if (!is.matrix(X)){
stop("* do.lda : 'X' should be a matrix.")
}
n = nrow(X)
p = ncol(X)
label = check_label(label, n)
ulabel = unique(label)
K = length(ulabel)
if (K==1){
stop("* do.lda : 'label' should have at least 2 unique labelings.")
}
if (K==n){
warning("* do.lda : given 'label' has all unique elements.")
}
if (any(is.na(label))||(any(is.infinite(label)))){
stop("* Supervised Learning : any element of 'label' as NA or Inf will simply be considered as a class, not missing entries.")
}
if (!check_ndim(ndim,p)){
stop("* do.lda : 'ndim' should be a positive integer in [1,
}
ndim = as.integer(ndim)
if (ndim>=K){
warning("* do.lda : by the nature of LDA, target dimension 'ndim' needs to be adjusted to match maximally permissible subspace.")
}
datlist = list()
for (i in 1:length(ulabel)){
datlist[[i]] = X[which(label==ulabel[i]),]
}
scattermat <- function(x){
return(cov(x)*(nrow(x)-1))
}
matE = array(0,c(p,p))
for (i in 1:length(ulabel)){
matE = matE + cov(datlist[[i]])*(nrow(datlist[[i]])-1)
}
matH = array(0,c(p,p))
meanlist = lapply(datlist, colMeans)
meantott = colMeans(X)
for (i in 1:length(ulabel)){
meandiff = as.vector(meanlist[[i]]-meantott)
matH = matH + nrow(datlist[[i]])*outer(meandiff,meandiff)
}
W = aux.traceratio(matH, matE, ndim, 1e-6, 123)
result = list()
result$Y = X%*%W
result$projection = W
result$algorithm = "linear:LDA"
return(structure(result, class="Rdimtools"))
}
lda_outer <- function(X){
p = ncol(X)
output = array(0,c(p,p))
for (i in 1:nrow(X)){
output = output + outer(X[i,],X[i,])
}
return(output)
}
|
library(quickmatch)
context("reg_estimator")
match_count <- function(x) {
out_count <- rep(NA, length(x))
for (i in unique(x)) out_count[x == i] <- sum(x == i, na.rm = TRUE)
out_count
}
raw_data <- c(
-0.4872, 0.7451, -0.5165, 1.9151, -1.0990, 0.1415, -1.6650, -0.7701, 0.8870, -1.7677, 0.4690, -0.7884, -1.5393, -1.7362,
-0.2024, 1.0733, -1.3620, -0.4470, 0.8180, -0.0763, 0.9161, 0.1498, -0.4148, -0.3479, 0.0125, 0.4151, -0.7968, -1.1322,
0.3485, 1.4876, 0.0120, -0.6994, 1.3863, 0.8316, 1.5635, -0.8186, -1.1553, 0.9905, 0.4355, -0.3541, 0.1017, 1.6381, -1.0360,
-0.3388, -0.3153, -0.8831, 1.5329, 0.8185, 0.6928, 0.3537, 1.3176, 1.0420, 0.9509, 0.0724, 1.1712, 1.4547, -1.2928, -0.7068,
0.9908, 0.9348, 0.7290, -1.1964, -0.5767, 1.4289, 0.1575, 0.8106, 1.8869, -2.1967, 1.1377, -0.4083, -0.1881, 1.0856, 0.3577,
1.5250, 0.2335, -1.0602, 0.1323, -0.1126, 0.3117, 0.7388, -0.2705, 0.6851, 0.1205, 0.9823, 0.9160, -1.3916, -0.0303, -2.6696,
0.4105, -0.5251, 0.2119, 0.5794, 0.8496, 1.3887, 0.4537, 0.2799, -0.6344, 0.1534, 0.3601, 1.7681, 0.0953, 3.1733, -0.6397,
0.6969, 1.2124, 0.0444, 0.2699, 0.5722, 1.4017, -2.0091, -0.2097, 1.1762, -0.8968, 0.4630, -1.0038, 0.9264, 0.0769, 0.6999,
-0.7871, -0.1970, 1.6685, 2.2448, 1.8787, -0.0526, -0.3524, 0.1996, 0.4861, -2.3330, 1.7631, -0.2454, 1.9811, 1.7298, -1.3136,
0.4381, -1.7302, -0.5488, -0.4629, 1.0734, 0.4401, 1.9076, 0.7295, 0.8086, -1.1172, -1.0829, 0.2377, 0.5529, 0.8747, -0.3075,
0.3003, 0.0108, -0.9400, -2.3602, -0.6517, 0.3543, 1.1219, 1.2237, 1.2876, -0.4258, -0.5316, 1.5097, -0.9258, -0.2263, -1.6545,
-0.5118, 0.8067, -0.4161, -1.3016, 0.6354, 0.5915, -1.3470, -0.8744, 0.1387, 0.6643, -0.2910, -0.3412, 0.1793, 0.7138, 0.2433,
0.6125, -0.2464, 0.0057, 0.6646, 0.0736, 0.6896, -0.7782, -1.8728, 0.8456, 0.9308, -0.4463, -1.8400, -0.5621, 1.5114, -1.0632,
0.1462, 1.9489, 0.3121, -0.6328, 0.0918, 0.2918, 0.4331, 1.2829, 0.3552, 0.4426, 0.2720, 2.3246, 0.7779, 0.9825, 1.7908, -0.6747,
1.0587, 0.2962, 1.2923, -1.1576, 0.4971, -2.0785, 0.8715, 2.2522, -0.4881, 0.2309, -0.0164, -1.4632, 1.7606, -0.3353, -0.1725,
-0.4967, 0.1605, 1.3567, 0.4294, 1.8146, -0.5629, 0.0107, 1.0025, -0.9478, -0.1239, -0.9951, 1.4195, 0.4877, -1.8599, 1.7040,
0.0246, 1.1572, -0.4044, 0.2038, -0.6518, 0.5821, 0.3766, -0.7009, -1.0738, 0.9604, 0.1802, 0.5913, 0.0365, 0.4543, -1.0197,
-0.7051, -0.6344, -1.0327, -0.9951, 0.6972, 0.8006, 0.8440, -1.3340, -0.4797, -0.2743, -1.0535, -0.0091, -0.4318, 0.3279,
-0.1839, -0.5958, 1.5160, -0.0422, 0.3614, -0.8697, -1.1830, -1.1213, 1.5815, 1.6135, -0.3470, 0.0419, -0.4221, -0.6461,
-1.0033, -0.0900, -0.5785, 1.7861, -0.1090, -1.0358, 0.1087, -0.0332, -0.3088, -0.4634, -0.0462, 0.6296, 1.7265, 0.4197, -0.7898,
-1.7844, 1.9471, 0.7274, -0.8677, -0.2795, 0.2455, -0.9393, 1.1793, -0.3175, -0.8311, -0.6760, 0.2970, -0.9475, -0.2148, 0.5637,
0.4079, 0.0066, 0.9437, -0.0163, -1.0125, 0.2154, -0.2482, -1.8247, -1.0617, 0.7498, 0.4034, 0.5635, -0.4876, 1.9992, 0.9648,
-0.8537, 0.0063, -1.1641, -1.6558, 0.8655, 0.9480, -0.5356, 0.2981, 0.5342, -1.0418, 1.0282, -0.2379, 0.1199, 1.4087, 0.5974,
1.0881, -0.6855, 2.0377, -0.5227, -1.0928, 0.6629, 1.2590, 1.7140, 0.3889, -1.1810, 0.5250, 1.0377, -2.8392, 0.2053, -0.2867,
0.0450, -1.3993, 0.4165, 2.9334, -0.0015, 0.5121, 0.1672, -0.5330, -0.1301, -0.6468, 0.4862, 1.4244, 0.3494, -0.7650, -3.0832,
-0.2569, -0.7141, -0.9665, -1.2767, 0.6289, -0.6010, -0.2776, -1.5355, -0.5862, -0.6076, -0.3462, -1.6480, -0.4506, -0.0737,
2.1826, 0.3112, -1.4866, 0.3100, -0.1294, 0.0274, 1.0829, -0.0825, -1.6882, 0.8567, -0.2415, 0.1970, -1.1719, 0.8883, -0.3625,
0.5567, 0.3272, -0.7696, -0.6935, 0.2545, -0.4362, -1.0174, 0.9380, 0.8912, 0.6014, -0.4535, 0.8919, 0.3829, -0.2889, -1.6220,
-0.3766, -0.0062, 1.2260, -1.3599, -0.9028, 0.8031, 0.4731, 1.1029, -0.4523, -1.4486, -0.5979, 0.3783, 0.0164, 0.8578, -1.5953,
-0.8259, -1.6055, 0.4267, -1.4018, 0.0276, 1.3672, 0.0181, 1.1177, -1.7308, 1.0657, -0.1088, 2.4203, -0.5355, -2.0901, -1.5322,
-1.7706, 0.2952, 1.5633, 0.3468, -0.7159, 0.7950, 0.5505, -0.5370, -0.4594, 0.1716, -0.8158, 1.3633, -0.9603, 1.1322, -0.4228,
-0.3554, 1.2230, 0.2992, 1.7149, -0.0627, 0.2368, -0.1479, -2.0702, -1.8919, 0.6002, -0.3636, -1.5506, 0.2206, -0.8984, 0.9310,
1.5714, 1.0776, 0.7620, -1.2547, 2.2364, -0.5050, 1.1581, 0.9402, -0.2105, 0.5425, -1.7107, 0.9627, 0.2343, 1.0857, 0.4265, 0.9014,
-2.2587, -0.4009, 0.1736, 0.5412, -0.6627, 1.0283, -0.3611, -0.0952, 1.1076, 0.1142, -0.8730, -0.4041, -0.1622, 0.6180, -1.4230,
0.7598, -1.1315, -1.4547, 0.9569, -1.1144, -0.8974, -1.8576, 0.3025, -0.2148, 0.0795, 1.7697, 0.5964, 1.3837, -0.3508, -0.4489,
-1.0038, 0.7689, -0.9172, -0.2032, 0.1305, 0.7555, -1.1910, 0.6642, 1.8022, -0.2778, 0.2482, -2.1934, 0.9776, -0.5258, 1.4201,
0.9297, 0.7087, 1.1819, -0.8285, 0.5929, -1.6667, 1.4040, 0.6843, 0.1170, -2.5217, 0.5207, -0.5059, -1.8744, 0.8313, -0.0058,
-1.4890, 1.7169, -0.9529, 0.1913, 1.5248, 0.9072, 0.6951, 0.9039, 1.1450, -0.7990, -0.8951, 0.0930, 1.8007, -0.8398, 0.1976,
0.0284, 1.6596, -0.2373, 1.6222, 0.5146, 0.5970, -0.9764, -1.1838, 0.9578, -0.1807, 0.0804, 0.1399, 1.5009, 1.1879, 0.4374, -0.5793,
0.5963, -1.2124, 1.2813, -0.7977, -0.2510, -0.4962, -0.5805, 0.5271, -0.1430, -0.4335, 0.3752, 0.4296, 0.9512, 2.5223, 0.0944,
0.4732, 0.8319, 0.1064, -1.5534, 0.5204, -0.3217, 0.6548, 1.8891, 1.8319, -0.5004, -0.5851, -0.4657, 1.5465, -1.3594, 1.0047,
-0.4412, -0.0397, 0.2357, 2.0599, 1.0330, -0.3042, 1.4978, 1.4697, 0.0848, 0.5442, -0.3818, 0.0743, 1.9379, 1.3631, 0.2789, 0.3412,
-0.9296, 0.6453, -0.4919, 1.4866, -0.2201, 1.9315, 0.0905, -1.8105, 0.8638, -0.7237, -0.2104, -0.4444, 0.7172, -0.3825, 0.2067,
-0.0333, -1.1909, 1.1056, 0.9053, -0.6597, -0.6914, 0.4585, -0.7110, 0.0690, 0.5465, 1.9854, 0.8117, 1.0793, 1.2360, -1.9689,
-0.6541, -0.2067, -0.9436, -0.2843, 0.3925, -0.5058, 0.2156, -0.2359, 0.3010, 2.1301, 1.5143, 0.0042, 0.3615, -0.6853, 0.8183,
-0.5962, -0.5115, -0.0717, -0.3841, -0.5058, -1.0159, 0.8669, 0.0163, -0.3912, 0.9714, 2.1844, 0.9561, 1.2363, -1.2320, 1.0044,
-2.8297, -0.5989, 0.9072, -0.4030, -1.9363, -0.7543, 1.0802, 0.2087, 0.0241, 1.7565, -0.8564, 0.2633, 1.1214, 1.1939, -0.1404,
-0.5400, -0.5482, -0.6363, 1.5533, -1.0036, 0.0684, -0.7229, -0.3722, 2.0825, 0.1669, 1.1343, 0.8718, -1.0742, 0.6947, 0.6584,
-1.5386, -0.4617, -0.4007, -0.4141, -0.9637, 1.2189, 0.0330, 0.8760, -0.7897, -0.2739, 0.1020, -0.0052, -1.2279, 0.7426, -0.2921,
-0.1473, 0.9460, 2.2570, -0.9717, 1.4505, 1.0058, 2.1400, 0.4182, -1.3513, -0.0570, -0.3588, 0.1365, 0.6475, -0.6026, 0.4890,
-1.7305, 0.4392, -1.6688, -0.4057, 0.2632, -1.7420, -0.1697, 0.6454, 1.6009, 0.2703, -0.2497, -0.5316, 0.8671, 0.6408, 0.9662,
1.7522, -0.4981, -0.6324, 0.7571, -0.4545, -1.5518, 0.7337, 0.4030, 0.1092, -0.2047, -0.7430, 1.1214, 0.7836, -0.3992, -0.3865,
-0.9020, -0.9157, -0.0421, 0.3431, -0.8068, 0.1751, 0.5083, -0.5680, 0.1369, -0.4947, 2.2623, 1.2339, 0.3881, -0.2316, -1.6752,
0.2572, 1.0593, -0.4890, -0.0756, -0.5038, -1.8795, -1.5513, -1.0853, 1.0083, 1.1964, -2.1472, 0.6647, 0.2958, 0.0789, 0.5603,
2.5896, -0.5381, -0.7058, 0.1116, 0.1473, -0.5630, 0.6310, -0.0618, 0.4437, 0.7692, -2.1426, -2.2755, -0.1039, -0.1375, -0.2636,
-0.0682, 0.4290, 1.5298, -0.4661, 0.2780, -0.3979, 0.9276, -0.4869, 1.5589, 0.7911, 0.0278, 0.1342, 0.6081, -1.2963, 0.6305,
-0.5811, -1.3431, -0.3408, 2.7015, -0.0249, -1.5477, -0.7342, -0.5546, 0.4840, -0.1092, -0.3016, -0.4935, -0.8670, -1.3928, 0.3843,
-0.1520, -0.6043, -1.5804, -0.2794, -0.0220, -0.3274, 0.3435, 0.4598, -0.0506, -0.0693, -0.5182, -0.7082, -0.2513, 0.5971, -0.0448,
-1.1931, 0.2547, 0.5547, 0.7275, 0.0790, 0.7290, -1.7580, 1.4076, 0.0707, -1.3745, -0.9425, -1.7886, 1.0114, 0.6533, -2.4790,
0.7734, -1.2740, 1.4678, 1.0326, 2.4520, -0.3818, 0.4637, 0.0647, 0.5835, -0.6451, 0.1827, 0.3267, 2.9147, 0.8831, 0.3677, 0.0840,
1.8727, -1.9208, 0.5406, -0.9817, 0.4599, 0.6025, -0.0785, 0.2673, 0.3753, -2.0838, -0.7829, 1.3637, 1.2702, 0.6830, -0.2844,
1.1863, -0.1296, -0.7212, 1.1061, 0.5191, -2.0950, -1.1772, 1.4060, -0.5879, -0.2722, 0.7108, -0.3690, 0.0525, 1.3578, -1.4684,
0.0200, -1.5456, 0.7970, -0.4809, -0.7506, -0.5057, -1.5580, 1.0935, -1.0784, -1.0562, -0.1146, -0.9110, 0.8766, -0.7964, -2.4560,
0.1778, 1.4359, 0.2717, -0.5767, 0.2234, 1.2251, 1.5370, -0.5174, 1.1125, 0.1106, 0.6372, 0.1512, 0.3230, 2.2387, -0.4424, -1.0800,
1.3210, -1.2190, -0.6978, 0.2300, 0.3607, 1.8892, 0.5572, 0.9886, 1.3938, 0.3778, 0.9841, -0.4031, -0.9848, 0.2440, -1.3726, -0.9412,
0.2147, -0.4574, 0.5361, 1.0282, 0.9216, 0.4758, 0.3440, 1.2460, -0.3306, -0.3788, 0.0800, 1.2618, 0.7217, -0.5614, 0.1019, 0.0530,
-0.2299, 0.8542, -0.4069, 0.5273, 0.1136, -1.4586, 1.5515)
outcomes <- c(0.0205, -0.3570, -0.1800, 1.6027, 0.6040, 0.0446, 1.1410, 0.6459, 0.2176, 1.0053, 0.8606, -1.6118, 0.5874, 1.1100,
-1.3736, -0.0285, 0.3507, 0.7171, -1.3828, 0.8234, -0.7631, -0.4639, -0.4376, 0.0730, 0.1047, -0.5083, -0.2196, 0.5361, -1.5352,
-0.8881, -0.8442, 0.0563, -1.5486, -0.5264, -0.8658, 1.5356, 0.2647, -0.0963, 0.4131, -1.1494, -1.9345, -0.5645, 1.1416, 0.0773,
-0.5720, 0.5793, -0.3981, -0.9894, -1.2676, -0.6354, -0.1311, -0.1716, 0.7746, 1.6090, 2.8755, -0.2764, 0.7829, 0.4025, -0.2133,
0.2556, -0.2961, 0.1277, -1.1842, 0.5236, 1.2570, -0.3152, 0.2932, -1.0783, -0.3862, -0.8232, -1.1835, -1.3552, -0.0789, -0.0066,
0.3635, 0.5077, 1.2753, -0.8967, 0.4159, -0.7981, 0.2287, -0.4356, -0.7993, -0.2827, -0.7846, 1.2104, 1.0357, -1.5568, 2.3634,
-0.1235, -0.6127, -1.2388, 1.3979, -0.2042, 0.5417, 1.1585, 0.1019, -0.4110, 1.7379, 1.0779, 0.4450, 3.2147, 1.0197, 1.3007,
-0.1291, 0.9400, 0.4611, 1.3303, 0.1158, 0.1236, 1.6459, -0.3607, 0.5939, -0.3914, -0.0605, -1.0023, 1.6778, 0.6189, -0.9104,
-1.5664, -0.8702, 0.7727, -1.0583, -0.7396, 0.5931, -0.6804, 2.3084, -0.1429, 2.4170, 1.5413, 0.8579, -0.2773, 0.5879, 0.7498,
0.1557, 0.3880, 0.4225, -1.1402, 1.7665, 0.4245, -0.3918, 0.4971, 0.7368, -0.9356, 0.4586, 1.7515, 1.2829, 0.2030, -0.6820,
0.0969, -1.0878, 0.0772, 2.5644, -0.3377, 1.1355, -0.6275, -0.3647, 0.1621, -0.1468, 1.6987, -0.8734, -0.9340, 0.5531, 1.4509,
-0.3212, -1.2277, 0.6314, 0.9667, -1.6311, 0.3286, -1.9934, -1.6888, 0.3473, 0.6372, 0.3762, -0.0419, -0.7407, -1.2121, 0.7571,
-0.5526, 0.1421, 0.1362, -0.2806, 0.0616, -1.2681, -0.4562, -0.7822, 1.4473, -0.9530, 0.4526, -1.1236, 1.0511, -0.8775, 0.1029,
-1.4251, -1.2171, 0.3472, -0.2190, 0.0336, 0.1680, 0.1281, -1.9779, 0.1375, 1.8399, -0.0493, 0.6907, 0.7541, 0.5287, -0.8845,
1.4811, 0.3286, 0.8972, 0.5654, 0.8593, -0.1344, 0.8320, -0.8736, -0.7748, 0.6392, -1.1989, 0.3728, -0.4211, -0.3649, -0.4534,
-0.0137, 0.3928, 1.2608, 1.2502, 0.3193, 1.1112, -1.8545, 0.5773, 0.2744, 0.0725, 0.2167, -0.7172, -0.7628, 0.8344, -0.2046,
1.0611, 1.2770, -1.6743, 1.3876, -0.4273, 0.4789, -0.8904, -2.2173, 0.6997, -1.8759, 0.7042, -0.2366, -0.8236, -0.5462, 1.8462,
0.5542, -0.9172, -2.1855, -0.6027, -2.0782, 0.5249, 1.9438, 0.4261, -0.2575, -2.7734, -0.7753, 0.0163, -0.8262, -1.6110, -0.1041,
-0.7182, 0.3477, 1.3551, -0.2285, -0.9560, -0.8441, 1.2757, -0.9876, 1.0534, -0.9341, -0.3950, -2.2642, -0.4673, -1.2123, -1.0671,
1.0994, -1.0178, 1.1849, 1.9378, -0.1527, -0.8706, 0.2871, 0.9813, -0.2128, 1.7363, -0.2256, 1.3844, -0.5083, 0.0575, -0.2202,
-2.0043, 0.3946, 0.8989, 0.5002, 0.9511, 1.1091, 0.7113, 1.3659, -0.0582, 1.6949, -0.7345, -0.6111, -0.5422, -2.6116, -0.9190,
0.4477, 1.2454, 1.2049, -0.2520, 0.5938, 0.4758, 0.1826, -1.1340, 0.4525, 0.1237, -0.7409, -0.8201, 0.1525, 0.2695, -1.5823,
-1.2049, 0.9168, 0.0510, -0.3695, -0.4639, -0.4096, 0.9551, -0.6061, -0.7474, 0.8266, 2.0093, 0.7526, 1.4513, -0.3172, 0.0437,
1.9979, 1.0427, -0.3827, -0.3352, -0.7851, 0.7902, -0.8383, -0.1463, 1.7544, -0.6223, 0.5491, 1.0549, -1.2745, 0.6006, 1.0724,
1.7022, -1.4415, 1.3337, 1.4286, 0.1131, 0.6909, -0.3527, 1.0276, -1.7789, -2.3209, 0.4760, 0.2717, -1.4556, -0.2188, -0.7969,
1.1241, 1.6584, 0.1295, -0.0227, 0.3267, -1.7511, 0.1707, -0.0164, -0.6512, 1.3965, 0.1340, 0.3256, -0.5760, 0.0319, 0.3296,
-0.8830, 0.5726, -1.5751, -0.7329, -0.7542, -0.7859, -0.3914, -0.2288, 1.5780, -1.7739, 0.0440, -0.0925, -1.8832, 1.3091, 0.2592,
1.8375, -1.5061, 1.4029, -1.0109, 1.1734, -0.6569, -0.7112, -2.3794, 0.7054, 1.5654, 0.8891, 0.0091, -0.6947, 1.4746, 0.7423,
-1.7094, -0.3652, -0.8040, -0.0838, -0.0832, -0.7429, -0.1221, -0.2304, 0.3326, -0.2007, 0.7618, 0.6339, 1.0916, 0.2606, 1.9462,
-0.0962, -0.0238, 0.3406, -0.4235, 1.5965, -1.3173, -0.5833, 0.9931, -0.6504, -1.6696, -0.1766, -0.0618, 0.9042, -1.8983, -0.7147,
0.0607, -0.3663, -0.3427, 0.0150, 2.0077, -1.5831, -1.1572, -2.3661, 0.5794, 0.3421, -1.2125, 2.0121, -0.2505, 1.0036, 2.1437,
-1.5260, 0.6540, 0.5038, -0.1488, 0.3597, 0.3622, 0.9767, -0.3947, -0.5022, 0.5277, -0.7256, -1.8513, -2.3371, 1.2231, -0.6757,
0.0961, -0.5849, -0.2429, 0.5242, 0.7977, -0.2923, 0.4917, -0.6212, -2.3871, -2.0155, -1.1342, 0.3785, -0.2179, -0.0241, -0.1828,
0.8068, -0.0506, -0.8762, -1.3112, 0.6008, 1.5089)
treatmentsUse <- c("B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "B", "B", "A", "B", "A", "A", "B", "A", "B", "A", "A", "A", "A", "B", "A",
"B", "A", "B", "A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "A", "A", "A", "A", "B", "B", "A", "A", "A", "B", "A", "A", "B",
"B", "B", "B", "B", "A", "A", "A", "B", "A", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A", "A", "B", "B", "B", "A", "A", "A",
"B", "B", "A", "B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "B", "B", "B", "B", "A", "B", "B", "A", "A", "B", "B", "B", "B",
"B", "A", "A", "B", "B", "A", "A", "B", "B", "B", "A", "B", "A", "B", "A", "B", "B", "B", "B", "A", "B", "A", "B", "B", "B", "B",
"A", "B", "A", "B", "A", "A", "A", "A", "A", "A", "B", "A", "A", "A", "A", "B", "B", "A", "B", "A", "B", "B", "B", "A", "A", "B",
"A", "B", "A", "A", "B", "A", "A", "A", "A", "A", "B", "B", "A", "A", "B", "B", "A", "B", "B", "A", "B", "B", "B", "A", "A", "B",
"A", "A", "A", "B", "A", "A", "A", "A", "B", "A", "A", "B", "B", "B", "B", "B", "A", "A", "B", "B", "A", "A", "A", "A", "B", "B",
"A", "A", "A", "A", "B", "B", "B", "B", "A", "B", "A", "A", "B", "A", "A", "A", "A", "A", "A", "B", "B", "A", "A", "B", "A", "B",
"A", "A", "A", "A", "B", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "A", "B", "A", "A", "B", "A", "B",
"B", "B", "B", "B", "B", "B", "A", "B", "B", "B", "B", "A", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "A", "A", "B", "A", "B", "A", "B", "B", "B", "A", "A", "A", "A", "B", "A", "B",
"B", "A", "A", "A", "A", "A", "A", "B", "B", "A", "A", "B", "A", "A", "B", "B", "A", "B", "B", "B", "A", "B", "A", "A", "A", "B",
"B", "A", "A", "B", "B", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B", "A", "B", "A", "B", "B", "B", "B", "A", "B", "A", "B",
"B", "A", "A", "A", "B", "B", "B", "A", "A", "B", "A", "A", "A", "B", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A",
"A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "A", "B", "A", "A", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B",
"A", "A", "A", "A", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A", "A", "B", "A", "A", "A", "A", "B", "A", "B", "A",
"A", "B", "B", "A", "B", "A", "A", "A", "B", "B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "A", "B", "B", "A", "A", "B", "B",
"B", "A", "B", "B", "B", "B", "A", "A", "A", "A", "A", "B", "B", "A", "B", "B", "A", "B", "A", "B", "A", "A", "A", "A", "B", "B",
"A", "B", "B", "A", "A", "B", "A")
treatmentsUse2 <- c("B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "B", "B", "A", "B", "A", "A", "B", "A", "B", "A", "A", "A", "A", "B", "A",
"A", "C", "A", "A", "C", "A", "A", "A", "A", "A", "C", "C", "A", "A", "C", "C", "A", "C", "C", "A", "C", "C", "C", "A", "A", "C",
"B", "A", "B", "A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "A", "A", "A", "A", "B", "B", "A", "A", "A", "B", "A", "A", "B",
"C", "C", "C", "C", "A", "A", "A", "C", "A", "C", "C", "A", "A", "A", "C", "C", "C", "C", "A", "A", "C", "C", "C", "A", "A", "A",
"A", "A", "A", "A", "C", "C", "C", "C", "A", "C", "A", "A", "C", "A", "A", "A", "A", "A", "A", "C", "C", "A", "A", "C", "A", "C",
"C", "C", "C", "C", "C", "C", "A", "C", "C", "C", "C", "A", "C", "A", "A", "C", "C", "C", "A", "A", "A", "C", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "A", "A", "B", "A", "B", "A", "B", "B", "B", "A", "A", "A", "A", "B", "A", "B",
"A", "A", "A", "C", "A", "A", "A", "A", "C", "A", "A", "C", "C", "C", "C", "C", "A", "A", "C", "C", "A", "A", "A", "A", "C", "C",
"B", "A", "A", "A", "A", "A", "A", "B", "B", "A", "A", "B", "A", "A", "B", "B", "A", "B", "B", "B", "A", "B", "A", "A", "A", "B",
"B", "A", "A", "B", "B", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B", "A", "B", "A", "B", "B", "B", "B", "A", "B", "A", "B",
"C", "A", "A", "C", "C", "A", "A", "C", "C", "C", "A", "C", "A", "C", "A", "C", "C", "C", "C", "A", "C", "A", "C", "C", "C", "C",
"A", "C", "A", "C", "A", "A", "A", "A", "A", "A", "C", "A", "A", "A", "A", "C", "C", "A", "C", "A", "C", "C", "C", "A", "A", "C",
"B", "A", "A", "A", "B", "B", "B", "A", "A", "B", "A", "A", "A", "B", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A",
"A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "A", "B", "A", "A", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B",
"A", "A", "A", "A", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A", "A", "B", "A", "A", "A", "A", "B", "A", "B", "A",
"A", "A", "A", "A", "C", "A", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "A", "C", "A", "A", "C", "A", "C",
"A", "B", "B", "A", "B", "A", "A", "A", "B", "B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "A", "B", "B", "A", "A", "B", "B",
"C", "C", "A", "C", "A", "A", "C", "C", "C", "C", "A", "A", "C", "C", "C", "C", "C", "A", "C", "C", "A", "A", "C", "C", "C", "C",
"B", "A", "B", "B", "B", "B", "A", "A", "A", "A", "A", "B", "B", "A", "B", "B", "A", "B", "A", "B", "A", "A", "A", "A", "B", "B",
"A", "B", "B", "A", "A", "B", "A")
treatmentsUse3 <- c("B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "B", "B", "A", "B", "D", "A", "B", "A", "B", "A", "A", "A", "A", "B", "A",
"A", "C", "A", "A", "C", "A", "A", "A", "A", "A", "C", "C", "A", "A", "C", "C", "A", "C", "C", "A", "C", "C", "C", "A", "A", "C",
"B", "A", "B", "A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "A", "A", "A", "A", "B", "B", "A", "A", "A", "B", "A", "A", "B",
"C", "C", "C", "C", "A", "A", "A", "C", "A", "C", "C", "A", "A", "A", "C", "C", "C", "C", "A", "A", "C", "C", "C", "A", "A", "A",
"A", "A", "A", "A", "C", "C", "C", "C", "A", "C", "A", "A", "C", "A", "A", "A", "A", "A", "A", "C", "C", "A", "A", "C", "A", "C",
"C", "C", "C", "C", "C", "C", "A", "C", "C", "C", "C", "A", "C", "A", "A", "C", "C", "C", "A", "A", "A", "C", "A", "A", "A", "A",
"D", "B", "B", "B", "B", "B", "B", "B", "B", "B", "A", "A", "B", "A", "B", "A", "B", "B", "B", "A", "A", "A", "A", "B", "A", "B",
"A", "A", "A", "C", "A", "D", "A", "A", "C", "A", "A", "C", "C", "C", "C", "C", "A", "A", "C", "C", "A", "A", "A", "A", "C", "C",
"B", "A", "A", "A", "A", "A", "A", "D", "B", "A", "A", "B", "A", "A", "B", "B", "A", "B", "B", "B", "A", "B", "A", "A", "A", "B",
"B", "A", "A", "B", "B", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B", "A", "B", "A", "B", "B", "B", "B", "A", "B", "A", "B",
"C", "A", "A", "C", "C", "A", "A", "C", "C", "C", "A", "C", "A", "C", "A", "C", "C", "C", "C", "A", "C", "A", "C", "C", "C", "C",
"A", "C", "A", "C", "A", "A", "A", "A", "A", "A", "C", "A", "A", "A", "A", "C", "C", "A", "C", "A", "C", "C", "C", "A", "A", "C",
"B", "A", "A", "A", "B", "B", "B", "A", "A", "B", "A", "A", "A", "B", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "A",
"A", "B", "B", "A", "A", "A", "A", "A", "B", "A", "B", "A", "A", "B", "A", "A", "B", "A", "A", "B", "B", "B", "A", "A", "A", "B",
"A", "A", "A", "A", "B", "B", "B", "B", "A", "A", "A", "B", "B", "B", "B", "D", "A", "B", "A", "A", "A", "A", "B", "A", "B", "A",
"A", "A", "D", "A", "C", "A", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "A", "C", "A", "A", "C", "A", "C",
"A", "B", "B", "A", "B", "A", "A", "A", "B", "B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "A", "B", "B", "A", "A", "B", "B",
"C", "C", "A", "C", "A", "A", "C", "C", "C", "C", "A", "A", "C", "C", "C", "C", "C", "A", "C", "C", "A", "A", "C", "C", "C", "C",
"B", "A", "B", "B", "B", "B", "A", "A", "A", "A", "A", "B", "B", "A", "B", "B", "A", "B", "A", "B", "A", "A", "A", "A", "B", "B",
"A", "B", "B", "A", "A", "B", "A")
df <- data.frame(y = outcomes,
x1 = raw_data[1:500],
x2 = raw_data[501:1000],
treat1 = treatmentsUse,
treat2 = treatmentsUse2,
treat3 = treatmentsUse3)
df1 <- df[c("y", "x1", "x2", "treat1")]
matching1 <- quickmatch(distances(df1[c("x1", "x2")]), df1$treat1)
df1$tot_count <- match_count(as.integer(matching1))
df1$unit_weight <- NA
df1$unit_weight[df1$treat1 == "A"] <- match_count(as.integer(matching1)[df1$treat1 == "A"])
df1$unit_weight[df1$treat1 == "B"] <- match_count(as.integer(matching1)[df1$treat1 == "B"])
df1$unit_weight <- df1$tot_count / (df1$unit_weight * 500)
lm_res <- stats::lm(y ~ 0 + treat1, data = df1, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2],
lm_res$coefficients[2] - lm_res$coefficients[1], 0),
ncol = 2, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0),
ncol = 2, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B"), c("A", "B"))
dimnames(control_variances) <- list(c("A", "B"), c("A", "B"))
test_that("`lm_match` vanilla", {
expect_silent(package_result <- lm_match(df1$y, df1$treat1, matching1))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat1 + x1 + x2, data = df1, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2],
lm_res$coefficients[2] - lm_res$coefficients[1], 0),
ncol = 2, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0),
ncol = 2, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B"), c("A", "B"))
dimnames(control_variances) <- list(c("A", "B"), c("A", "B"))
test_that("`lm_match` covariates", {
expect_silent(package_result <- lm_match(df1$y, df1$treat1, matching1, df1[c("x1", "x2")]))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
df1 <- df[c("y", "x1", "x2", "treat1")]
matching1 <- quickmatch(distances(df1[c("x1", "x2")]), df1$treat1)
target <- df1$treat1 == "B"
df1$tot_count <- NA
tmp_int_match <- as.integer(matching1)
for (i in unique(tmp_int_match)) {
df1$tot_count[tmp_int_match == i] <- sum(target[tmp_int_match == i])
}
df1$unit_weight <- NA
df1$unit_weight[df1$treat1 == "A"] <- match_count(as.integer(matching1)[df1$treat1 == "A"])
df1$unit_weight[df1$treat1 == "B"] <- match_count(as.integer(matching1)[df1$treat1 == "B"])
df1$unit_weight <- df1$tot_count / (df1$unit_weight * sum(target))
lm_res <- stats::lm(y ~ 0 + treat1, data = df1, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2],
lm_res$coefficients[2] - lm_res$coefficients[1], 0),
ncol = 2, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0),
ncol = 2, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B"), c("A", "B"))
dimnames(control_variances) <- list(c("A", "B"), c("A", "B"))
test_that("`lm_match` target", {
expect_silent(package_result1 <- lm_match(df1$y, df1$treat1, matching1, target = "B"))
expect_silent(package_result2 <- lm_match(df1$y, df1$treat1, matching1, target = target))
expect_silent(package_result3 <- lm_match(df1$y, df1$treat1, matching1, target = which(target)))
expect_silent(package_result4 <- lm_match(df1$y, df1$treat1, matching1, target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat1 + x1 + x2, data = df1, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2],
lm_res$coefficients[2] - lm_res$coefficients[1], 0),
ncol = 2, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0),
ncol = 2, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B"), c("A", "B"))
dimnames(control_variances) <- list(c("A", "B"), c("A", "B"))
test_that("`lm_match` target + covariates", {
expect_silent(package_result1 <- lm_match(df1$y, df1$treat1, matching1, df1[c("x1", "x2")], target = "B"))
expect_silent(package_result2 <- lm_match(df1$y, df1$treat1, matching1, df1[c("x1", "x2")], target = target))
expect_silent(package_result3 <- lm_match(df1$y, df1$treat1, matching1, df1[c("x1", "x2")], target = which(target)))
expect_silent(package_result4 <- lm_match(df1$y, df1$treat1, matching1, df1[c("x1", "x2")], target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat2")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat2)
df2$tot_count <- match_count(as.integer(matching2))
df2$unit_weight <- NA
df2$unit_weight[df2$treat2 == "A"] <- match_count(as.integer(matching2)[df2$treat2 == "A"])
df2$unit_weight[df2$treat2 == "B"] <- match_count(as.integer(matching2)[df2$treat2 == "B"])
df2$unit_weight[df2$treat2 == "C"] <- match_count(as.integer(matching2)[df2$treat2 == "C"])
df2$unit_weight <- df2$tot_count / (df2$unit_weight * 500)
lm_res <- stats::lm(y ~ 0 + treat2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments", {
expect_silent(package_result <- lm_match(df2$y, df2$treat2, matching2))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat2 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + covariates", {
expect_silent(package_result <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")]))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat2")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat2)
target <- df2$treat2 == "B"
df2$tot_count <- NA
tmp_int_match <- as.integer(matching2)
for (i in unique(tmp_int_match)) {
df2$tot_count[tmp_int_match == i] <- sum(target[tmp_int_match == i])
}
df2$unit_weight <- NA
df2$unit_weight[df2$treat2 == "A"] <- match_count(as.integer(matching2)[df2$treat2 == "A"])
df2$unit_weight[df2$treat2 == "B"] <- match_count(as.integer(matching2)[df2$treat2 == "B"])
df2$unit_weight[df2$treat2 == "C"] <- match_count(as.integer(matching2)[df2$treat2 == "C"])
df2$unit_weight <- df2$tot_count / (df2$unit_weight * sum(target))
lm_res <- stats::lm(y ~ 0 + treat2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat2 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + covariates + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat2")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat2, target = "B")
target <- df2$treat2 == "B"
df2$tot_count <- NA
tmp_int_match <- as.integer(matching2)
for (i in unique(tmp_int_match)) {
df2$tot_count[tmp_int_match == i] <- sum(target[tmp_int_match == i], na.rm = TRUE)
}
df2$unit_weight <- NA
df2$unit_weight[df2$treat2 == "A"] <- match_count(as.integer(matching2)[df2$treat2 == "A"])
df2$unit_weight[df2$treat2 == "B"] <- match_count(as.integer(matching2)[df2$treat2 == "B"])
df2$unit_weight[df2$treat2 == "C"] <- match_count(as.integer(matching2)[df2$treat2 == "C"])
df2$unit_weight <- df2$tot_count / (df2$unit_weight * sum(target))
lm_res <- stats::lm(y ~ 0 + treat2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat2 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + covariates + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat2")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat2, target = "B", secondary_unassigned_method = "ignore")
target <- df2$treat2 == "B"
df2$tot_count <- NA
tmp_int_match <- as.integer(matching2)
for (i in unique(tmp_int_match)) {
df2$tot_count[tmp_int_match == i] <- sum(target[tmp_int_match == i], na.rm = TRUE)
}
df2$unit_weight <- NA
df2$unit_weight[df2$treat2 == "A"] <- match_count(as.integer(matching2)[df2$treat2 == "A"])
df2$unit_weight[df2$treat2 == "B"] <- match_count(as.integer(matching2)[df2$treat2 == "B"])
df2$unit_weight[df2$treat2 == "C"] <- match_count(as.integer(matching2)[df2$treat2 == "C"])
df2$unit_weight <- df2$tot_count / (df2$unit_weight * sum(target))
lm_res <- stats::lm(y ~ 0 + treat2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat2 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], lm_res$coefficients[1] - lm_res$coefficients[3],
lm_res$coefficients[2] - lm_res$coefficients[1], 0, lm_res$coefficients[2] - lm_res$coefficients[3],
lm_res$coefficients[3] - lm_res$coefficients[1], lm_res$coefficients[3] - lm_res$coefficients[2], 0),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3],
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3],
coef_var[1,1] + coef_var[3,3] - 2 * coef_var[1,3], coef_var[2,2] + coef_var[3,3] - 2 * coef_var[2,3], 0),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + covariates + target", {
expect_silent(package_result1 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = "B"))
expect_silent(package_result2 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = target))
expect_silent(package_result3 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = which(target)))
expect_silent(package_result4 <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")], target = rev(which(target))))
expect_equal(package_result1$effects, control_effects)
expect_equal(package_result1$effect_variances, control_variances)
expect_equal(package_result2$effects, control_effects)
expect_equal(package_result2$effect_variances, control_variances)
expect_equal(package_result3$effects, control_effects)
expect_equal(package_result3$effect_variances, control_variances)
expect_equal(package_result4$effects, control_effects)
expect_equal(package_result4$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat2")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat2, treatment_constraints = c("A" = 1L, "B" = 1L))
df2$tot_count <- match_count(as.integer(matching2))
df2$unit_weight <- NA
df2$unit_weight[df2$treat2 == "A"] <- match_count(as.integer(matching2)[df2$treat2 == "A"])
df2$unit_weight[df2$treat2 == "B"] <- match_count(as.integer(matching2)[df2$treat2 == "B"])
df2$unit_weight[df2$treat2 == "C"] <- NA
df2$unit_weight <- df2$tot_count / (df2$unit_weight * 500)
lm_res <- stats::lm(y ~ 0 + treat2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], NA,
lm_res$coefficients[2] - lm_res$coefficients[1], 0, NA,
NA, NA, NA),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], NA,
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, NA,
NA, NA, NA),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + missing treatment in matched group", {
expect_warning(package_result <- lm_match(df2$y, df2$treat2, matching2))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat2 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(0, lm_res$coefficients[1] - lm_res$coefficients[2], NA,
lm_res$coefficients[2] - lm_res$coefficients[1], 0, NA,
NA, NA, NA),
ncol = 3, byrow = TRUE)
control_variances <- matrix(c(0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], NA,
coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, NA,
NA, NA, NA),
ncol = 3, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C"), c("A", "B", "C"))
dimnames(control_variances) <- list(c("A", "B", "C"), c("A", "B", "C"))
test_that("`lm_match` three treatments + missing treatment + covariates", {
expect_warning(package_result <- lm_match(df2$y, df2$treat2, matching2, df2[c("x1", "x2")]))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
df2 <- df[c("y", "x1", "x2", "treat3")]
matching2 <- quickmatch(distances(df2[c("x1", "x2")]), df2$treat3, treatment_constraints = c("B" = 1L, "C" = 1L))
df2$tot_count <- match_count(as.integer(matching2))
df2$unit_weight <- NA
df2$unit_weight[df2$treat3 == "A"] <- NA
df2$unit_weight[df2$treat3 == "B"] <- match_count(as.integer(matching2)[df2$treat3 == "B"])
df2$unit_weight[df2$treat3 == "C"] <- match_count(as.integer(matching2)[df2$treat3 == "C"])
df2$unit_weight[df2$treat3 == "D"] <- NA
df2$unit_weight <- df2$tot_count / (df2$unit_weight * 500)
lm_res <- stats::lm(y ~ 0 + treat3, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(NA, NA, NA, NA,
NA, 0, lm_res$coefficients[1] - lm_res$coefficients[2], NA,
NA, lm_res$coefficients[2] - lm_res$coefficients[1], 0, NA,
NA, NA, NA, NA),
ncol = 4, byrow = TRUE)
control_variances <- matrix(c(NA, NA, NA, NA,
NA, 0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], NA,
NA, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, NA,
NA, NA, NA, NA),
ncol = 4, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C", "D"), c("A", "B", "C", "D"))
dimnames(control_variances) <- list(c("A", "B", "C", "D"), c("A", "B", "C", "D"))
test_that("`lm_match` four treatments + missing treatment in matched group", {
expect_warning(package_result <- lm_match(df2$y, df2$treat3, matching2))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
lm_res <- stats::lm(y ~ 0 + treat3 + x1 + x2, data = df2, weights = unit_weight)
coef_var <- sandwich::vcovHC(lm_res, type = "HC1")
control_effects <- matrix(c(NA, NA, NA, NA,
NA, 0, lm_res$coefficients[1] - lm_res$coefficients[2], NA,
NA, lm_res$coefficients[2] - lm_res$coefficients[1], 0, NA,
NA, NA, NA, NA),
ncol = 4, byrow = TRUE)
control_variances <- matrix(c(NA, NA, NA, NA,
NA, 0, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], NA,
NA, coef_var[1,1] + coef_var[2,2] - 2 * coef_var[1,2], 0, NA,
NA, NA, NA, NA),
ncol = 4, byrow = TRUE)
dimnames(control_effects) <- list(c("A", "B", "C", "D"), c("A", "B", "C", "D"))
dimnames(control_variances) <- list(c("A", "B", "C", "D"), c("A", "B", "C", "D"))
test_that("`lm_match` four treatments + missing treatment + covariates", {
expect_warning(package_result <- lm_match(df2$y, df2$treat3, matching2, df2[c("x1", "x2")]))
expect_equal(package_result$effects, control_effects)
expect_equal(package_result$effect_variances, control_variances)
})
|
source("ESEUR_config.r")
le=read.csv(paste0(ESEUR_dir, "economics/msr2018b_evol.csv.xz"), as.is=TRUE)
npm=subset(le, Network == "NPM")
npm$Network=NULL
rownames(npm)=npm$From.To
npm$From.To=NULL
rs=rowSums(npm)
le_perc=t(sapply(1:nrow(npm), function(X) 100*npm[X, ]/rs[X]))
rownames(le_perc)=colnames(le_perc)
|
"sign.boot" <-
function(x, i, p1=0.2, p2=0.8)
{
x <- x[i]
n <- length(x)
Nplus <- sum(x > 0)
Nzero <- sum(x == 0)
Nminus <- n - Nplus - Nzero
if(sum(Nzero) > 0) cat("WARNING:", sum(Nzero), "ties occurred.\n")
S1 <- qbinom(0.95, n, p1)
S2 <- qbinom(0.05, n, p2)
result <- sum(Nplus >= S1 & Nplus <= S2)
}
|
context("Check ms_update_observations() function")
source("test_objects.R")
if (requireNamespace("ranger", quietly=TRUE)) {
ms <- modelStudio::modelStudio(explain_rf, apartments[1:2,], N = 5, B = 2, show_info = v)
testthat::test_that("modelStudio class", {
testthat::expect_is(ms, "modelStudio")
testthat::expect_silent(ms)
})
testthat::test_that("ms_update_observations", {
testthat::expect_silent(new_ms1 <- modelStudio::ms_update_observations(ms, explain_rf, B = 2,
show_info = v))
testthat::expect_is(new_ms1, "modelStudio")
testthat::expect_silent(new_ms2 <- modelStudio::ms_update_observations(ms, explain_rf, B = 2,
show_info = v,
new_observation = apartments[100:101,],
overwrite = FALSE))
testthat::expect_is(new_ms2, "modelStudio")
testthat::expect_silent(new_ms3 <- modelStudio::ms_update_observations(ms, explain_rf, B = 2,
show_info = v,
new_observation = apartments[1:2,],
overwrite = TRUE))
testthat::expect_is(new_ms3, "modelStudio")
testthat::test_that("ms_merge_observations", {
testthat::expect_silent(merged_ms <- ms_merge_observations(new_ms1, new_ms2, new_ms3))
testthat::expect_is(merged_ms, "modelStudio")
})
})
}
|
library(tidyverse)
sza <-
readr::read_csv(file = "data-raw/sza.csv") %>%
dplyr::mutate(month = factor(
month,
levels = c(
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"))
)
|
imNine <- function(items){
if(missing(items)){
stop("Please include x number of items to generate")
}
if(items > 15){
stop("Please select less than 16 items.")
}
fib <- matrix(c(1,1), ncol=1)
x <- NULL
for (i in 1:18) {
x[i] <- c(fib[i,1] + fib[(i+1),1])
fib <- rbind(fib, x[i])
}
vector.fib <- fib[ ,1]
bank_fib <- matrix(ncol=6)
colnames(bank_fib) <- colnames(bank_fib, do.NULL = FALSE, prefix = "Q")
colnames(bank_fib)[6] <- "A"
for (i in 1:items) {
item <- c(vector.fib[i:(i+5)])
bank_fib <- rbind(bank_fib, item)
bank_fib <- na.omit(bank_fib)
}
return(bank_fib)
}
|
get_estimates_naive <- function(Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL,
predictors_Y2 = NULL, copula_param = "both") {
if (is.null(Y1) | is.null(Y2)) {
stop("Both Y1 and Y2 have to be supplied.")
}
dataframe_Y1 <- data.frame(Y1 = Y1)
dataframe_Y2 <- data.frame(Y2 = Y2)
n_ind <- dim(dataframe_Y1)[1]
if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) |
(!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) {
stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.")
}
if (class(predictors_Y1) == "data.frame") {
if (!all(sapply(predictors_Y1, is.numeric))) {
predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1))
warning("predictors_Y1 contains non-numeric Variables,
which have automatically been transformed.")
}
}
if (class(predictors_Y2) == "data.frame") {
if (!all(sapply(predictors_Y2, is.numeric))) {
predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2))
warning("predictors_Y2 contains non-numeric Variables,
which have automatically been transformed.")
}
}
if (!is.null(predictors_Y1)) {
predictors_Y1 <- data.frame(predictors_Y1)
}
if (!is.null(predictors_Y2)) {
predictors_Y2 <- data.frame(predictors_Y2)
}
if (!n_ind == dim(dataframe_Y2)[1]) {
stop("Variables must have same length.")
}
if (!is.null(predictors_Y1)) {
if (!n_ind == dim(predictors_Y1)[1]) {
stop("Variables must have same length.")
}
}
if (!is.null(predictors_Y2)) {
if (!n_ind == dim(predictors_Y2)[1]) {
stop("Variables must have same length.")
}
}
if (!is.null(predictors_Y1)) {
dataframe_Y1 <- cbind(dataframe_Y1, predictors_Y1)
}
if (!is.null(predictors_Y2)) {
dataframe_Y2 <- cbind(dataframe_Y2, predictors_Y2)
}
res_Y1 <- stats::lm(Y1 ~ ., data = dataframe_Y1)
res_Y2 <- stats::lm(Y2 ~ ., data = dataframe_Y2)
param_Y1_sigma <- log(stats::sd(res_Y1$residuals, na.rm = T))
names(param_Y1_sigma) <- "Y1_log_sigma"
param_Y2_sigma <- log(stats::sd(res_Y2$residuals, na.rm = T))
names(param_Y2_sigma) <- "Y2_log_sigma"
tau <- stats::cor(Y1, Y2, use = "complete.obs", method = c("kendall"))
if (tau == 0) {
tau <- 1e-04
}
log_phi <- log(2 * tau/(1 - tau))
log_theta <- log((1/(1 - tau)) - 1)
param_Y1_Y2 <- c(log_phi, log_theta)
names(param_Y1_Y2) <- c("log_phi", "log_theta_minus1")
if (copula_param == "phi") {
param_Y1_Y2 <- param_Y1_Y2[1]
}
if (copula_param == "theta") {
param_Y1_Y2 <- param_Y1_Y2[2]
}
param_Y1_predictors <- res_Y1$coefficients
names(param_Y1_predictors) <- paste("Y1_", names(param_Y1_predictors), sep = "")
param_Y2_predictors <- res_Y2$coefficients
names(param_Y2_predictors) <- paste("Y2_", names(param_Y2_predictors), sep = "")
if (any(is.na(param_Y1_Y2))) {
warning("One or both dependence parameters could not be estimated.")
}
if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) {
warning("One or both marginal variances could not be estimated.")
}
if (any(is.na(param_Y1_predictors)) | any(is.na(param_Y2_predictors))) {
warning("One or more marginal parameters could not be estimated.")
}
estimates <- c(param_Y1_Y2, param_Y1_sigma, param_Y2_sigma,
param_Y1_predictors, param_Y2_predictors)
return(estimates)
}
|
"lL.gaussian" <-
function(params){
sigma <- params[p]
mu <- c(X %*% params[-p])
-sum(log(pnorm(qb, mu, sigma) - pnorm(qa, mu, sigma)))
}
|
fit_members <- function(model_stack, ...) {
check_model_stack(model_stack)
dat <- model_stack[["train"]]
member_names <-
.get_glmn_coefs(
model_stack[["coefs"]][["fit"]],
model_stack[["coefs"]][["spec"]][["args"]][["penalty"]]
) %>%
dplyr::filter(estimate != 0 & terms != "(Intercept)") %>%
dplyr::pull(terms)
if (model_stack[["mode"]] == "classification") {
member_dict <-
sanitize_classification_names(model_stack, member_names)
member_names <- member_dict$new %>% unique()
}
metrics_dict <-
tibble::enframe(model_stack[["model_metrics"]]) %>%
tidyr::unnest(cols = value) %>%
dplyr::mutate(.config = process_.config(.config, ., name = make.names(name)))
if (model_stack[["mode"]] == "regression") {
members_map <-
tibble::enframe(model_stack[["cols_map"]]) %>%
tidyr::unnest(cols = value) %>%
dplyr::full_join(metrics_dict, by = c("value" = ".config"))
} else {
members_map <-
tibble::enframe(model_stack[["cols_map"]]) %>%
tidyr::unnest(cols = value) %>%
dplyr::full_join(member_dict, by = c("value" = "old")) %>%
dplyr::filter(!is.na(new)) %>%
dplyr::select(name, value = new) %>%
dplyr::filter(!duplicated(.$value)) %>%
dplyr::full_join(metrics_dict, by = c("value" = ".config"))
}
if (foreach::getDoParWorkers() > 1) {
`%do_op%` <- foreach::`%dopar%`
} else {
`%do_op%` <- foreach::`%do%`
}
member_fits <-
foreach::foreach(mem = member_names, .inorder = FALSE) %do_op% {
asNamespace("stacks")$fit_member(
name = mem,
wflows = model_stack[["model_defs"]],
members_map = members_map,
train_dat = dat
)
}
model_stack[["member_fits"]] <-
setNames(member_fits, member_names)
if (model_stack_constr(model_stack)) {model_stack}
}
fit_member <- function(name, wflows, members_map, train_dat) {
member_row <-
members_map %>%
dplyr::filter(value == name)
member_params <-
wflows[[member_row$name.x[1]]] %>%
dials::parameters() %>%
dplyr::pull(id)
needs_finalizing <- length(member_params) != 0
if (needs_finalizing) {
member_metrics <-
members_map %>%
dplyr::filter(value == name) %>%
dplyr::slice(1)
member_wf <-
wflows[[member_metrics$name.x]]
new_member <-
tune::finalize_workflow(member_wf, member_metrics[,member_params]) %>%
generics::fit(data = train_dat)
} else {
member_model <-
members_map %>%
dplyr::filter(value == name) %>%
dplyr::select(name.x) %>%
dplyr::pull()
new_member <-
generics::fit(wflows[[member_model[1]]], data = train_dat)
}
new_member
}
sanitize_classification_names <- function(model_stack, member_names) {
outcome_levels <-
model_stack[["train"]] %>%
dplyr::select(!!.get_outcome(model_stack)) %>%
dplyr::pull() %>%
as.character() %>%
unique()
pred_strings <- paste0(".pred_", outcome_levels, "_") %>%
make.names()
new_member_names <-
gsub(
pattern = paste0(pred_strings, collapse = "|"),
x = member_names,
replacement = ""
)
tibble::tibble(
old = member_names,
new = new_member_names
)
}
check_model_stack <- function(model_stack) {
if (inherits(model_stack, "model_stack")) {
if (!is.null(model_stack[["member_fits"]])) {
glue_warn(
"The members in the supplied `model_stack` have already been fitted ",
"and need not be fitted again."
)
}
return(invisible(TRUE))
} else if (inherits(model_stack, "data_stack")) {
glue_stop(
"The supplied `model_stack` argument is a data stack rather than ",
"a model stack. Did you forget to first evaluate the ensemble's ",
"stacking coefficients with `blend_predictions()`?"
)
} else {
check_inherits(model_stack, "model_stack")
}
}
|
library(ggplot2)
library(ggiraph)
df <- expand.grid(x = 1:10, y=1:10)
df$angle <- runif(100, 0, 2*pi)
df$speed <- runif(100, 0, sqrt(0.1 * df$x))
p <- ggplot(df, aes(x, y)) +
geom_point() +
geom_spoke_interactive(aes(angle = angle, tooltip=round(angle, 2)), radius = 0.5)
x <- girafe(ggobj = p)
if( interactive() ) print(x)
p2 <- ggplot(df, aes(x, y)) +
geom_point() +
geom_spoke_interactive(aes(angle = angle, radius = speed,
tooltip=paste(round(angle, 2), round(speed, 2), sep="\n")))
x2 <- girafe(ggobj = p2)
if( interactive() ) print(x2)
|
setClass("madness",
representation(val="array", dvdx="matrix", xtag="character", vtag="character", varx="matrix"),
prototype(val=matrix(nrow=0,ncol=0),
dvdx=matrix(nrow=0,ncol=0),
xtag=NA_character_,
vtag=NA_character_,
varx=matrix(nrow=0,ncol=0)),
validity=function(object) {
if (length(object@val) != dim(object@dvdx)[1]) { return("bad dimensionality or derivative not in numerator layout.") }
if (dim(object@varx)[1] != dim(object@varx)[2]) { return("must give empty or square varx variance covariance.") }
if ((dim(object@varx)[1] != 0) && (dim(object@varx)[1] != dim(object@dvdx)[2])) {
return("must give empty or conformable varx variance covariance.")
}
return(TRUE)
}
)
setMethod('initialize',
signature('madness'),
function(.Object,val,dvdx,xtag=NA_character_,vtag=NA_character_,varx=matrix(nrow=0,ncol=0)) {
if (length(val) != dim(dvdx)[1]) { stop("bad dimensionality or derivative not in numerator layout.") }
if (dim(varx)[1] != dim(varx)[2]) { stop("must give empty or square varx variance covariance.") }
if ((dim(varx)[1] != 0) && (dim(varx)[1] != dim(dvdx)[2])) {
stop("must give empty or conformable varx variance covariance.")
}
if (is.null(dim(val))) {
if (length(val) > 1) { warning('no dimension given, turning val into a column') }
dim(val) <- c(length(val),1)
}
.Object@val <- val
.Object@dvdx <- dvdx
.Object@xtag <- xtag
.Object@vtag <- vtag
.Object@varx <- varx
.Object
})
madness <- function(val,dvdx=NULL,vtag=NULL,xtag=NULL,varx=NULL) {
if (missing(vtag)) {
vtag <- deparse(substitute(val))
}
if (missing(dvdx) || is.null(dvdx)) {
dvdx <- diag(1,nrow=length(val))
if (missing(xtag)) {
xtag <- vtag
}
} else if (missing(xtag)) {
xtag <- 'x'
}
if (is.null(dim(val))) {
if (length(val) > 1) { warning('no dimension given, turning val into a column') }
dim(val) <- c(length(val),1)
}
if (is.null(dim(dvdx))) {
if (length(dvdx) > length(val)) { warning('no dimension given, turning independent variable into a column') }
taild <- length(dvdx) / length(val)
dim(dvdx) <- c(length(val),taild)
}
if (is.null(varx)) { varx <- matrix(nrow=0,ncol=0) }
retv <- new("madness", val=val, dvdx=dvdx, xtag=xtag, vtag=vtag, varx=varx)
invisible(retv)
}
as.madness <- function(x, vtag=NULL, xtag=NULL) {
UseMethod("as.madness", x)
}
as.madness.default <- function(x, vtag=NULL, xtag=NULL) {
if (missing(vtag)) {
vtag <- deparse(substitute(val))
}
if (missing(xtag)) {
xtag <- vtag
}
val <- coef(x)
if (is.null(dim(val))) {
dim(val) <- c(length(val),1)
}
varx <- tryCatch({ vcov(x) },error = function(e) { NULL })
invisible(madness(val,xtag=xtag,vtag=vtag,varx=varx))
}
setGeneric('val', signature="x", function(x) standardGeneric('val'))
setMethod('val', 'madness', function(x) x@val )
setMethod('dim', 'madness', function(x) dim(val(x)) )
setMethod('length', 'madness', function(x) length(val(x)) )
setGeneric('dvdx', signature="x", function(x) standardGeneric('dvdx'))
setMethod('dvdx', 'madness', function(x) x@dvdx )
setGeneric('xtag', signature="x", function(x) standardGeneric('xtag'))
setMethod('xtag', 'madness', function(x) x@xtag )
setGeneric('vtag', signature="x", function(x) standardGeneric('vtag'))
setMethod('vtag', 'madness', function(x) x@vtag )
setGeneric('varx', signature="x", function(x) standardGeneric('varx'))
setMethod('varx', 'madness', function(x) x@varx )
setGeneric('xtag<-', signature="x", function(x,value) standardGeneric('xtag<-'))
setReplaceMethod('xtag', 'madness', function(x,value) initialize(x, val=x@val, dvdx=x@dvdx, xtag=value, vtag=x@vtag, varx=x@varx))
setGeneric('vtag<-', signature="x", function(x,value) standardGeneric('vtag<-'))
setReplaceMethod('vtag', 'madness', function(x,value) initialize(x, val=x@val, dvdx=x@dvdx, xtag=x@xtag, vtag=value, varx=x@varx))
setGeneric('varx<-', signature="x", function(x,value) standardGeneric('varx<-'))
setReplaceMethod('varx', 'madness', function(x,value) initialize(x, val=x@val, dvdx=x@dvdx, xtag=x@xtag, vtag=x@xtag, varx=value))
NULL
setMethod('show', signature('madness'),
function(object) {
rchar <- function(achr,alen) { paste0(rep(achr,ceiling(alen)),collapse='') }
cat('class:', class(object), '\n')
xlen <- nchar(object@xtag) + 4
ylen <- nchar(object@vtag) + 4
mlen <- max(xlen,ylen)
repr <- sprintf(paste0(' %',ceiling((mlen + ylen)/2),'s\n',
' calc: ',rchar('-',mlen), ' \n',
' %',ceiling((mlen + xlen)/2),'s\n'),
paste0(rchar(' ',(mlen-ylen)/2),'d ',object@vtag),
paste0(rchar(' ',(mlen-xlen)/2),'d ',object@xtag))
cat(repr)
cat(' val:', head(object@val,1L), '...\n')
cat(' dvdx:', head(object@dvdx,1L), '...\n')
cat(' varx:', head(object@varx,1L), '...\n')
})
|
lexicon <- function(lexicon){
check_lexicon_name(lexicon)
get(paste0("lexicon_", lexicon))
}
|
library(shiny.fluent)
if (interactive()) {
shinyApp(
ui = TooltipHost(
content = "This is the tooltip content",
delay = 0,
Text("Hover over me")
),
server = function(input, output) {}
)
}
|
CrinsEtAl2014 <- data.frame("publication"=c("Spada (2006)", "Ganschow (2005)",
"Gibelli (2004)", "Heffron (2003)",
"Schuller (2005)", "Gras (2008)"),
"year"=c(2006, 2005, 2004, 2003, 2005, 2008),
"randomized"=factor(c("yes","no")[c(1,2,2,1,2,2)],
levels=c("yes","no","n.s.")),
"control.type"=factor(c("concurrent","historical",
"historical","concurrent",
"concurrent","historical"),
levels=c("concurrent","historical")),
"comparison"=factor(c("IL-2RA only","delayed CNI","no/low steroids")[c(3,1,1,2,1,3)],
levels=c("IL-2RA only","delayed CNI","no/low steroids")),
"IL2RA"=factor(c("basiliximab","daclizumab")[c(1,1,1,2,2,1)]),
"CNI"=factor(c("cyclosporine A","tacrolimus")[c(2,1,1,2,2,2)]),
"MMF"=factor(c("yes","no")[c(2,2,2,1,1,2)],
levels=c("yes","no")),
"followup"=c(12,36,6,24,6,36),
"exp.AR.events"=c(4,9,16,14,3,0),
"exp.SRR.events"=c(NA,4,NA,2,NA,1),
"exp.PTLD.events"=c(1,1,NA,NA,0,NA),
"exp.deaths"=c(4,1,NA,4,NA,2),
"exp.total"=c(36,54,28,61,18,50),
"cont.AR.events"=c(11,29,19,15,8,3),
"cont.SRR.events"=c(NA,6,NA,4,NA,4),
"cont.PTLD.events"=c(1,0,NA,NA,0,NA),
"cont.deaths"=c(3,3,NA,3,NA,3),
"cont.total"=c(36,54,28,20,12,34),
stringsAsFactors=FALSE)[c(4,3,5,2,1,6),]
rownames(CrinsEtAl2014) <- as.character(1:6)
|
max_expo <- function(indiv, adrug){
expo_no <- cbind("indiv"=indiv, "adrug"=adrug)
expo_no_unique <- data.frame(unique(expo_no))
no_of_expo <- table(expo_no_unique$indiv)
max_no_of_expo <- max(no_of_expo)
return(max_no_of_expo)
}
|
generate_dot2 <- function(graph) {
attr_type <- attr <- value <- string <- NULL
nodes_df <- graph$nodes_df
edges_df <- graph$edges_df
directed <- graph$directed
global_attrs <- graph$global_attrs
if ("graph" %in% global_attrs$attr_type) {
graph_attrs <-
global_attrs %>%
dplyr::filter(attr_type == "graph") %>%
dplyr::mutate(string = paste0(attr, " = '", value, "'"))
graph_attrs <-
graph_attrs %>%
dplyr::pull(string)
} else {
graph_attrs <- NA
}
if ("node" %in% global_attrs$attr_type) {
node_attrs <-
global_attrs %>%
dplyr::filter(attr_type == "node") %>%
dplyr::mutate(string = paste0(attr, " = '", value, "'"))
node_attrs <-
node_attrs %>%
dplyr::pull(string)
for (i in 1:nrow(global_attrs %>% dplyr::filter(attr_type == "node"))) {
node_attr_to_set <- (global_attrs %>% dplyr::filter(attr_type == "node"))[i, 1]
if (node_attr_to_set %in% colnames(nodes_df)) {
col_num <- which(colnames(nodes_df) == node_attr_to_set)
nodes_df[which(is.na(nodes_df[, col_num])), col_num] <-
(global_attrs %>% dplyr::filter(attr_type == "node"))[i, 2]
}
}
} else {
node_attrs <- NA
}
if ("edge" %in% global_attrs$attr_type) {
edge_attrs <-
global_attrs %>%
dplyr::filter(attr_type == "edge") %>%
dplyr::mutate(string = paste0(attr, " = '", value, "'"))
edge_attrs <-
edge_attrs %>%
dplyr::pull(string)
for (i in 1:nrow(global_attrs %>% dplyr::filter(attr_type == "edge"))) {
edge_attr_to_set <- (global_attrs %>% dplyr::filter(attr_type == "edge"))[i, 1]
if (edge_attr_to_set %in% colnames(edges_df)) {
col_num <- which(colnames(edges_df) == edge_attr_to_set)
edges_df[which(is.na(edges_df[, col_num])), col_num] <-
(global_attrs %>% dplyr::filter(attr_type == "edge"))[i, 2]
}
}
} else {
edge_attrs <- NA
}
if (!is.null(nodes_df)) {
if (ncol(nodes_df) >= 4) {
for (i in 4:ncol(nodes_df)) {
nodes_df[, i] <-
as.character(nodes_df[, i])
nodes_df[, i] <-
ifelse(is.na(nodes_df[, i]), "", nodes_df[, i])
}
}
}
if (!is.null(edges_df)) {
if (ncol(edges_df) >= 4) {
for (i in 4:ncol(edges_df)) {
edges_df[, i] <-
ifelse(is.na(edges_df[, i]), "", edges_df[, i])
edges_df[, i] <-
as.character(edges_df[, i])
}
}
}
if ("equation" %in% colnames(nodes_df)) {
equation_col <- which(colnames(nodes_df) == "equation")
for (i in 1:nrow(nodes_df)) {
if (grepl("^\\$.*\\$$", nodes_df[i, equation_col])) {
nodes_df[i, equation_col] <-
str_replace_all(
nodes_df[i, equation_col], "\\\\", "\\\\\\\\")
} else {
nodes_df[i, equation_col] <- ""
}
}
}
if ("display" %in% colnames(nodes_df)) {
display_col <- which(colnames(nodes_df) == "display")
label_col <- which(colnames(nodes_df) == "label")
for (i in 1:nrow(nodes_df)) {
if (nodes_df[i, display_col] != "") {
nodes_df[i, label_col] <-
nodes_df[
i, which(colnames(nodes_df) == nodes_df[i, display_col])]
} else {
nodes_df[i, label_col] <- ""
}
}
}
if ("display" %in% colnames(edges_df)) {
display_col <- which(colnames(edges_df) == "display")
if (!("label" %in% colnames(edges_df))) {
edges_df <-
edges_df %>%
mutate(label = as.character(NA))
}
label_col <- which(colnames(edges_df) == "label")
for (i in 1:nrow(edges_df)) {
if (!is.na(edges_df[i, display_col]) ) {
if (edges_df[i, display_col] != "") {
edges_df[i, label_col] <-
edges_df[
i, which(colnames(edges_df) == edges_df[i, display_col])]
}
} else {
edges_df[i, label_col] <- ""
}
}
}
graph_attributes <- c("layout", "bgcolor", "rankdir",
"overlap", "outputorder", "fixedsize",
"mindist", "nodesep", "ranksep",
"stylesheet")
node_attributes <- c("shape", "style", "penwidth", "color", "fillcolor",
"fontname", "fontsize", "fontcolor", "image", "fa_icon",
"height", "width", "group",
"tooltip", "xlabel", "URL",
"distortion", "sides", "skew", "peripheries",
"gradientangle", "label", "fixedsize",
"labelloc", "margin", "orientation", "pos")
edge_attributes <- c("style", "penwidth", "color", "arrowsize",
"arrowhead", "arrowtail",
"fontname", "fontsize", "fontcolor",
"len", "tooltip", "URL",
"label", "labelfontname", "labelfontsize",
"labelfontcolor", "labeltooltip", "labelURL",
"edgetooltip", "edgeURL",
"headtooltip", "headURL",
"headclip", "headlabel", "headport",
"tailtooltip", "tailURL",
"tailclip", "taillabel", "tailport",
"dir", "decorate")
if (nrow(nodes_df) == 0 &
nrow(edges_df) == 0) {
dot_code <-
paste0(ifelse(directed,
"digraph", "graph"),
" {\n", "\n}")
} else {
if (!(any(is.na(graph_attrs)))) {
graph_attr_stmt <-
paste0("graph [",
paste(graph_attrs,
collapse = ",\n "),
"]\n")
} else {
graph_attr_stmt <- ""
}
if (!(any(is.na(node_attrs)))) {
node_attr_stmt <-
paste0("node [", paste(node_attrs,
collapse = ",\n "),
"]\n")
} else {
node_attr_stmt <- ""
}
if (!(any(is.na(edge_attrs)))) {
edge_attr_stmt <-
paste0("edge [", paste(edge_attrs,
collapse = ",\n "),
"]\n")
} else {
edge_attr_stmt <- ""
}
combined_attr_stmts <-
paste(
graph_attr_stmt,
node_attr_stmt,
edge_attr_stmt, sep = "\n")
if (nrow(nodes_df) > 0) {
column_with_x <-
which(colnames(nodes_df) %in% "x")[1]
column_with_y <-
which(colnames(nodes_df) %in% "y")[1]
if (!is.na(column_with_x) & !is.na(column_with_y)) {
pos <-
data.frame(
"pos" =
paste0(
nodes_df[, column_with_x],
",",
nodes_df[, column_with_y],
"!"))
nodes_df$pos <- pos$pos
}
if (any(grepl("$alpha^", colnames(nodes_df)))) {
column_with_alpha_assigned <-
grep("$alpha^", colnames(nodes_df))
} else {
column_with_alpha_assigned <- NA
}
if (!is.na(column_with_alpha_assigned)) {
number_of_col_attr <-
length(which(colnames(nodes_df) %in%
c("color", "fillcolor",
"fontcolor")))
if (number_of_col_attr == 1) {
name_of_col_attr <-
colnames(nodes_df)[
which(colnames(nodes_df) %in%
c("color", "fillcolor",
"fontcolor"))]
colnames(nodes_df)[column_with_alpha_assigned] <-
paste0("alpha:", name_of_col_attr)
}
}
if (any(grepl("alpha:.*", colnames(nodes_df)))) {
alpha_column_no <- grep("alpha:.*", colnames(nodes_df))
color_attr_column_name <-
unlist(strsplit(colnames(nodes_df)[
(which(grepl("alpha:.*", colnames(nodes_df))))
], ":"))[-1]
color_attr_column_no <-
which(colnames(nodes_df) %in% color_attr_column_name)
if (any(c("color", "fillcolor", "fontcolor") %in%
colnames(nodes_df)[color_attr_column_no])) {
if (all(grepl("[a-z]*",
as.character(nodes_df[, color_attr_column_no]))) &
all(as.character(nodes_df[, color_attr_column_no]) %in%
x11_hex()[, 1])) {
for (i in 1:nrow(nodes_df)) {
nodes_df[i, color_attr_column_no] <-
paste0(x11_hex()[
which(x11_hex()[, 1] %in%
as.character(nodes_df[i, color_attr_column_no])), 2],
formatC(round(as.numeric(nodes_df[i, alpha_column_no]), 0),
flag = "0", width = 2))
}
}
if (all(grepl("
as.character(nodes_df[, color_attr_column_no])))) {
for (i in 1:nrow(nodes_df)) {
nodes_df[, color_attr_column_no] <-
as.character(nodes_df[, color_attr_column_no])
nodes_df[i, color_attr_column_no] <-
paste0(nodes_df[i, color_attr_column_no],
round(as.numeric(nodes_df[i, alpha_column_no]), 0))
}
}
}
}
other_columns_with_node_attributes <-
which(colnames(nodes_df) %in% node_attributes)
for (i in 1:nrow(nodes_df)) {
if (i == 1) {
node_block <- vector(mode = "character", length = 0)
}
if (length(other_columns_with_node_attributes) > 0) {
for (j in other_columns_with_node_attributes) {
if (j == other_columns_with_node_attributes[1]) {
attr_string <- vector(mode = "character", length = 0)
}
if (all(colnames(nodes_df)[j] %in%
c("label", "tooltip"),
is.na(nodes_df[i, j]))) {
attribute <- NULL
} else if (all(colnames(nodes_df)[j] %in%
c("label", "tooltip"),
!is.na(nodes_df[i, j]))) {
attribute <-
paste0(colnames(nodes_df)[j],
" = ", "'", nodes_df[i, j], "'")
} else if (all(!(colnames(nodes_df)[j] %in%
c("label", "tooltip")),
is.na(nodes_df[i, j]))) {
attribute <- NULL
} else if (all(!(colnames(nodes_df)[j] %in%
c("label", "tooltip")),
!is.na(nodes_df[i, j]))) {
attribute <-
paste0(colnames(nodes_df)[j],
" = ", "'", nodes_df[i, j], "'")
}
attr_string <- c(attr_string, attribute)
}
if (j == other_columns_with_node_attributes[
length(other_columns_with_node_attributes)]) {
attr_string <- paste(attr_string, collapse = ", ")
}
}
if (exists("attr_string")) {
line <- paste0(" '", nodes_df[i, 1], "'",
" [", attr_string, "] ")
}
if (!exists("attr_string")) {
line <-
paste0(" '",
nodes_df[i, 1],
"'")
}
node_block <- c(node_block, line)
}
if ("rank" %in% colnames(nodes_df)) {
node_block <-
c(node_block,
tapply(node_block,
nodes_df$rank, FUN = function(x) {
if(length(x) > 1) {
x <- paste0('subgraph{rank = same\n',
paste0(x, collapse = '\n'),
'}\n')
}
return(x)
}))
}
else if ('cluster' %in% colnames(nodes_df)) {
clustered_node_block <- character(0)
clusters <- split(node_block, nodes_df$cluster)
for (i in seq_along(clusters)) {
if (names(clusters)[[i]] == "") {
cluster_block <- clusters[[i]]
} else {
cluster_block <- paste0("subgraph cluster", i, "{\nlabel='",
names(clusters)[[i]], "'\n",
paste0(clusters[[i]], collapse="\n"), "}\n")
}
clustered_node_block <- c(clustered_node_block, cluster_block)
}
node_block <- clustered_node_block
rm(clustered_node_block, clusters, cluster_block)
}
node_block <- paste(node_block, collapse = "\n")
if (exists("attr_string")) {
rm(attr_string)
}
if (exists("attribute")) {
rm(attribute)
}
}
if (nrow(edges_df) > 0) {
from_to_columns <-
ifelse(any(c("from", "to") %in%
colnames(edges_df)), TRUE, FALSE)
other_columns_with_edge_attributes <-
which(colnames(edges_df) %in% edge_attributes)
if (from_to_columns) {
both_from_to_columns <-
all(c(any(c("from") %in%
colnames(edges_df))),
any(c("to") %in%
colnames(edges_df)))
}
if (exists("both_from_to_columns")) {
if (both_from_to_columns) {
from_column <-
which(colnames(edges_df) %in% c("from"))[1]
to_column <-
which(colnames(edges_df) %in% c("to"))[1]
}
}
if (exists("from_column") &
exists("to_column")) {
if (length(from_column) == 1 &
length(from_column) == 1) {
for (i in 1:nrow(edges_df)) {
if (i == 1) {
edge_block <-
vector(mode = "character", length = 0)
}
if (length(other_columns_with_edge_attributes) > 0) {
for (j in other_columns_with_edge_attributes) {
if (j == other_columns_with_edge_attributes[1]) {
attr_string <- vector(mode = "character", length = 0)
}
if (all(colnames(edges_df)[j] %in%
c("edgetooltip", "headtooltip",
"label", "labeltooltip",
"taillabel", "tailtooltip",
"tooltip"),
is.na(edges_df[i, j]))) {
attribute <- NULL
} else if (all(colnames(edges_df)[j] %in%
c("edgetooltip", "headtooltip",
"label", "labeltooltip",
"taillabel", "tailtooltip",
"tooltip"),
edges_df[i, j] != '')) {
attribute <-
paste0(colnames(edges_df)[j],
" = ", "'", edges_df[i, j],
"'")
} else if (all(!(colnames(edges_df)[j] %in%
c("edgetooltip", "headtooltip",
"label", "labeltooltip",
"taillabel", "tailtooltip",
"tooltip")),
is.na(edges_df[i, j]))) {
attribute <- NULL
} else if (all(!(colnames(edges_df)[j] %in%
c("edgetooltip", "headtooltip",
"label", "labeltooltip",
"taillabel", "tailtooltip",
"tooltip")),
edges_df[i, j] != '')) {
attribute <-
paste0(colnames(edges_df)[j],
" = ", "'", edges_df[i, j], "'")
}
attr_string <- c(attr_string, attribute)
}
if (j == other_columns_with_edge_attributes[
length(other_columns_with_edge_attributes)]) {
attr_string <- paste(attr_string, collapse = ", ")
}
}
if (exists("attr_string")) {
line <-
paste0("'", edges_df[i, from_column], "'",
ifelse(directed, "->", "--"),
"'", edges_df[i, to_column], "'",
paste0(" [", attr_string, "] "))
}
if (!exists("attr_string")) {
line <-
paste0(" ",
"'", edges_df[i, from_column], "'",
ifelse(directed, "->", "--"),
"'", edges_df[i, to_column], "'",
" ")
}
edge_block <- c(edge_block, line)
}
}
}
if (exists("edge_block")) {
edge_block <- paste(edge_block, collapse = "\n")
}
}
if (exists("combined_attr_stmts")) {
if (exists("edge_block") & exists("node_block")) {
combined_block <-
paste(combined_attr_stmts,
node_block, edge_block,
sep = "\n")
}
if (!exists("edge_block") & exists("node_block")) {
combined_block <-
paste(combined_attr_stmts,
node_block,
sep = "\n")
}
}
if (!exists("combined_attr_stmts")) {
if (exists("edge_block")) {
combined_block <- paste(node_block, edge_block,
sep = "\n")
}
if (!exists("edge_block")) {
combined_block <- node_block
}
}
dot_code <-
paste0(ifelse(directed, "digraph", "graph"),
" {\n", "\n", combined_block, "\n}")
dot_code <- gsub(" \\[\\] ", "", dot_code)
}
dot_code
}
|
print.comp.cutpoints.binary <-
function(x, digits = 4, ...) {
cat("\n\n*************************************************\n")
cat("Compare optimal number of cut points")
cat("\n*************************************************\n\n")
cat(paste("Bias corrected AUC difference:", round(x$AUC.cor.diff, 4), sep=" "), fill=TRUE)
cat(paste("95% Bootstrap Confidence Interval:","(",round(x$icb.auc.diff[1], 4),",", round(x$icb.auc.diff[2], 4), ")" ,sep=" "), fill=TRUE)
invisible(x)
}
|
scale_colour_brewer <- function(..., type = "seq", palette = 1, direction = 1, aesthetics = "colour") {
discrete_scale(aesthetics, "brewer", brewer_pal(type, palette, direction), ...)
}
scale_fill_brewer <- function(..., type = "seq", palette = 1, direction = 1, aesthetics = "fill") {
discrete_scale(aesthetics, "brewer", brewer_pal(type, palette, direction), ...)
}
scale_colour_distiller <- function(..., type = "seq", palette = 1, direction = -1, values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "colour") {
type <- match.arg(type, c("seq", "div", "qual"))
if (type == "qual") {
warn("Using a discrete colour palette in a continuous scale.\n Consider using type = \"seq\" or type = \"div\" instead")
}
continuous_scale(aesthetics, "distiller",
gradient_n_pal(brewer_pal(type, palette, direction)(7), values, space), na.value = na.value, guide = guide, ...)
}
scale_fill_distiller <- function(..., type = "seq", palette = 1, direction = -1, values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "fill") {
type <- match.arg(type, c("seq", "div", "qual"))
if (type == "qual") {
warn("Using a discrete colour palette in a continuous scale.\n Consider using type = \"seq\" or type = \"div\" instead")
}
continuous_scale(aesthetics, "distiller",
gradient_n_pal(brewer_pal(type, palette, direction)(7), values, space), na.value = na.value, guide = guide, ...)
}
scale_colour_fermenter <- function(..., type = "seq", palette = 1, direction = -1, na.value = "grey50", guide = "coloursteps", aesthetics = "colour") {
type <- match.arg(type, c("seq", "div", "qual"))
if (type == "qual") {
warn("Using a discrete colour palette in a binned scale.\n Consider using type = \"seq\" or type = \"div\" instead")
}
binned_scale(aesthetics, "fermenter", binned_pal(brewer_pal(type, palette, direction)), na.value = na.value, guide = guide, ...)
}
scale_fill_fermenter <- function(..., type = "seq", palette = 1, direction = -1, na.value = "grey50", guide = "coloursteps", aesthetics = "fill") {
type <- match.arg(type, c("seq", "div", "qual"))
if (type == "qual") {
warn("Using a discrete colour palette in a binned scale.\n Consider using type = \"seq\" or type = \"div\" instead")
}
binned_scale(aesthetics, "fermenter", binned_pal(brewer_pal(type, palette, direction)), na.value = na.value, guide = guide, ...)
}
|
exo <- function(x)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[!is.na(x@Vars$exogenous)][x@Vars$exogenous[!is.na(x@Vars$exogenous)]]
}
"exo<-" <- function(x,value)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[!is.na(x@Vars$exogenous)][x@Vars$exogenous[!is.na(x@Vars$exogenous)]] <- FALSE
x@Vars$exogenous[x@Vars$name%in%value] <- TRUE
return(x)
}
endo <- function(x)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[!is.na(x@Vars$exogenous)][!x@Vars$exogenous[!is.na(x@Vars$exogenous)]]
}
"endo<-" <- function(x,value)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[!is.na(x@Vars$exogenous)][!x@Vars$exogenous[!is.na(x@Vars$exogenous)]] <- TRUE
x@Vars$exogenous[x@Vars$name%in%value] <- FALSE
return(x)
}
man <- function(x)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[x@Vars$manifest]
}
"man<-" <- function(x,value)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$manifest[x@Vars$name%in%value] <- TRUE
return(x)
}
lat <- function(x)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$name[!x@Vars$manifest]
}
"lat<-" <- function(x,value)
{
if (!"semPlotModel"%in%class(x)) stop("'semPlotModel' object is required")
x@Vars$manifest[x@Vars$name%in%value] <- FALSE
return(x)
}
|
context("getObjetFunctionArgumentNames")
source('pathResolver.R')
source(file.path(computeRootPath(), 'code-samples', 'classes', 'sample-classes.R'))
test_that("getObjetFunctionArgumentNames", {
expect_true(is.na(getObjectFunctionArgumentNames(new.env())))
expect_length(getObjectFunctionArgumentNames(EmptyEnv()), 0)
expect_length(getObjectFunctionArgumentNames(MyEnv()), 1)
expect_length(getObjectFunctionArgumentNames(Bu_S3()), 2)
expect_length(getObjectFunctionArgumentNames(Accumulator_R6$new(), FALSE), 1)
expect_length(getObjectFunctionArgumentNames(new('Person_RC', name = 'neonira'), FALSE), 2)
expect_true(length(getObjectFunctionArgumentNames(new('Person_S4', name = 'neonira'), FALSE)) <= 1)
})
|
library(networkreporting)
library(surveybootstrap)
hidden.q <- c("sex.workers", "msm", "idu", "clients")
hm.q <- c("widower", "nurse.or.doctor", "male.community.health", "teacher",
"woman.smoke", "priest", "civil.servant", "woman.gave.birth",
"muslim", "incarcerated", "judge", "man.divorced", "treatedfortb",
"nsengimana", "murekatete", "twahirwa", "mukandekezi", "nsabimana",
"mukamana", "ndayambaje", "nyiraneza", "bizimana", "nyirahabimana",
"ndagijimana", "mukandayisenga", "died")
tot.pop.size <- 10718378
example.knownpop.dat
kp.vec <- df.to.kpvec(example.knownpop.dat, kp.var="known.popn", kp.value="size")
kp.vec
tot.pop.size <- 10e6
head(example.survey)
known.popn.vars <- paste(example.knownpop.dat$known.popn)
summary(example.survey[,known.popn.vars])
example.survey <- topcode.data(example.survey,
vars=known.popn.vars,
max=30)
summary(example.survey[,known.popn.vars])
d.hat <- kp.degree.estimator(survey.data=example.survey,
known.popns=kp.vec,
total.popn.size=tot.pop.size,
missing="complete.obs")
summary(d.hat)
library(ggplot2)
theme_set(theme_minimal())
qplot(d.hat, binwidth=25)
example.survey$d.hat <- d.hat
idu.est <- nsum.estimator(survey.data=example.survey,
d.hat.vals=d.hat,
total.popn.size=tot.pop.size,
y.vals="idu",
missing="complete.obs")
idu.est
idu.est <- bootstrap.estimates(
survey.design = ~ cluster + strata(region),
num.reps=100,
estimator.fn="nsum.estimator",
weights="indweight",
bootstrap.fn="rescaled.bootstrap.sample",
survey.data=example.survey,
d.hat.vals=d.hat,
total.popn.size=tot.pop.size,
y.vals="idu",
missing="complete.obs")
library(plyr)
all.idu.estimates <- ldply(idu.est,
function(x) { data.frame(estimate=x$estimate) })
qplot(all.idu.estimates$estimate, binwidth=50)
summary(all.idu.estimates$estimate)
quantile(all.idu.estimates$estimate, probs=c(0.025, 0.975))
iv.result <- nsum.internal.validation(survey.data=example.survey,
known.popns=kp.vec,
missing="complete.obs",
killworth.se=TRUE,
total.popn.size=tot.pop.size,
kp.method=TRUE,
return.plot=TRUE)
iv.result$results
print(iv.result$plot)
print(iv.result$plot + ggtitle("internal validation checks"))
example.survey <- add.kp(example.survey, kp.vec, tot.pop.size)
d.hat.new <- kp.degree.estimator(survey.data=example.survey,
missing="complete.obs")
summary(d.hat.new)
|
adKSampleTest <- function(x, ...) UseMethod("adKSampleTest")
adKSampleTest.default <-
function(x, g, ...)
{
if (is.list(x)) {
if (length(x) < 2L)
stop("'x' must be a list with at least 2 elements")
DNAME <- deparse(substitute(x))
x <- lapply(x, function(u) u <- u[complete.cases(u)])
k <- length(x)
l <- sapply(x, "length")
if (any(l == 0))
stop("all groups must contain data")
g <- factor(rep(1 : k, l))
x <- unlist(x)
}
else {
if (length(x) != length(g))
stop("'x' and 'g' must have the same length")
DNAME <- paste(deparse(substitute(x)), "and",
deparse(substitute(g)))
OK <- complete.cases(x, g)
x <- x[OK]
g <- g[OK]
if (!all(is.finite(g)))
stop("all group levels must be finite")
g <- factor(g)
k <- nlevels(g)
if (k < 2)
stop("all observations are in the same group")
}
ix <- order(as.character(g))
g <- g[ix]
x <- x[ix]
n <- tapply(x, g, length)
N <- sum(n)
ADstatV1 <- function(x, g){
lev <- levels(g)
Zstar <- sort(x)
Zstar <- unique(Zstar)
L <- length(Zstar)
f <- matrix(0, ncol=L, nrow=k)
for (i in 1:k){
tmp <- x[g == lev[i]]
f[i,] <- sapply(Zstar, function(Z){
return(length(tmp[tmp == Z]))
}
)
}
l <- sapply(1:L, function(j) sum(f[,j]))
tmp <- rep(NA,k)
for (i in 1:k){
tm <- 0
for (j in 1:(L-1)){
Bj <- sum(l[1:j])
Mij <- sum(f[i, 1:j])
tm <- tm + (l[j] / N) *
((N * Mij - n[i] * Bj)^2 /
(Bj * (N - Bj)))
}
tmp[i] <- tm
}
AsqkN <- sum(1/n * tmp)
return(AsqkN)
}
AsqkN <- ADstatV1(x, g)
H <- sum(1/n)
h <- sum(1/(1:(N-1)))
G <- 0
for (i in 1:(N-2)){
G <- G + sum( 1 / ((N - i) * (i+1):(N-1)))
}
a <- (4 * G - 6) * (k - 1) + (10 - 6 * G) * H
b <- (2 * G - 4) * k^2 + 8 * h * k +
(2 * G - 14 * h - 4) * H - 8 * h + 4 * G - 6
c <- (6 * h + 2 * G - 2) * k^2 +
(4 * h - 4 * G + 6) * k +
(2 * h - 6) * H + 4 * h
d <- (2 * h + 6) * k^2 - 4 * h * k
varAsqkN <- (a * N^3 + b * N^2 + c * N + d) /
((N - 1) * (N - 2) * (N- 3))
m <- k - 1
TkN <- (AsqkN - m) / sqrt(varAsqkN)
PVAL <- ad.pval(tx=TkN, m=m, version=1)
METHOD <- paste("Anderson-Darling k-Sample Test")
ans <- list(method = METHOD,
data.name = DNAME,
p.value = PVAL,
statistic = c(TkN = TkN),
parameter = c(m = m),
estimate = c(A2kN = AsqkN, "sigmaN" = sqrt(varAsqkN)))
class(ans) <- "htest"
ans
}
adKSampleTest.formula <-
function(formula, data, subset, na.action, ...)
{
mf <- match.call(expand.dots=FALSE)
m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1L]] <- quote(stats::model.frame)
if(missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
mf <- eval(mf, parent.frame())
if(length(mf) > 2L)
stop("'formula' should be of the form response ~ group")
DNAME <- paste(names(mf), collapse = " by ")
names(mf) <- NULL
y <- do.call("adKSampleTest", as.list(mf))
y$data.name <- DNAME
y
}
|
tlsce <- function(A,
B,
Wa=NULL,
Wb=NULL,
minA=NULL,
maxA=NULL,
A_init=A,
Xratios=TRUE,
...)
{
A <- as.matrix(A)
B <- as.matrix(B)
l <- nrow(A)
m <- ncol(A)
n <- NCOL(B)
w <- which(A>0)
lw <- length(w)
A_c <- A[w]
if (Xratios
) {
E <- t(rep(1,m)); F <- t(rep(1,n))} else {
E <- t(rep(0,m)); F <- t(rep(0,n))}
G <- diag(1,m); H <- matrix(0,m,n)
if (is.null(Wa)) Wa <- 1
if (length(Wa)==1) Wa <- matrix(Wa,l,m)
if (length(Wa)==length(A)) Wa_c <- Wa[w]
if (length(Wb)==1) Wb <- matrix(Wb,l,n)
A_c_init <- A_init[w]
if (is.null(minA)) minA_c <- rep(0,lw) else minA_c <- minA[w]
if (is.null(maxA)) maxA_c <- rep(+Inf,lw) else maxA_c <- maxA[w]
residuals <- function(A_c_new)
{
A_new <- A
A_new[w] <- A_c_new
X <- LSEI(A_new,B,E,F,G,H,Wa=Wb)$X
if (is.null(Wb)) return(c(Wa_c*(A_c-A_c_new),A_new%*%X-B))
return(c(Wa_c*(A_c-A_c_new),Wb*(A_new%*%X-B)))
}
tlsce_fit <- modFit(residuals,A_c,lower=minA_c,upper=maxA_c,...)
A_c_fit <- tlsce_fit$par
A_fit <- A; A_fit[w] <- A_c_fit
LSEI_fit <- LSEI(A_fit,B,E,F,G,H,Wa=Wb)
X <- LSEI_fit$X; rownames(X) <- colnames(A); colnames(X) <- colnames(B)
B_fit <- A_fit%*%X
ssr <- tlsce_fit$ssr
ssr_B <- LSEI_fit$solutionNorm
ssr_A <- ssr-ssr_B
solutionNorms <- c(ssr,ssr_A,ssr_B); names(solutionNorms) <- c("total","A","B")
return(list(X=X,
A_fit=A_fit,
B_fit=B_fit,
SS=solutionNorms,
fit=tlsce_fit))
}
LSEI <- function(A=NULL,B=NULL,E=NULL,F=NULL,G=NULL,H=NULL,Wa=NULL,...)
{
if (is.vector(B)) return(lsei(A,B,E,F,G,H,Wa=Wa,...))
else
{
X <- matrix(NA,ncol(A),ncol(B))
solutionNorm <- 0
for (i in 1:ncol(B))
{
BnotNA <- !is.na(B[,i])
ls <- lsei(A[BnotNA,],B[BnotNA,i],E,F[,i],G,H[,i],Wa=Wa[BnotNA,i],...)
X[,i] <- ls$X
solutionNorm <- solutionNorm + ls$solutionNorm
}
return(list(X=X,solutionNorm=solutionNorm))
}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
message = FALSE,
warning = FALSE,
fig.height = 7,
fig.width = 7,
dpi = 75
)
check_namespaces <- function(pkgs){
return(all(unlist(sapply(pkgs, requireNamespace,quietly = TRUE))))
}
library(geofi)
muni <- get_municipalities(year = 2019)
libs <- c("pxweb","dplyr","tidyr","janitor","ggplot2")
if (check_namespaces(pkgs = libs)) {
library(pxweb)
pxweb_query_list <-
list("Alue 2020"=c("*"),
"Tiedot"=c("*"),
"Vuosi"=c("2019"))
px_raw <-
pxweb_get(url = "https://pxnet2.stat.fi/PXWeb/api/v1/en/Kuntien_avainluvut/2020/kuntien_avainluvut_2020_aikasarja.px",
query = pxweb_query_list)
library(dplyr)
library(tidyr)
library(janitor)
library(sf)
px_data <- as_tibble(
as.data.frame(px_raw,
column.name.type = "text",
variable.value.type = "text")
) %>% setNames(make_clean_names(names(.))) %>%
pivot_longer(names_to = "information", values_to = "municipal_key_figures", 3:ncol(.))
px_data
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
if (check_namespaces(pkgs = libs)) {
count(px_data, region_2020)
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
if (check_namespaces(pkgs = libs)) {
map_data <- right_join(muni,
px_data,
by = c("municipality_name_fi" = "region_2020"))
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
if (check_namespaces(pkgs = libs)) {
library(ggplot2)
map_data %>%
filter(grepl("swedish|foreign", information)) %>%
ggplot(aes(fill = municipal_key_figures)) +
geom_sf() +
facet_wrap(~information) +
theme(legend.position = "top")
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
if (FALSE){
library(readr)
cols(
Area = col_character(),
Time = col_date(format = ""),
val = col_double()
) -> cov_cols
thl_korona_api <- "https://sampo.thl.fi/pivot/prod/en/epirapo/covid19case/fact_epirapo_covid19case.csv?row=dateweek20200101-508804L&column=hcdmunicipality2020-445222L"
status <- httr::status_code(httr::GET(thl_korona_api))
xdf_raw <- read_csv2(thl_korona_api, col_types = cov_cols)
xdf <- xdf_raw %>%
rename(date = Time,
shp = Area,
day_cases = val) %>%
group_by(shp) %>%
arrange(shp,date) %>%
filter(!is.na(day_cases)) %>%
mutate(total_cases = cumsum(day_cases)) %>%
ungroup() %>%
group_by(shp) %>%
filter(date == max(date, na.rm = TRUE)) %>%
ungroup()
}
xdf <- structure(list(shp = c("Åland", "All areas", "Central Finland Hospital District",
"Central Ostrobothnia Hospital District", "Helsinki and Uusimaa Hospital District",
"Itä-Savo Hospital District", "Kainuu Hospital District", "Kanta-Häme Hospital District",
"Kymenlaakso Hospital District", "Länsi-Pohja Hospital District",
"Lappi Hospital District", "North Karelia Hospital District",
"North Ostrobothnia Hospital District", "North Savo Hospital District",
"Päijät-Häme Hospital District", "Pirkanmaa Hospital District",
"Satakunta Hospital District", "South Karelia Hospital District",
"South Ostrobothnia Hospital District", "South Savo Hospital District",
"Southwest Finland Hospital District", "Vaasa Hospital District"
), date = structure(c(18674, 18674, 18674, 18674, 18674, 18674,
18674, 18674, 18674, 18674, 18674, 18674, 18674, 18674, 18674,
18674, 18674, 18674, 18674, 18674, 18674, 18674), class = "Date"),
day_cases = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0), total_cases = c(120, 51047, 1850, 177,
29519, 141, 227, 873, 854, 478, 465, 516, 2265, 850, 1243,
2662, 671, 348, 534, 573, 4803, 1878)), row.names = c(NA,
-22L), class = c("tbl_df", "tbl", "data.frame"))
xdf %>%
count(shp)
muni <- get_municipalities(year = 2021)
muni %>%
st_drop_geometry() %>%
count(sairaanhoitop_name_en)
libs <- c("ggplot2")
if (check_namespaces(pkgs = libs)) {
muni %>%
count(sairaanhoitop_name_en) %>%
left_join(xdf, by = c("sairaanhoitop_name_en" = "shp")) %>%
ggplot(aes(fill = total_cases)) +
geom_sf() +
geom_sf_text(aes(label = paste0(sairaanhoitop_name_en, "\n", total_cases)),
color = "white") +
labs(title = "Number of total COVID-19 cases reported since January 2020",
fill = NULL)
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
libs <- c("ggplot2","pxweb","janitor")
if (check_namespaces(pkgs = libs)) {
library(pxweb)
pxweb_query_list <-
list("Postinumeroalue"=c("*"),
"Tiedot"=c("*"))
px_raw <-
pxweb_get(url = "https://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2019/paavo_1_he_2019.px",
query = pxweb_query_list)
px_data <- as_tibble(
as.data.frame(px_raw,
column.name.type = "text",
variable.value.type = "text")
) %>% setNames(make_clean_names(names(.)))
px_data %>%
filter(postal_code_area != "Finland")
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
libs <- c("ggplot2","pxweb","janitor")
if (check_namespaces(pkgs = libs)) {
px_data$posti_alue <- sub(" .+$", "", px_data$postal_code_area)
zipcodes19 <- get_zipcodes(year = 2019)
zipcodes_map <- left_join(zipcodes19,
px_data %>% filter(data == "Average age of inhabitants, 2017 (HE)"))
ggplot(zipcodes_map) +
geom_sf(aes(fill = paavo_open_data_by_postal_code_area_2019),
color = alpha("white", 1/3)) +
labs(title = "Average age of inhabitants, 2017 (HE)",
fill = NULL)
} else {
message("One or more of the following packages is not available: ",
paste(libs, collapse = ", "))
}
|
dufour_etal <- function(mainlm, hettest, R = 1000L, alternative = c("greater",
"less", "two.sided"), errorgen = stats::rnorm,
errorparam = list(), seed = 1234, ...) {
alternative <- match.arg(alternative, c("greater", "less", "two.sided"))
if (is.character(hettest)) {
hettestfunc <- get(hettest)
} else {
stop("hettest must be a character naming a function")
}
if (is.character(errorgen)) errorgen <- get(errorgen)
arguments <- list(...)
invisible(list2env(arguments, envir = environment()))
if ("alternative" %in% names(formals(hettestfunc)))
arguments$alternative <- alternative
processmainlm(m = mainlm)
n <- length(e)
if (hettest == "horn") {
if (exists("exact", where = environment(), inherits = FALSE)) {
if (exact) stop("This method is only available for tests with a continuous test statistic")
} else {
if (n - p <= 11) stop("This method is only available for tests with a continuous test statistic")
}
} else if (hettest %in% c("anscombe", "bickel", "wilcox_keselman")) {
stop("This method is only available for tests that are invariant with respect
to nuisance parameters and for which the test statistic can be computed
based only on the design matrix and the OLS residuals.")
} else if (hettest == "simonoff_tsai") {
if (!exists("method", where = environment(), inherits = FALSE)) {
stop("This function is only available for hettest `simonoff_tsai` with `method` argument set to \"score\".")
} else if (method != "score") {
stop("This function is only available for hettest `simonoff_tsai` with `method` argument set to \"score\".")
}
} else if (hettest == "zhou_etal" && p > 2) {
if (exists("method", where = environment(), inherits = FALSE)) {
if (method %in% c("covariate-specific", "hybrid")) {
stop("`zhou_etal` cannot be used in godfrey_orme with method \"covariate-specific\" or \"hybrid\" when model has more than two covariates")
}
}
}
if (exists("deflator", where = environment(), inherits = FALSE)) {
if (is.character(deflator))
arguments$deflator <- which(colnames(X) == deflator)
}
statobs <- do.call(what = hettestfunc,
args = append(list("mainlm" = list("y" = y, "X" = X),
"statonly" = TRUE), arguments))
if (!(hettest == "goldfeld_quandt")) {
M <- fastM(X, n)
if (!is.na(seed)) set.seed(seed)
epsgen <- replicate(R, do.call(errorgen, c("n" = n, errorparam)),
simplify = FALSE)
egen <- lapply(epsgen, function(eps) M %*% eps)
statgen <- vapply(1:R, function(j) do.call(what = hettestfunc,
args = append(list("mainlm" = list("X" = X, "e" = egen[[j]]),
"statonly" = TRUE), arguments)), NA_real_)
} else {
if (exists("method", where = environment(), inherits = FALSE)) {
method <- match.arg(method, c("parametric", "nonparametric"))
if (method == "nonparametric") stop("This method is only available for tests with a continuous test statistic")
}
if (!is.na(seed)) set.seed(seed)
epsgen <- replicate(R, do.call(errorgen, c("n" = n, errorparam)),
simplify = FALSE)
hasintercept <- columnof1s(X)
if (class(mainlm) == "list") {
if (hasintercept[[1]]) {
if (hasintercept[[2]] != 1) stop("Column of 1's must be first column of design matrix")
colnames(X) <- c("(Intercept)", paste0("X", 1:(p - 1)))
} else {
colnames(X) <- paste0("X", 1:p)
}
}
if (!exists("deflator", where = environment(), inherits = FALSE)) deflator <- NA
if (!exists("prop_central", where = environment(), inherits = FALSE)) prop_central <- 1 / 3
if (!exists("group1prop", where = environment(), inherits = FALSE)) group1prop <- 1 / 2
checkdeflator(deflator, X, p, hasintercept[[1]])
theind <- gqind(n, p, prop_central, group1prop)
if (!is.na(deflator) && !is.null(deflator)) {
if (!is.na(suppressWarnings(as.integer(deflator)))) {
deflator <- as.integer(deflator)
}
X <- X[order(X[, deflator]), , drop = FALSE]
}
M1 <- fastM(X[theind[[1]], , drop = FALSE], length(theind[[1]]))
M2 <- fastM(X[theind[[2]], , drop = FALSE], length(theind[[2]]))
thedf2 <- (length(theind[[2]]) - p)
thedf1 <- (length(theind[[1]]) - p)
egen1 <- lapply(epsgen, function(eps) M1 %*% eps[theind[[1]]])
egen2 <- lapply(epsgen, function(eps) M2 %*% eps[theind[[2]]])
statgen <- unlist(mapply(FUN = function(e1, e2)
(sum(e2 ^ 2) / thedf2) / (sum(e1 ^ 2) / thedf1), egen1, egen2,
SIMPLIFY = FALSE))
}
if (alternative == "greater") {
teststat <- sum(statgen >= statobs)
} else if (alternative == "less") {
teststat <- sum(statgen <= statobs)
} else if (alternative == "two.sided") {
teststat <- min(sum(statgen >= statobs),
sum(statgen <= statobs))
}
pval <- (teststat + 1) / (R + 1) *
ifelse(alternative == "two.sided", 2, 1)
rval <- structure(list(statistic = teststat, parameter = R, p.value = pval,
null.value = "Homoskedasticity",
alternative = alternative, method = "Monte Carlo"),
class = "htest")
broom::tidy(rval)
}
|
NLDoCommandWhile <-
function(condition, ..., max.minutes=10, nl.obj=NULL)
{
if (is.null(nl.obj))
{
nl.obj <- "_nl.intern_"
}
if (nl.obj %in% .rnetlogo$objects) {
nl.obj <- get(nl.obj, envir=.rnetlogo)
} else {
stop(paste('There is no NetLogo reference stored under the name ',nl.obj,".", sep=""))
}
commands <- lapply(list(...), function(x) {eval.commandobject(x)})
command <- paste(commands, collapse=" ")
.jcall(nl.obj, "V", "doCommandWhile", .jnew("java/lang/String", command), .jnew("java/lang/String", condition), .jnew("java/lang/Integer", as.integer(max.minutes)))
if (!is.null(e<-.jgetEx()))
{
if (.jcheck(silent=TRUE))
{
print(e)
stop()
}
}
}
|
library(shiny)
library(shinyWidgets)
ui <- fluidPage(
tags$h1("Update pretty radio buttons"),
br(),
fluidRow(
column(
width = 6,
prettyRadioButtons(
inputId = "radio1",
label = "Update my value!",
choices = month.name[1:4],
status = "danger",
icon = icon("remove")
),
verbatimTextOutput(outputId = "res1"),
br(),
radioButtons(
inputId = "update1", label = "Update value :",
choices = month.name[1:4], inline = TRUE
)
),
column(
width = 6,
prettyRadioButtons(
inputId = "radio2",
label = "Update my choices!",
thick = TRUE,
choices = month.name[1:4],
animation = "pulse",
status = "info"
),
verbatimTextOutput(outputId = "res2"),
br(),
actionButton(inputId = "update2", label = "Update choices !")
)
)
)
server <- function(input, output, session) {
output$res1 <- renderPrint(input$radio1)
observeEvent(input$update1, {
updatePrettyRadioButtons(
session = session,
inputId = "radio1",
selected = input$update1
)
}, ignoreNULL = FALSE)
output$res2 <- renderPrint(input$radio2)
observeEvent(input$update2, {
updatePrettyRadioButtons(
session = session,
inputId = "radio2",
choices = sample(month.name, 4),
prettyOptions = list(animation = "pulse",
status = "info",
shape = "round")
)
}, ignoreInit = TRUE)
}
if (interactive())
shinyApp(ui, server)
|
HWidentify <- function(x,y,label=seq_along(x), lab.col='darkgreen',
pt.col='red', adj=c(0,0), clean=TRUE,
xlab=deparse(substitute(x)),
ylab=deparse(substitute(y)), ...) {
plot(x,y,xlab=xlab, ylab=ylab,...)
dx <- grconvertX(x,to='ndc')
dy <- grconvertY(y,to='ndc')
mm <- function(buttons, xx, yy) {
d <- (xx-dx)^2 + (yy-dy)^2
if ( all( d > .01 ) ){
plot(x,y,xlab=xlab,ylab=ylab,...)
return()
}
w <- which.min(d)
plot(x,y,xlab=xlab,ylab=ylab,...)
points(x[w],y[w], cex=2, col=pt.col)
text(grconvertX(xx,from='ndc'),grconvertY(yy,from='ndc'),
label[w], col=lab.col, adj=adj)
return()
}
md <- function(buttons, xx, yy) {
if (any(buttons=='2')) return(1)
return()
}
getGraphicsEvent('Right Click to exit', onMouseMove = mm, onMouseDown=md)
if(clean) mm( , Inf, Inf )
invisible()
}
HTKidentify <- function(x,y,label=seq_along(x), lab.col='darkgreen',
pt.col='red', adj=c(0,0),
xlab=deparse(substitute(x)),
ylab=deparse(substitute(y)), ...) {
if( !requireNamespace("tkrplot", quietly=TRUE) ) stop ('tkrplot package is required')
dx <- numeric(0)
dy <- numeric(0)
xx <- yy <- 0
replot <- function() {
d <- (xx-dx)^2 + (yy-dy)^2
if ( all( d > .01 ) ) {
plot(x,y,xlab=xlab,ylab=ylab,...)
if( length(dx)==0 ) {
dx <<- grconvertX(x, to='ndc')
dy <<- grconvertY(y, to='ndc')
}
return()
}
w <- which.min(d)
plot(x,y,xlab=xlab,ylab=ylab,...)
points(x[w],y[w], cex=2, col=pt.col)
text(grconvertX(xx,from='ndc'),grconvertY(yy,from='ndc'),
label[w], col=lab.col, adj=adj)
}
tt <- tcltk::tktoplevel()
img <- tkrplot::tkrplot(tt, replot, hscale=1.5, vscale=1.5)
tcltk::tkpack(img, side='top')
iw <- as.numeric(tcltk::tcl("image","width", tcltk::tkcget(img, "-image")))
ih <- as.numeric(tcltk::tcl("image","height", tcltk::tkcget(img, "-image")))
cc <- function(x,y) {
x <- (as.double(x) -1)/iw
y <- 1-(as.double(y)-1)/ih
c(x,y)
}
mm <- function(x, y) {
xy <- cc(x,y)
xx <<- xy[1]
yy <<- xy[2]
tkrplot::tkrreplot(img)
}
tcltk::tkbind(img, "<Motion>", mm)
invisible()
}
|
phi = function(x, y=NULL,
ci=FALSE, conf=0.95, type="perc",
R=1000, histogram=FALSE, verbose=FALSE,
digits=3,
reportIncomplete=FALSE, ...) {
PHI=NULL
if(is.factor(x)){x=as.vector(x)}
if(is.factor(y)){x=as.vector(y)}
if(is.vector(x) & is.vector(y)){
if((length(unique(x)) != 2) || (length(unique(y)) != 2))
{stop("phi is applicable only for 2 binomial variables")}
Tab = xtabs(~ x + y)
}
if(is.matrix(x)){Tab=as.table(x)}
if(is.table(x)){Tab = x}
if((nrow(Tab) != 2) || (ncol(Tab) != 2))
{stop("phi is applicable only for a 2 x 2 table")}
if(verbose){print(Tab) ;cat("\n")}
Tab2 = Tab / sum(Tab)
a=Tab2[1,1]; b=Tab2[1,2]; c=Tab2[2,1]; d=Tab2[2,2]
PHI = (a- (a+b)*(a+c))/sqrt((a+b)*(c+d)*(a+c)*(b+d) )
Phi= signif(as.numeric(PHI), digits=digits)
if(is.nan(Phi) & ci==TRUE){
return(data.frame(phi=Phi, lower.ci=NA, upper.ci=NA))}
if(ci==TRUE){
Counts = as.data.frame(Tab)
Long = Counts[rep(row.names(Counts), Counts$Freq), c(1, 2)]
rownames(Long) = seq(1:nrow(Long))
L1 = length(unique(droplevels(Long[,1])))
L2 = length(unique(droplevels(Long[,2])))
Function = function(input, index){
Input = input[index,]
NOTEQUAL=0
if(length(unique(droplevels(Input[,1]))) != L1 |
length(unique(droplevels(Input[,2]))) != L2){NOTEQUAL=1}
if(NOTEQUAL==1){FLAG=1; return(c(NA,FLAG))}
if(NOTEQUAL==0){
Tab = xtabs(~ Input[,1] + Input[,2])
Tab2 = Tab / sum(Tab)
a=Tab2[1,1]; b=Tab2[1,2]; c=Tab2[2,1]; d=Tab2[2,2]
PHI = (a- (a+b)*(a+c))/sqrt((a+b)*(c+d)*(a+c)*(b+d))
FLAG = 0
return(c(PHI,FLAG))}
}
Boot = boot(Long, Function, R=R)
BCI = boot.ci(Boot, conf=conf, type=type)
if(type=="norm") {CI1=BCI$normal[2]; CI2=BCI$normal[3]}
if(type=="basic"){CI1=BCI$basic[4]; CI2=BCI$basic[5]}
if(type=="perc") {CI1=BCI$percent[4]; CI2=BCI$percent[5]}
if(type=="bca") {CI1=BCI$bca[4]; CI2=BCI$bca[5]}
if(sum(Boot$t[,2])>0 & reportIncomplete==FALSE) {CI1=NA; CI2=NA}
CI1=signif(CI1, digits=digits)
CI2=signif(CI2, digits=digits)
if(histogram==TRUE){hist(Boot$t[,1], col = "darkgray", xlab="phi", main="")}
}
if(ci==FALSE){names(Phi)="phi"; return(Phi)}
if(ci==TRUE){return(data.frame(phi=Phi, lower.ci=CI1, upper.ci=CI2))}
}
|
library(hgutils)
load_packages("stringr","magrittr")
cols = list(orange="orange",blue="blue",red="red")
col = cols$blue
packages = c("metafor","shiny","ggplot2","mice","rms","magrittr","dplyr","hgutils")
txts = sapply(packages, function(x) paste0(x,"-",str_replace_all(packageDescription(x)$Version,"-","--")))
urls = paste0("https://img.shields.io/badge/",txts,"-",col,".png")
for(i in 1:length(urls)) {
download.file(urls[i],paste0("tools/output/",packages[i],".png"),mode="wb")
}
|
NULL
if (!methods::isClass("Weight")) methods::setOldClass("Weight")
NULL
NULL
Weight <- pproto("Weight", ProjectModifier)
add_default_weights <- function(x) {
assertthat::assert_that(inherits(x, "ProjectProblem"),
!is.Waiver(x$objective))
add_feature_weights(x, x$objective$default_feature_weights())
}
|
item_upload_create = function(parent_id, files, ..., scrape_files = TRUE, session=current_session()){
if(length(files) > 50){
warning('Trying to attach a large number of files to a SB item. SB imposes file limits which may cause this to fail')
}
item <- as.sbitem(parent_id)
params <- '?title=title'
if(!scrape_files) {
params <- paste0(params, '&scrapeFile=false')
}
r = sbtools_POST(url = paste0(pkg.env$url_upload_create, item$id, params),
...,
body = multi_file_body(files),
session = session)
if (grepl('josso/signon', r$url)) {
stop('Not authenticated or lack of permission to parent object\nAunthenticate with the authenticate_sb function.')
}
item <- as.sbitem(content(r))
return(check_upload(item, files))
}
item_append_files = function(sb_id, files, ..., scrape_files = TRUE, session=current_session()){
if(length(files) > 50){
warning('Trying to attach a large number of files to a SB item. SB imposes file limits which may cause this to fail')
}
item <- as.sbitem(sb_id)
if(is.null(item)) return(NULL)
params <- paste0("?id=", item$id)
if(!scrape_files) {
params <- paste0(params, "&scrapeFile=false")
}
r = sbtools_POST(url = paste0(pkg.env$url_upload, params), ...,
body = multi_file_body(files),
session = session)
item <- as.sbitem(content(r))
return(check_upload(item, files))
}
check_upload <- function(item, files) {
if(!all(basename(files) %in% sapply(item$files, function(x) x$name))) {
warning("Not all files ended up in the item files. \n",
"This indicates that a sciencebase extension was created with the file. \n",
"set 'scrape_files' to FALSE to avoid this behavior. \n",
"NOTE: 'scrape_files' will default to FALSE in a future version of sbtools.")
}
item
}
multi_file_body <- function(files){
body = list()
for(i in 1:length(files)){
if(!file.exists(files[i])){
stop('This file does not exist or cannot be accessed: ', files[i])
}
body[[paste0('file', i)]] = upload_file(files[i])
}
names(body) = rep('file', length(body))
return(body)
}
|
AmerPutLSM <-
function (Spot=1, sigma=0.2, n=1000, m=365, Strike=1.1, r=0.06, dr=0.0, mT=1) {
GBM<-matrix(NA, nrow=n, ncol=m)
for(i in 1:n) {
GBM[i,]<-Spot*exp(cumsum(((r-dr)*(mT/m)-0.5*sigma*sigma*(mT/m))+(sigma*(sqrt(mT/m))*rnorm(m, mean= 0, sd=1))))
}
X<-ifelse(GBM<Strike,GBM,NA)
CFL<-matrix(pmax(0,Strike-GBM), nrow=n, ncol=m)
Xsh<-X[,-m]
X2sh<-Xsh*Xsh
Y1<-CFL*exp(-1*r*(mT/m))
Y2<-cbind((matrix(NA, nrow=n, ncol=m-1)), Y1[,m])
CV<-matrix(NA, nrow=n, ncol=m-1)
try(for(i in (m-1):1) {
reg1<-lm(Y2[,i+1]~Xsh[,i]+X2sh[,i])
CV[,i]<-(matrix(reg1$coefficients)[1,1])+((matrix(reg1$coefficients)[2,1])*Xsh[,i])+((matrix(reg1$coefficients)[3,1])*X2sh[,i])
CV[,i]<-(ifelse(is.na(CV[,i]),0,CV[,i]))
Y2[,i]<-ifelse(CFL[,i]>CV[,i], Y1[,i], Y2[,i+1]*exp(-1*r*(mT/m)))
}
, silent = TRUE)
CV<-ifelse(is.na(CV),0,CV)
CVp<-cbind(CV, (matrix(0, nrow=n, ncol=1)))
POF<-ifelse(CVp>CFL,0,CFL)
FPOF<-firstValueRow(POF)
dFPOF<-matrix(NA, nrow=n, ncol=m)
for(i in 1:m) {
dFPOF[,i]<-FPOF[,i]*exp(-1*mT/m*r*i)
}
PRICE<-mean(rowSums(dFPOF))
res<- list(price=(PRICE), Spot, Strike, sigma, n, m, r, dr, mT)
class(res)<-"AmerPut"
return(res)
}
|
plot.cv.ncvreg <- function(x, log.l=TRUE, type=c("cve", "rsq", "scale", "snr", "pred", "all"), selected=TRUE, vertical.line=TRUE, col="red", ...) {
type <- match.arg(type)
if (type=="all") {
plot(x, log.l=log.l, type="cve", selected=selected, ...)
plot(x, log.l=log.l, type="rsq", selected=selected, ...)
plot(x, log.l=log.l, type="snr", selected=selected, ...)
if (length(x$fit$family)) {
if (x$fit$family == "binomial") plot(x, log.l=log.l, type="pred", selected=selected, ...)
if (x$fit$family == "gaussian") plot(x, log.l=log.l, type="scale", selected=selected, ...)
}
return(invisible(NULL))
}
l <- x$lambda
if (log.l) {
l <- log(l)
xlab <- expression(log(lambda))
} else xlab <- expression(lambda)
L.cve <- x$cve - x$cvse
U.cve <- x$cve + x$cvse
if (type=="cve") {
y <- x$cve
L <- L.cve
U <- U.cve
ylab <- "Cross-validation error"
} else if (type=="rsq" | type == "snr") {
if (length(x$fit$family) && x$fit$family=='gaussian') {
rsq <- pmin(pmax(1 - x$cve/x$null.dev, 0), 1)
rsql <- pmin(pmax(1 - U.cve/x$null.dev, 0), 1)
rsqu <- pmin(pmax(1 - L.cve/x$null.dev, 0), 1)
} else {
rsq <- pmin(pmax(1 - exp(x$cve-x$null.dev), 0), 1)
rsql <- pmin(pmax(1 - exp(U.cve-x$null.dev), 0), 1)
rsqu <- pmin(pmax(1 - exp(L.cve-x$null.dev), 0), 1)
}
if (type == "rsq") {
y <- rsq
L <- rsql
U <- rsqu
ylab <- ~R^2
} else if(type=="snr") {
y <- rsq/(1-rsq)
L <- rsql/(1-rsql)
U <- rsqu/(1-rsqu)
ylab <- "Signal-to-noise ratio"
}
} else if (type=="scale") {
if (x$fit$family == "binomial") stop("Scale parameter for binomial family fixed at 1", call.=FALSE)
y <- sqrt(x$cve)
L <- sqrt(L.cve)
U <- sqrt(U.cve)
ylab <- ~hat(sigma)
} else if (type=="pred") {
y <- x$pe
n <- x$fit$n
CI <- sapply(y, function(x) {binom.test(x*n, n, conf.level=0.68)$conf.int})
L <- CI[1,]
U <- CI[2,]
ylab <- "Prediction error"
}
ind <- if (type=="pred") which(is.finite(l[1:length(x$pe)])) else which(is.finite(l[1:length(x$cve)]))
ylim <- if (is.null(x$cvse)) range(y[ind]) else range(c(L[ind], U[ind]))
aind <- intersect(ind, which((U-L)/diff(ylim) > 1e-3))
plot.args = list(x=l[ind], y=y[ind], ylim=ylim, xlab=xlab, ylab=ylab, type="n", xlim=rev(range(l[ind])), las=1)
new.args = list(...)
if (length(new.args)) plot.args[names(new.args)] = new.args
do.call("plot", plot.args)
if (vertical.line) abline(v=l[x$min], lty=2, lwd=.5)
suppressWarnings(arrows(x0=l[aind], x1=l[aind], y0=L[aind], y1=U[aind], code=3, angle=90, col="gray80", length=.05))
points(l[ind], y[ind], col=col, pch=19, cex=.5)
if (selected) {
n.s <- predict(x$fit, lambda=x$lambda, type="nvars")
axis(3, at=l, labels=n.s, tick=FALSE, line=-0.5)
mtext("Variables selected", cex=0.8, line=1.5)
}
}
|
tokenizer_set <- function(conn, index, body, ...) {
is_conn(conn)
if (length(index) > 1) stop("Only one index allowed", call. = FALSE)
url <- conn$make_url()
url <- sprintf("%s/%s", url, esc(index))
tokenizer_PUT(conn, url, body, ...)
}
tokenizer_PUT <- function(conn, url, body, ...){
body <- check_inputs(body)
out <- conn$make_conn(url, json_type(), ...)$put(
body = body, encode = "json")
if (out$status_code > 202) geterror(conn, out)
if (conn$warn) catch_warnings(out)
jsonlite::fromJSON(out$parse('UTF-8'))
}
|
.onAttach <- function(libname, pkgname){
if (!interactive()) return()
Rcmdr <- options()$Rcmdr
plugins <- Rcmdr$plugins
options(list(".RcmdrPlugin.orloca.l2" = T))
options(list(".RcmdrPlugin.orloca.lp" = NA))
if (!pkgname %in% plugins) {
Rcmdr$plugins <- c(plugins, pkgname)
options(Rcmdr=Rcmdr)
if("package:Rcmdr" %in% search()) {
if(!getRcmdr("autoRestart")) {
closeCommander(ask=FALSE, ask.save=TRUE)
Commander()
}
}
else {
Commander()
}
}
}
.RcmdrPlugin.orloca.get.norma <- function(sep=",")
{
l2 <- options(".RcmdrPlugin.orloca.l2")
command <- ""
if (l2 != TRUE)
{
lp <- options(".RcmdrPlugin.orloca.lp")
command <- paste(sep, " lp = ", lp, sep="")
}
command
}
gettext("Planar location", domain="R-RcmdrPlugin.orloca")
Rcmdr.new.loca.p <- function(){
initializeDialog(title=gettext("New loca.p", domain="R-RcmdrPlugin.orloca"))
nameVar <- tclVar(gettextRcmdr("Data"))
nameEntry <- tkentry(top, width="8", textvariable=nameVar)
onOK <- function(){
closeDialog()
name <- tclvalue(nameVar)
if (!is.valid.name(name)) {
errorCondition(recall=Rcmdr.new.loca.p, message=paste('"', name, '" ', gettextRcmdr("is not a valid name."), sep=""))
return()
}
if (is.element(name, listDataSets()))
{
if ("no" == tclvalue(checkReplace(name, gettextRcmdr("Data set"))))
{
errorCondition(recall=Rcmdr.new.loca.p, message=gettextRcmdr("Introduce the name (another) for the new data.frame."))
return()
}
}
command <- paste(name, "<- edit(data.frame(x=numeric(0), y=numeric(0), w=numeric(0)))")
doItAndPrint(command)
if (nrow(get(name)) == 0){
errorCondition(recall=Rcmdr.new.loca.p, message=gettextRcmdr("empty data set."))
return()
}
activeDataSet(name)
closeDialog()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="loca.p")
tkgrid(tklabel(top, text=gettext("Name of new loca.p object", domain="R-RcmdrPlugin.orloca")), nameEntry, sticky="e")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
tkgrid.configure(nameEntry, sticky="w")
dialogSuffix(rows=2, columns=2, focus=nameEntry)
}
Rcmdr.rloca.p <- function(){
initializeDialog(title=gettext("New loca.p Random Instance", domain="R-RcmdrPlugin.orloca"))
nameVar <- tclVar(gettextRcmdr("Data"))
nameEntry <- tkentry(top, width="8", textvariable=nameVar)
nVar <- tclVar("100")
nEntry <- tkentry(top, width="8", textvariable=nVar)
xminVar <- tclVar("0")
xminEntry <- tkentry(top, width="8", textvariable=xminVar)
xmaxVar <- tclVar("1")
xmaxEntry <- tkentry(top, width="8", textvariable=xmaxVar)
yminVar <- tclVar("0")
yminEntry <- tkentry(top, width="8", textvariable=yminVar)
ymaxVar <- tclVar("1")
ymaxEntry <- tkentry(top, width="8", textvariable=ymaxVar)
groupsVar <- tclVar("0")
groupsEntry <- tkentry(top, width="8", textvariable=groupsVar)
onOK <- function(){
closeDialog()
name <- tclvalue(nameVar)
if (!is.valid.name(name)) {
errorCondition(recall=Rcmdr.rloca.p, message=paste('"', name, '" ', gettextRcmdr("is not a valid name."), sep=""))
return()
}
if (is.element(name, listDataSets()))
{
if ("no" == tclvalue(checkReplace(name, gettextRcmdr("Data set"))))
{
errorCondition(recall=Rcmdr.rloca.p, message=gettextRcmdr("Introduce the name (another) for the new data.frame."))
return()
}
}
n <- round(as.numeric(tclvalue(nVar)))
if (is.na(n) || n <= 0){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("The number of demand points must be a positive integer.", domain="R-RcmdrPlugin.orloca"))
return()
}
xmin <- as.numeric(tclvalue(xminVar))
if (is.na(xmin)){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("xmin must be a real number.", domain="R-RcmdrPlugin.orloca"))
return()
}
xmax <- as.numeric(tclvalue(xmaxVar))
if (is.na(xmax) || xmax < xmin){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("xmax must be a real number bigger that xmin.", domain="R-RcmdrPlugin.orloca"))
return()
}
ymin <- as.numeric(tclvalue(yminVar))
if (is.na(ymin)){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("ymin must be a real number.", domain="R-RcmdrPlugin.orloca"))
return()
}
ymax <- as.numeric(tclvalue(ymaxVar))
if (is.na(ymax) || ymax < ymin){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("ymax must be a real number bigger that ymin.", domain="R-RcmdrPlugin.orloca"))
return()
}
groups <- round(as.numeric(tclvalue(groupsVar)))
if (is.na(groups) || groups < 0){
errorCondition(recall=Rcmdr.rloca.p, message=gettext("groups must be a non negative integer.", domain="R-RcmdrPlugin.orloca"))
return()
}
command <- paste(name, " <- rloca.p(n = ", n,", xmin = ", xmin,", xmax = ", xmax,", ymin = ", ymin,", ymax = ", ymax,", groups = ", groups,")", sep="")
doItAndPrint(command)
command <- paste(name, " <- as(", name, ", \"data.frame\")", sep="")
doItAndPrint(command)
activeDataSet(name)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="rloca.p")
tkgrid(tklabel(top, text=gettext("Name of new loca.p object", domain="R-RcmdrPlugin.orloca")), nameEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("Number of demand points", domain="R-RcmdrPlugin.orloca")), nEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("x Minimum", domain="R-RcmdrPlugin.orloca")), xminEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("x Maximum", domain="R-RcmdrPlugin.orloca")), xmaxEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("y Minimum", domain="R-RcmdrPlugin.orloca")), yminEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("y Maximum", domain="R-RcmdrPlugin.orloca")), ymaxEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("Number of groups", domain="R-RcmdrPlugin.orloca")), groupsEntry, sticky="e")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
tkgrid.configure(nameEntry, sticky="w")
tkgrid.configure(nEntry, sticky="w")
tkgrid.configure(xminEntry, sticky="w")
tkgrid.configure(xmaxEntry, sticky="w")
tkgrid.configure(yminEntry, sticky="w")
tkgrid.configure(ymaxEntry, sticky="w")
tkgrid.configure(groupsEntry, sticky="w")
dialogSuffix(rows=7, columns=2, focus=nEntry)
}
Rcmdr.distsum <- function(){
initializeDialog(title=gettext("Evaluation of Objective Function for weighted sum Location Problem", domain="R-RcmdrPlugin.orloca"))
xVar <- tclVar("0")
xEntry <- tkentry(top, width="6", textvariable=xVar)
yVar <- tclVar("0")
yEntry <- tkentry(top, width="6", textvariable=yVar)
onOK <- function(){
closeDialog()
x <- as.numeric(tclvalue(xVar))
if (is.na(x)){
errorCondition(recall=Rcmdr.distsum, message=gettext("x-axis must be a number.", domain="R-RcmdrPlugin.orloca"))
return()
}
y <- as.numeric(tclvalue(yVar))
if (is.na(y)){
errorCondition(recall=Rcmdr.distsum, message=gettext("y-axis must be a number.", domain="R-RcmdrPlugin.orloca"))
return()
}
command <- paste("distsum(as(", ActiveDataSet(), ", \"loca.p\") , x = ", x,", y = ", y, sep="")
command <- paste(command, .RcmdrPlugin.orloca.get.norma(), sep="")
command <- paste(command, ") \n
command <- paste(command, gettext("Weighted sum of distances", domain="R-RcmdrPlugin.orloca"), sep="")
doItAndPrint(command)
command <- paste("distsumgra(as(", ActiveDataSet(), ", \"loca.p\") , x = ", x,", y = ", y, sep="")
command <- paste(command, .RcmdrPlugin.orloca.get.norma(), sep="")
command <- paste(command, ")
command <- paste(command, gettext("Gradient of the weighted sum of distances function", domain="R-RcmdrPlugin.orloca"), sep="")
doItAndPrint(command)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="distsum")
tkgrid(tklabel(top, text=gettext("x-axis", domain="R-RcmdrPlugin.orloca")), xEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("y-axis", domain="R-RcmdrPlugin.orloca")), yEntry, sticky="e")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
tkgrid.configure(xEntry, sticky="w")
tkgrid.configure(yEntry, sticky="w")
dialogSuffix(rows=2, columns=2, focus=xEntry)
}
Rcmdr.distsummin <- function(){
initializeDialog(title=gettext("Solve weighted sum Location Problem", domain="R-RcmdrPlugin.orloca"))
xVar <- tclVar("0")
xEntry <- tkentry(top, width="6", textvariable=xVar)
yVar <- tclVar("0")
yEntry <- tkentry(top, width="6", textvariable=yVar)
nVar <- tclVar("100")
nEntry <- tkentry(top, width="6", textvariable=nVar)
epsVar <- tclVar("0.001")
epsEntry <- tkentry(top, width="6", textvariable=epsVar)
gettext("Gradient", domain="R-RcmdrPlugin.orloca")
gettext("Search method", domain="R-RcmdrPlugin.orloca")
radioButtons(name="algorithm", buttons=c("Weiszfeld", "gradient", "ucminf", "NelderMead", "BFGS", "CG", "LBFGSB", "SANN"), values=c("Weiszfeld", "gradient", "ucminf", "Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN"), initialValue="Weiszfeld", labels=gettext(c("Weiszfeld", "gradient", "ucminf", "Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN"), domain="R-RcmdrPlugin.orloca"), title=gettext("Select algorithm", domain="R-RcmdrPlugin.orloca"))
onOK <- function(){
closeDialog()
x <- as.numeric(tclvalue(xVar))
if (is.na(x)){
errorCondition(recall=Rcmdr.distsummin, message=gettext("x-axis must be a number.", domain="R-RcmdrPlugin.orloca"))
return()
}
y <- as.numeric(tclvalue(yVar))
if (is.na(y)){
errorCondition(recall=Rcmdr.distsummin, message=gettext("y-axis must be a number.", domain="R-RcmdrPlugin.orloca"))
return()
}
n <- as.numeric(tclvalue(nVar))
if (is.na(n) || n <= 0){
errorCondition(recall=Rcmdr.distsummin, message=gettext("The maximum number of iterations must be a positive integer", domain="R-RcmdrPlugin.orloca"))
return()
}
eps <- as.numeric(tclvalue(epsVar))
if (is.na(eps) || eps <= 0){
errorCondition(recall=Rcmdr.distsummin, message=gettext("The norm of the gradient must be positive.", domain="R-RcmdrPlugin.orloca"))
return()
}
algorithm <- tclvalue(algorithmVariable)
command <- paste(".sol <- distsummin(as(", ActiveDataSet(), ", \"loca.p\") , x = ", x,", y = ", y,", eps =", eps, ", algorithm =\"", algorithm, "\"", sep="")
command <- paste(command, .RcmdrPlugin.orloca.get.norma(), " )
doItAndPrint(command)
doItAndPrint(paste(".sol
command <- paste("distsum(as(", ActiveDataSet(), ", \"loca.p\") , x =", .sol[1], ", y = ", .sol[2], wep="")
command <- paste(command, .RcmdrPlugin.orloca.get.norma(), sep="")
command <- paste(command, ")
doItAndPrint(command)
doItAndPrint("remove(.sol)")
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="distsummin")
tkgrid(tklabel(top, text=gettext("Maximum number of iterations", domain="R-RcmdrPlugin.orloca")), nEntry, sticky="w")
tkgrid.configure(nEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("x-axis", domain="R-RcmdrPlugin.orloca")), xEntry, sticky="w")
tkgrid.configure(xEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("y-axis", domain="R-RcmdrPlugin.orloca")), yEntry, sticky="w")
tkgrid.configure(yEntry, sticky="e")
tkgrid(tklabel(top, text=gettext("Maximum gradient norm", domain="R-RcmdrPlugin.orloca")), epsEntry, sticky="w")
tkgrid.configure(epsEntry, sticky="e")
tkgrid.configure(algorithmFrame, sticky="w")
tkgrid(algorithmFrame, sticky="w", columnspan=2)
tkgrid.configure(buttonsFrame, sticky="w")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
dialogSuffix(rows=20, columns=2, focus=xEntry)
}
Rcmdr.help.orloca <- function(){
gettext("Help about orloca", domain="R-RcmdrPlugin.orloca")
command <- paste("help(\"", gettext("orloca", domain="R-orloca"), sep="")
command <- paste(command, "\")", sep="")
doItAndPrint(command)
invisible(NULL)
}
Rcmdr.help.orloca.vignettes <- function(){
gettext("Planar Location with orloca", domain="R-RcmdrPlugin.orloca")
command <- paste("vignette(\"", gettext("planarlocation", domain="R-RcmdrPlugin.orloca"), sep="")
command <- paste(command, "\")", sep="")
doItAndPrint(command)
invisible(NULL)
}
Rcmdr.help.RcmdrPlugin.orloca <- function(){
gettext("Help about RcmdrPlugin.orloca", domain="R-RcmdrPlugin.orloca")
command <- paste("help(\"", gettext("RcmdrPlugin.orloca", domain="R-RcmdrPlugin.orloca"), sep="")
command <- paste(command, "\")", sep="")
doItAndPrint(command)
invisible(NULL)
}
Rcmdr.help.RcmdrPlugin.orloca.vignettes <- function(){
gettext("Planar Location with Rcmdr", domain="R-RcmdrPlugin.orloca")
command <- paste("vignette(\"", gettext("planarlocationRcmdr", domain="R-RcmdrPlugin.orloca"), sep="")
command <- paste(command, "\")", sep="")
doItAndPrint(command)
invisible(NULL)
}
Rcmdr.summary.loca.p <- function(){
gettext("Summary", domain="R-RcmdrPlugin.orloca")
command <- paste("summary(as(", ActiveDataSet(), ", \"loca.p\"))", sep="")
doItAndPrint(command)
invisible(NULL)
}
activeDataSetLocaP <- function() activeDataSetP() && validObject(new("loca.p",x=get(ActiveDataSet())$x, y=get(ActiveDataSet())$y, w=get(ActiveDataSet())$w))
activeDataSetLocaP <- function()
{
if (activeDataSetP())
{
.activeDataSet <- get(ActiveDataSet())
(nrow(.activeDataSet)==length(.activeDataSet$x)) && (nrow(.activeDataSet)==length(.activeDataSet$y)) && (nrow(.activeDataSet)==length(.activeDataSet$w)) && (sum(is.na(.activeDataSet$x))+sum(is.na(.activeDataSet$y)+sum(is.na(.activeDataSet$w)))==0)
}
else FALSE
}
Rcmdr.orloca.norm <- function(){
gettext("Show/Set norm", domain="R-RcmdrPlugin.orloca")
l2 <- options(".RcmdrPlugin.orloca.l2")
if (l2 == TRUE)
{
lp <- ""
iv <- "l2"
}
else
{
lp <- as.character(options(".RcmdrPlugin.orloca.lp"))
iv <- 'lp'
}
initializeDialog(title=gettext("Selection of the norm", domain="R-RcmdrPlugin.orloca"))
radioButtons(name="norma", title= gettext("Select the norm", domain="R-RcmdrPlugin.orloca"), buttons=c("l2", "lp"), labels=gettext(c("l_2 ", "l_p "), domain="R-RcmdrPlugin.orloca"), values=c("l2", "lp"), initialValue=iv)
nameVar <- tclVar(lp)
nameEntry <- tkentry(top, width="8", textvariable=nameVar)
onOK <- function(){
closeDialog()
name <- as.numeric(tclvalue(nameVar))
on <- tclvalue(normaVariable)
if (identical(on, 'l2')) options(list(".RcmdrPlugin.orloca.l2" = T))
else if (name >= 1)
{
options(list(".RcmdrPlugin.orloca.l2" = F))
options(list(".RcmdrPlugin.orloca.lp" = name))
tkfocus(CommanderWindow())
}
else
{
errorCondition(recall=Rcmdr.orloca.norm, message=paste('"', name, '" ', gettext("is not a valid l_p norm.", domain="R-RcmdrPlugin.orloca"), sep=""))
}
return()
}
OKCancelHelp(helpSubject="distsum")
tkgrid(normaFrame, sticky="w")
tkgrid(tklabel(top, text=gettext("p = ", domain="R-RcmdrPlugin.orloca")), nameEntry, sticky="e")
tkgrid(buttonsFrame, sticky="w", columnspan=2)
tkgrid.configure(nameEntry, sticky="w")
dialogSuffix(rows=3, columns=2, focus=normaFrame)
}
|
RTIGER = function(expDesign,
rigidity=NULL,
outputdir=NULL,
nstates = 3,
seqlengths = NULL,
eps=0.01,
max.iter=50,
trace = FALSE,
tiles = 4e5,
all = TRUE,
random = FALSE,
specific = FALSE,
nsamples = 20,
post.processing = TRUE,
save.results = FALSE,
verbose = TRUE){
if(any(seqlengths < tiles)) stop("Your tiling distance is larger than some of your chromosomes. Reduce the tiling parameter.\n")
if(is.null(rigidity)) stop("Rigidity must be specified. This is a data specific parameter. Check vignette.\n")
if(!is.integer(rigidity)) rigidity = as.integer(rigidity)
if(is.null(outputdir) & save.results ) stop("Outputdir must be specified. The results are automatichally saved inside the folder.\n")
if(!is.null(outputdir)) if(!file.exists(outputdir)) if(verbose) cat(paste0("The new directory: ", outputdir, " will be created.\n"))
if(!is.integer(nstates)) nstates = as.integer(nstates)
if(is.null(seqlengths)) stop("seqlengths are necessary to create the Genomic Ranges object to store the data. Please, introduce the chromosome lengths of your organism.\n")
if(!is.integer(max.iter)) max.iter = as.integer(max.iter)
if(save.results){
requireNamespace("Gviz")
requireNamespace("rtracklayer")
}
if(verbose) cat("Loading data and generating RTIGER object.\n")
newn = paste("Sample", 1:nrow(expDesign), sep = "_")
names(newn) = expDesign$name
expDesign$OName = expDesign$name
expDesign$name = newn
myDat = generateObject(experimentDesign = expDesign,nstates = nstates,rigidity = rigidity, seqlengths = seqlengths, verbose = verbose)
info = myDat@info
obs.l = sapply(myDat@matobs, function(x) sapply(x, ncol))
if(any(obs.l < 2*rigidity)) stop("Some of your observations is smaller than 2 times rigidity. Decrease your rigidity value.")
if(verbose) cat("\n\nFitting the parameters and Viterbi decoding. \n")
if(verbose) cat("post processing value is:", post.processing,"\n")
myDat = fit(rtigerobj = myDat,
max.iter = max.iter,
eps = eps,
trace = trace,
all = all,
random = random,
specific = specific,
nsamples = nsamples,
post.processing = post.processing
)
if(all(info$sample_names == expDesign$name)) info$sample_names = expDesign$OName
myDat@info$expDesign = expDesign
if(verbose) cat("Number of iterations run: ", [email protected], "\n\n")
if([email protected] == max.iter) cat("--------------------------\n
Warning!! The maximum number of iterations were needed without reaching convergence.\n
We recommend to increase the number of iterations.
\n\n--------------------------\n\n")
if(save.results){
if(!dir.exists(outputdir)) dir.create(outputdir)
if(verbose) cat("Plotting samples Genotypes.\n")
for(samp in info$sample_names){
sampdir = file.path(outputdir, samp)
myx = paste0("GenotypePlot_",samp, ".pdf")
if(!dir.exists(sampdir)) dir.create(sampdir)
on = file.path(sampdir, myx)
pdf(on)
for(chr in info$part_names){
ren = newn[as.character(samp)]
plotGenotype(myDat, ren, chr, ratio = TRUE, window = 10)
}
dev.off()
}
if(verbose) cat("PLotting CO number per chromosome. \n")
myf = file.path(outputdir, "COs-per-Chromosome.pdf")
plotCOs(myDat, myf)
cos = calcCOnumber(myDat)
cos = melt(cos)
rev.newn = myDat@info$expDesign$OName
names(rev.newn) = myDat@info$expDesign$name
colnames(cos) = c("Chr", "Sample", "COs")
cos$Sample = rev.newn[cos$Sample]
myf = file.path(outputdir, "CO-count-perSample.pdf")
pdf(myf)
p <- ggplot(data=cos, aes(x=Sample, y=COs)) +
geom_bar(stat="identity") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
ylab("Number of COs")+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))
print(p)
dev.off()
if(verbose) cat("Creating bed and IGV output formats.\n")
for(samp in info$sample_names){
export2IGV(myDat, sample = samp, dir = outputdir, ratio = TRUE, newn = newn)
}
if(nstates < 4){
if(verbose) cat("Plotting goodness of fit.\n")
vit = myDat@Viterbi
if(length(vit) >= 10)vit = vit[sample(1:length(vit), ceiling(.1*length(vit)))]
hetrat = unlist(lapply(vit, function(x) x$P1.Allele.Count[x$Viterbi == "het"]/x$total[x$Viterbi == "het"] * 100))
patrat = unlist(lapply(vit, function(x) x$P1.Allele.Count[x$Viterbi == "pat"]/x$total[x$Viterbi == "pat"]* 100))
matrat = unlist(lapply(vit, function(x) x$P1.Allele.Count[x$Viterbi == "mat"]/x$total[x$Viterbi == "mat"]* 100))
if(nstates == 3 & any(c(length(hetrat), length(patrat), length(matrat)) == 0)){
if(verbose) cat("Your data probably comes form a back-crossed population. Please fit the model with nstates = 2.\n
The plot Goodness-Of-Fit.pdf might be erroneous.")
myl = list(hetrat, patrat, matrat)
myl = myl[which(c(length(hetrat), length(patrat), length(matrat)) != 0)]
hetrat = myl[[1]]
patrat = myl[[2]]
}
if(nstates < 4){
alphas = as.vector(myDat@params$paraBetaAlpha)
names(alphas) = rownames(myDat@params$paraBetaAlpha)
betas = as.vector(myDat@params$paraBetaBeta)
names(betas) = rownames(myDat@params$paraBetaBeta)
x = 0:100
y = NULL
ecolors = c("red","violet","blue")
for (e_state in names(alphas)) { y = cbind(y,dbb(x,100,alphas[e_state],betas[e_state])) }
colnames(y) = names(alphas)
myf = file.path(outputdir, "Goodness-Of-Fit.pdf")
pdf(myf)
if(length(patrat) > 0){
hist(patrat, probability = TRUE, col = rgb(1,0,0,0.25), main = "P1 homozygous states", xlab = "Allele ratio", xlim = c(0,100))
points(x,y[,"pat"],type="l",col=ecolors[1])
legend("topleft",c("Fitted P1 distribution"),
lty = 1, col = c("red"), cex = .7)
}
if(length(hetrat) > 0){
hist(hetrat, probability = TRUE, col = rgb( 0.744,0.34,0.844,0.25), main = "P1 homozygous states", xlab = "Allele ratio", xlim = c(0,100))
points(x,y[,"het"],type="l",col=ecolors[2])
legend("topleft",c( "Fitted Heterozygous\n distribution"),
lty = 1, col = c( "violet"), cex = .7)
}
if(length(matrat) > 0){
hist(matrat, probability = TRUE, col = rgb(0,0,1,0.25), main = "P1 homozygous states", xlab = "Allele ratio", xlim = c(0,100))
points(x,y[,"mat"],type="l",col=ecolors[3])
legend("topleft",c("Fitted P2 distribution"),
lty = 1, col = c("blue"), cex = .7)
}
dev.off()
}
}
myx = lapply(vit, function(samp){
myp = lapply(seqlevels(samp), function(chr){
myn = samp[seqnames(samp) == chr]
myn = Vit2GrangesGen(myn, "Viterbi")
seqlengths(myn) = seqlengths(samp)
return(myn)
})
names(myp) = seqlevels(samp)
return(myp)
})
myf = file.path(outputdir, "GenomicFrequencies.pdf")
plotFreqgen(myx = myx, tiles = tiles, file = myf, info = info, groups = NULL, verbose = verbose)
}
return(myDat)
}
|
fit.ns <- function(points, lims, R, disp = "gaussian", child.dist = "pois", child.info = NULL,
sibling.list = NULL, edge.correction = "pbc", start = NULL, bounds = NULL,
use.bobyqa = FALSE, trace = FALSE){
classes.list <- setup.classes(fit = TRUE, family = "ns",
family.info = list(child.dist = child.dist,
child.info = child.info,
disp = disp,
sibling.list = sibling.list),
fit.info = list(edge.correction = edge.correction,
use.bobyqa = use.bobyqa))
obj <- create.obj(classes = classes.list$classes, points = points, lims = lims, R = R,
child.list = classes.list$child.list, parent.locs = NULL,
sibling.list = sibling.list, trace = trace, start = start, bounds = bounds)
obj$fit()
obj
}
sim.ns <- function(pars, lims, disp = "gaussian", child.dist = "pois", parents = NULL, child.info = NULL){
classes.list <- setup.classes(fit = FALSE, family = "ns", family.info = list(child.dist = child.dist,
child.info = child.info,
parent.locs = parents,
disp = disp),
fit.info = NULL)
obj <- create.obj(classes = classes.list$classes, points = NULL, lims = lims, R = NULL,
child.list = classes.list$child.list, parent.locs = classes.list$parent.locs,
sibling.list = NULL, trace = NULL, start = NULL, bounds = NULL)
obj$simulate(pars)
}
fit.void <- function(points, lims, R, edge.correction = "pbc", start = NULL, bounds = NULL,
use.bobyqa = FALSE, trace = FALSE){
classes.list <- setup.classes(fit = TRUE, family = "void", family.info = NULL,
fit.info = list(edge.correction = edge.correction,
use.bobyqa = use.bobyqa))
obj <- create.obj(classes = classes.list$classes, points = points, lims = lims, R = R,
child.list = NULL, parent.locs = NULL, sibling.list = NULL,
trace = trace, start = start, bounds = bounds)
obj$fit()
obj
}
sim.void <- function(pars, lims, parents = NULL){
classes.list <- setup.classes(fit = FALSE, family = "void", family.info = list(parent.locs = parents),
fit.info = NULL)
obj <- create.obj(classes = classes.list$classes, points = NULL, lims = lims, R = NULL,
child.list = NULL, parent.locs = classes.list$parent.locs,
sibling.list = NULL, trace = NULL, start = NULL, bounds = NULL)
obj$simulate(pars)
}
setup.classes <- function(fit, family, family.info, fit.info){
use.fit.class <- FALSE
use.nlminb.class <- FALSE
use.bobyqa.class <- FALSE
use.pbc.class <- FALSE
use.buffer.class <- FALSE
use.ns.class <- FALSE
use.sibling.class <- FALSE
use.poischild.class <- FALSE
use.binomchild.class <- FALSE
use.twocamerachild.class <- FALSE
child.list <- NULL
parent.locs <- NULL
use.thomas.class <- FALSE
use.matern.class <- FALSE
use.void.class <- FALSE
use.totaldeletion.class <- FALSE
use.giveparent.class <- FALSE
if (fit){
use.fit.class <- TRUE
if (fit.info$use.bobyqa){
use.bobyqa.class <- TRUE
} else {
use.nlminb.class <- TRUE
}
if (fit.info$edge.correction == "pbc"){
use.pbc.class <- TRUE
} else if (fit.info$edge.correction == "buffer"){
use.buffer.class <- TRUE
} else {
stop("Edge correction method not recognised; use either 'pbc' or 'buffer'.")
}
}
if (family == "ns"){
use.ns.class <- TRUE
if (!is.null(family.info$sibling.list)){
use.sibling.class <- TRUE
}
if (family.info$child.dist == "pois"){
use.poischild.class <- TRUE
} else if (substr(family.info$child.dist, 1, 5) == "binom"){
use.binomchild.class <- TRUE
n <- as.numeric(substr(family.info$child.dist, 6, nchar(family.info$child.dist)))
child.list <- list(size = n)
} else if (family.info$child.dist == "twocamera"){
use.twocamerachild.class <- TRUE
child.list <- list(twocamera.w = family.info$child.info$w,
twocamera.b = family.info$child.info$b,
twocamera.l = family.info$child.info$l,
twocamera.tau = family.info$child.info$tau)
} else {
stop("Only 'pois', 'binomx', or 'twocamera' can currently be used for 'child.dist'.")
}
if (family.info$disp == "gaussian"){
use.thomas.class <- TRUE
} else if (family.info$disp == "uniform"){
use.matern.class <- TRUE
} else {
stop("Dispersion type not recognised; use either 'gaussian' or 'uniform'.")
}
} else if (family == "void"){
use.void.class <- TRUE
use.totaldeletion.class <- TRUE
}
if (!is.null(family.info$parent.locs)){
use.giveparent.class <- TRUE
parent.locs <- family.info$parent.locs
}
classes <- c("fit"[use.fit.class],
"bobyqa"[use.bobyqa.class],
"nlminb"[use.nlminb.class],
"pbc"[use.pbc.class],
"buffer"[use.buffer.class],
"ns"[use.ns.class],
"sibling"[use.sibling.class],
"poischild"[use.poischild.class],
"binomchild"[use.binomchild.class],
"twocamerachild"[use.twocamerachild.class],
"thomas"[use.thomas.class],
"matern"[use.matern.class],
"void"[use.void.class],
"totaldeletion"[use.totaldeletion.class],
"giveparent"[use.giveparent.class])
list(classes = classes, child.list = child.list, parent.locs = parent.locs)
}
fit.twocamera <- function(points, cameras = NULL, d, w, b, l, tau, R,
edge.correction = "pbc", start = NULL,
bounds = NULL, trace = FALSE){
if (is.vector(points)){
points <- matrix(points, ncol = 1)
}
if (is.null(cameras)){
sibling.list <- NULL
} else {
sibling.list <- siblings.twocamera(cameras)
}
if (is.null(bounds)){
bounds <- list(sigma = c(0, min(R, b/3)))
} else if (!any(names(bounds) == "sigma")){
bounds[["sigma"]] <- c(0, min(R, b/3))
}
fit.ns(points = points, lims = rbind(c(0, d)), R = R,
child.dist = "twocamera",
child.info = list(w = w, b = b, l = l, tau = tau),
sibling.list = sibling.list, edge.correction = edge.correction,
start = start, bounds = bounds, trace = trace)
}
sim.twocamera <- function(pars, d, w, b, l, tau, parents = NULL){
if (!is.null(parents)){
parents <- matrix(parents, ncol = 1)
}
family.info <- list(child.dist = "twocamera",
child.info = list(w = w, b = b, l = l, tau = tau),
parent.locs = parents, disp = "gaussian")
classes.list <- setup.classes(fit = FALSE, family = "ns",
family.info = family.info)
obj <- create.obj(classes = classes.list$classes, points = NULL, lims = rbind(c(0, d)),
R = NULL, child.list = classes.list$child.list,
parent.locs = classes.list$parent.locs, sibling.list = NULL,
trace = NULL, bounds = NULL)
obj$simulate(pars)
}
boot.palm <- function(fit, N, prog = TRUE){
fit$boot(N, prog)
fit
}
|
overly<- function(veg,Plot.no,y,sint,...) UseMethod("overly")
overly.default<- function(veg,Plot.no,y,sint,...) {
o.overly<- overly2(veg,Plot.no,y,sint)
o.overly$call<- match.call()
cat("Call:\n")
class(o.overly) <- "overly"
print(o.overly$call)
o.overly
nt<- o.overly$n.tsteps
cat("Number of time steps in new time series: ",nt,"\n")
cat("Time span of the new time series: 0 -",o.overly$tsteps[nt],"\n")
o.overly
}
plot.overly<- function(x,...,colors=NULL,l.widths=NULL) {
o.overly<- x
tree<- o.overly$tree
out<- pco(o.overly$d.mat,k=2)
plot(out$points[,1],out$points[,2],xlab="PCOA axis 1",ylab="PCOA axis 2",asp=1,cex.axis=0.7,cex.lab=0.7,mgp=c(1.8,0.4,0))
abline(h=0,v=0,lwd=1.0,col="gray")
lines(tree,ord=out,display="sites",col="lightblue",lwd=1.5)
pos.corr<-c(3,1,1,1,3,1,2,3,3,3,3,3,3,3,4,3,2,2,1,4,3,3,3,3,3,3,3,4,3,3,3,
3,3,3,4,3,3,3,2,3,3,2,3,3,3,4,3,3,3,2,2,3,3,4,3,2,4,3,3)
text(out$points[,1],out$points[,2],o.overly$plot.labels,pos=pos.corr,cex=0.6)
veg<- o.overly$vegraw
nspec<- ncol(veg)
nt<- ncol(o.overly$d.mat)
range<- o.overly$n.tsteps
plot(c(0,range*1.05),c(0,nt),type="n",xlab="Time step no.",ylab="Time series",cex.lab=0.7)
for (i in 1:nt) {
lines(c(o.overly$linex1[i],o.overly$linex2[i]),c(i,i),lwd=2.5,col="gray")
text(o.overly$linex2[i],i,o.overly$ltext[i],pos=4,cex=0.6)
}
abline(v=0,lwd=1.0,col="gray")
defwidth<- is.null(l.widths)
if(defwidth == TRUE) ll.widths<- seq(0.5,4.0,0.5)
if(defwidth != TRUE) ll.widths<- l.widths
defcol<- is.null(colors)
if(defcol == TRUE) c.colors<- c("darkred","red1","darkorange","gold","lightgreen","darkolivegreen4")
if(defcol != TRUE) c.colors<- colors
sint<- o.overly$sint
M<- o.overly$tser.data
vegtypes<- o.overly$vegtypes
timescal<- seq(0,(range-1)*sint,sint)
par(mfrow=c(1,1),omi=c(2,0,0,0))
plot(c(0,range*sint),c(0,max(M)),xlab="Time units",ylab="Cover scale",type="n")
for(i in 1:nspec) lines(timescal,M[,i],col=c.colors[i],lwd=ll.widths[i],lty=1)
legend("topleft",vegtypes,lty=1,lwd=ll.widths,col=c.colors,ncol=2,bty="n",cex=0.8,text.font=3)
}
overly2<- function(veg,Plot.no,y,sint) {
vegtypes<- names(veg)
veg<- veg^y
veg<- veg[order(Plot.no),]
ser<- as.integer(table(Plot.no))
lev<- levels(as.factor(Plot.no))
nt<- length(ser)
dser<- rep(0,nt*nt)
dim(dser)<-c(nt,nt)
mser<- rep(0,nt*nt*2)
dim(mser)<-c(nt,nt,2)
kids<-rep(0,nt)
jj<-rep(0,2)
drel<- as.matrix(dist(veg))
nspec <- length(veg[1,])
i1<- 0 ; i2<- 0
for (i in 1:nt){
i1<- i2+1
i2<- i2+ser[i]
j1<- 0 ; j2<- 0
for (j in 1:nt) {
j1<- j2+1
j2<- j2+ser[j]
if (i != j) {
m<- min(drel[i1:i2,j1:j2])
jj<- which(drel[i1:i2,j1:j2] == m)
dser[j,i]<- m
mser[j,i,2]<- ceiling(jj[1]/ser[i])
mser[j,i,1]<- jj[1]-((ser[i]*(mser[j,i,2]-1)))
}
}
}
out <- pco(dser,k=2)
tree<- spantree(dser)
kids[2:nt]<- tree$kid ; kids[1]<-kids[2]
parents<- c(1:nt)
merged<- rep(0,nt) ; merged[1]<- 1
shift<- rep(0,nt)
shift[parents[2]]<- mser[kids[2],parents[2],1]-mser[kids[2],parents[2],2]+shift[kids[2]]
merged[2]<- 1
while(sum(merged) < nt) {
for (i in 2:nt) {
if (merged[kids[i]]==1 & merged[parents[i]]==0) {
shift[parents[i]]<- mser[kids[i],parents[i],2]-mser[kids[i],parents[i],1]+shift[kids[i]]
merged[parents[i]]<- 1
}
}
}
shift<- shift-min(shift)
range<-max(shift+ser)
veg<- veg^(1/y)
linex1<- rep(0,nt)
linex2<- rep(0,nt)
ltext<- rep("x",nt)
is<- 1
count.null<- rep(0,range)
count.temp<- count.null
count.sum<- count.null
nrel<- nrow(veg)
itim<- rep(0,nrel)
is<-1
for(i in 1:nt) {
l<- is:(is+ser[i]-1)
m<- (shift[i]+1):(shift[i]+ser[i])
itim[l]<- m
is<-is+ser[i]
count.temp[(shift[i]+1):(shift[i]+ser[i])]<- rep(1,ser[i])
linex1[i]<- shift[i]+1
linex2[i]<- shift[i]+ser[i]
ltext[i]<- lev[i]
count.sum<- count.sum+count.temp
count.temp<- count.null
}
agg<- aggregate(veg,list(itim),sum)
S<- agg[,-1]
C<- count.sum
M<- S/C
timescal<- seq(0,(range-1)*sint,sint)
M<- as.data.frame(M)
colnames(M) <- vegtypes
rownames(M) <- as.character(seq(1,range,1))
overly<- list(plot.labels=levels(Plot.no),n.tsteps=range,tsteps=timescal,tser.data=M,ord.scores=out$points,d.mat=dser,tree=tree,vegraw=veg,linex1=linex1,linex2=linex2,ltext=ltext,sint=sint,vegtypes=vegtypes)
}
|
expected <- eval(parse(text="structure(numeric(0), .Dim = c(20L, 0L), .Dimnames = list(c(\"ant\", \"bee\", \"cat\", \"cpl\", \"chi\", \"cow\", \"duc\", \"eag\", \"ele\", \"fly\", \"fro\", \"her\", \"lio\", \"liz\", \"lob\", \"man\", \"rab\", \"sal\", \"spi\", \"wha\"), NULL))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(numeric(0), .Dim = c(20L, 0L), .Dimnames = list(c(\"ant\", \"bee\", \"cat\", \"cpl\", \"chi\", \"cow\", \"duc\", \"eag\", \"ele\", \"fly\", \"fro\", \"her\", \"lio\", \"liz\", \"lob\", \"man\", \"rab\", \"sal\", \"spi\", \"wha\"), NULL)))"));
do.call(`log10`, argv);
}, o=expected);
|
info.design <- function(seqs = NA) {
sequences <- length(seqs)
if (sequences < 2)
stop("At least 2 sequences required.")
if (!is.character(seqs))
stop("Sequences must be given as strings, not numbers.")
if (sequences != length(unique(seqs)))
stop(paste("The", sequences,"sequences must be unique."))
periods <- unique(nchar(seqs))
if (periods < 2)
stop("Not a crossover design.")
if (periods == 2 & sequences == 2) {
stop("Not a replicate design.")
}
if (length(periods) > 1)
stop("Each sequence must have the same number of periods.")
reordered <- NA
if (periods == 4 & sequences == 4 & is.na(reordered[1])) {
if (sum(seqs %in% c("RTRT", "RTTR", "TRRT", "TRTR")) == 4) {
reordered <- seqs[order(match(seqs, c("TRTR", "RTRT", "TRRT", "RTTR")))]
}
if (sum(seqs %in% c("RRTT", "RTTR", "TRRT", "TTRR")) == 4 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRRT", "RTTR", "TTRR", "RRTT")))]
}
if (is.na(reordered[1])) {
message("Untested design.")
reordered <- rev(seqs)
}
design <- "full"
}
if (periods == 4 & sequences == 2 & is.na(reordered[1])) {
if (sum(seqs %in% c("RTRT", "TRTR")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRTR", "RTRT")))]
}
if (sum(seqs %in% c("RTTR", "TRRT")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRRT", "RTTR")))]
}
if (sum(seqs %in% c("TTRR", "RRTT")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TTRR", "RRTT")))]
}
if (is.na(reordered[1])) {
message("Untested design.")
reordered <- rev(seqs)
}
design <- "full"
}
if (periods == 3 & sequences == 2 & is.na(reordered[1])) {
if (sum(seqs %in% c("RTR", "TRT")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRT", "RTR")))]
design <- "full"
}
if (sum(seqs %in% c("RTT", "TRR")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRR", "RTT")))]
design <- "full"
}
if (sum(seqs %in% c("RTR", "TRR")) == 2 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRR", "RTR")))]
design <- "partial"
}
if (is.na(reordered[1])) {
message("Untested design.")
reordered <- rev(seqs)
design <- "partial"
}
}
if (periods == 3 & sequences == 3 & is.na(reordered[1])) {
if (sum(seqs %in% c("RRT", "RTR", "TRR")) == 3 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TRR", "RTR", "RRT")))]
}
if (is.na(reordered[1])) {
message("Untested design.")
reordered <- rev(seqs)
}
design <- "partial"
}
if (periods == 2 & sequences == 4 & is.na(reordered[1])) {
if (sum(seqs %in% c("RR", "RT", "TR", "TT")) == 4 & is.na(reordered[1])) {
reordered <- seqs[order(match(seqs, c("TR", "RT", "TT", "RR")))]
}
if (is.na(reordered[1])) {
message("Untested design.")
reordered <- rev(seqs)
}
design <- "full"
}
design <- list(reordered, paste0(reordered, collapse="|"),
sequences, periods, design)
names(design) <- c("reordered", "type", "sequences", "periods", "design")
return(design)
}
|
expand_ar <- function(ar, sar, s){
x <- polynom(c(0,1))
phi <- polynom(c(1, -ar))
sphi <- polynom(c(1, -sar))(x^s)
coef(phi * sphi)
}
poly_x <- polynom(c(0,1))
poly_delta <- polynom(c(1, -1))
.sarima_env <- function(){
.process_fixed <- function(x, fixed = NULL){
if(is.null(x))
stop("'x' must have a value here")
xlen <- length(x)
if(is.null(fixed))
rep(FALSE, xlen)
else if(isTRUE(fixed))
rep(TRUE, xlen)
else if(is.logical(fixed)){
if(length(fixed) == 1)
rep(fixed, xlen)
else if(length(fixed) == xlen)
fixed
else
stop("if 'fixed' is logical, its length must be equal to one or the order.")
}else if(is.numeric(fixed)){
if(!is.integer(fixed) && any(round(fixed) != fixed))
stop("if numeric, 'fixed' must contain integer numbers")
if(any(fixed <= 0) || any(fixed > xlen))
stop("if numeric, 'fixed' must contain integers between 1 and 'order'")
res <- rep(FALSE, xlen)
res[fixed] <- TRUE
res
}else{
stop("unsupported type of 'fixed'")
}
}
.process_atanh.tr <- function(x, transf = NULL){
if(is.null(x))
stop("'x' must have a value here")
xlen <- length(x)
if(is.null(transf))
rep(FALSE, xlen)
else if(isTRUE(transf))
rep(TRUE, xlen)
else if(is.logical(transf)){
if(length(transf) == 1)
rep(transf, xlen)
else if(length(transf) == xlen)
transf
else
stop("if 'transf' is logical, its length must be equal to one or the order.")
}else if(is.numeric(transf)){
if(!is.integer(transf) && any(round(transf) != transf))
stop("if numeric, 'transf' must contain integer numbers")
if(any(transf <= 0) || any(transf > xlen))
stop("if numeric, 'transf' must contain integers between 1 and 'order'")
res <- rep(FALSE, xlen)
res[transf] <- TRUE
res
}else{
stop("unsupported type of 'transf'")
}
}
.set_coef <- function(order, coef = NULL, fixed = NULL, nonfixed = NULL,
atanh.tr = NULL, ...){
wrk <- NULL
coef.type <- "coef"
if(!is.null(order))
wrk <- rep(NA_real_, order)
if(!missing(coef) && !is.null(coef)){
if(is.null(wrk))
wrk <- coef
else{
if(length(coef) != length(wrk))
stop("if given, 'coef' must have length equal to 'order'")
wrk[seq_along(coef)] <- coef
}
}
a <- .process_fixed(wrk, fixed)
b <- .process_atanh.tr(wrk, atanh.tr)
if(!missing(nonfixed) || !is.null(nonfixed)){
bb <- .process_fixed(wrk, nonfixed)
a <- a & !bb
}
res <- wrk
attr(res, "fixed") <- a
attr(res, "atanh.tr") <- b
dots <- list(...)
for(at in names(dots))
attr(res, at) <- dots[[at]]
res
}
ar <- function(p = 0, ar, sign = "-", atanh.tr = TRUE, ...){
coef <- .set_coef(p, ar, sign = sign, dispname = "ar", atanh.tr = atanh.tr, ...)
list(name = "ar", p = p, coef = coef)
}
ma <- function(q = 0, ma, sign = "+", atanh.tr = TRUE, ...){
coef <- .set_coef(q, ma, sign = sign, dispname = "ma", atanh.tr = atanh.tr, ...)
list(name = "ma", q = q, coef = coef)
}
s <- function(...){
dots <- c(...)
if(length(dots) != 1)
stop("currently only one argument is supported")
p <- dots[1] - 1
coef <- .set_coef(p, rep(1, p), sign = "+", fixed = TRUE, operator = TRUE, dispname = "s")
list(name = "s", p = p, coef = coef)
}
i <- function(d, ...){
coef <- .set_coef(1, 1, sign = "-", fixed = TRUE, d = d, operator = TRUE,
dispname = "i", ...)
list(name = "i", d = d, p = 1, coef = coef)
}
u <- function(u, fixed = TRUE, operator = all(fixed), ...){
f <- function(x){
if(is.complex(x))
-2*cos(Arg(x))
else -2 * cospi(2*x)
}
co <- sapply(u, f)
coef <- lapply(co, function(x) .set_coef(2, c(x, 1), sign = "+", fixed = fixed,
operator = operator, dispname = "su") )
list(name = "u", u = u, coef = coef)
}
uar <- function(p = 2, parcor, sign = "-", atanh.tr = TRUE, fixed = NULL, ...){
if(p < 2)
stop("'p' must be greater than 2 for unit AR polynomials")
if(abs(parcor[p]) != 1)
stop("the last coefficient supplied should be +1 or -1")
if(is.null(fixed)){
fixed <- rep(FALSE, p)
if(p > 0)
fixed[p] <- TRUE
}
coef <- .set_coef(p, parcor, sign = sign, dispname = "uar", atanh.tr = atanh.tr,
fixed = fixed, ...)
list(name = "uar", p = p, coef = coef)
}
sar <- function(s, p = 0, ar, sign = "-", atanh.tr = TRUE, ...){
coef <- .set_coef(p, ar, sign = sign, nseasons = s, dispname = "sar",
atanh.tr = atanh.tr, ...)
list(name = "sar", s = s, p = p, coef = coef)
}
sma <- function(s, q = 0, ma, sign = "+", atanh.tr = TRUE, ...){
coef <- .set_coef(q, ma, sign = sign, nseasons = s, dispname = "sma",
atanh.tr = atanh.tr, ...)
list(name = "sma", s = s, q = q, coef = coef)
}
ss <- function(s, ...){
dots <- c(...)
if(length(dots) != 1)
stop("currently only one argument is supported")
p <- dots[1] - 1
coef <- .set_coef(p, rep(1, p), sign = "+", nseasons = s, fixed = TRUE,
operator = TRUE, dispname = "ss")
list(name = "ss", s = s, p = p, coef = coef)
}
si <- function(s, d, ...){
coef <- .set_coef(1, 1, sign = "-", nseasons = s, fixed = TRUE,
operator = TRUE, dispname = "si", ...)
list(name = "si", s = s, d = d, coef = coef)
}
su <- function(s, h){
int_cond <- any(h %% 1 > 0)
if(int_cond)
stop("'h' must contain only (positive) integer values")
pos_cond <- any(h < 1)
if(int_cond)
stop("'h' must contain only positive (integer) values")
max_cond <- !all(h < s/2)
if(max_cond)
stop("'h' must be a positive integer less than 's/2'")
coef <- lapply(h, function(x)
.set_coef(2, c(- 2 * cospi(2*x/s), 1),
sign = "+", fixed = TRUE, operator = TRUE,
dispname = "su", su.nseasons = s, su.harmonic = x) )
list(name = "su", s = s, u = h, coef = coef)
}
.specials <- ls()
.sarima_descr <- list()
class(.sarima_descr) <- "sarimadescr"
environment()
}
SARIMA <- function(formula){
e <- .sarima_env()
parent.env(e) <- environment(formula)
te <- terms(formula, specials = e$.specials, keep.order = TRUE)
termvars <- attr(te, "variables")
sp <- attr(te, "specials")
res <- list()
indices <- lapply(names(sp),
function(nam){
ind <- sp[[nam]]
if(is.null(ind))
return(integer(0))
names(ind) <- rep(nam, length(ind))
ind
}
)
indices <- sort(unlist(indices))
nams <- names(indices)
indices <- indices + 1
res <- vector("list", length = length(indices))
names(res) <- nams
for(i in seq_along(indices)){
res[[i]] <- eval(termvars[[indices[i]]], envir = e)
}
res
}
trendMaker <- function(formula, data = NULL, time = NULL){
if(is.null(data))
data.env <- new.env(hash = FALSE, parent = environment(formula))
else{
stopifnot(is.environment(data))
data.env <- data
}
environment(formula) <- data.env
data.env$formula <- formula
data.env$.t.orig <- data.env$t <- time
.t.orig <- "dummy for R CMD check; .t.orig is needed in dataenv, as set above"
data.env$.p <- function(degree){
if(identical(t, .t.orig))
res <- poly(t, degree = degree, simple = TRUE)
else{
wrk <- poly(.t.orig, degree = degree, simple = FALSE)
res <- predict(wrk, newdata = t)
}
colnames(res) <- paste0("ortht", seq_len(degree))
res
}
environment(data.env$.p) <- data.env
data.env$.cs <- function(s, k){
res <- if(length(k) == 1){
structure(c(cospi(2*t*k/s), sinpi(2*t*k/s)),
dim = c(length(t), 2),
.Dimnames = list(NULL, paste0(c("c", "s"), s, ".", k) ))
}else if(length(k) > 1){
wrk <- lapply(k, function(x) cbind(cospi(2*t*x/s), sinpi(2*t*x/s)) )
wrk <- do.call("cbind", wrk)
colnames(wrk) <- paste0(c("c", "s"), s, ".", rep(k, each = 2) )
wrk
}else
stop("'k' must have positive length")
res
}
environment(data.env$.cs) <- data.env
data.env$.B <- function(x, lags){
flags <- t > 0
t.pos <- t[flags]
t.neg <- t[!flags]
if(any(flags)){
if(is.matrix(x)){
res <- matrix(NA_real_, nrow = length(t), ncol = ncol(x) * length(lags))
nc.x <- ncol(x)
curcols <- seq_len(nc.x)
for(i in seq_along(lags)){
lag <- lags[i]
res[t - lag > 0, curcols] <- x[pmax(t - lag, 0), ]
curcols <- curcols + nc.x
}
xnam <- deparse(substitute(x))
colnames(res) <- paste0("L(", xnam, rep(seq_len(ncol(x)), length(lags)),
", ", rep(lags, each = ncol(x)), ")")
}else{
res <- matrix(NA_real_, nrow = length(t), ncol = length(lags))
for(i in seq_along(lags)){
lag <- lags[i]
res[t - lag > 0, i] <- x[pmax(t - lag, 0)]
}
}
}
res
}
environment(data.env$.B) <- data.env
res <- function(index){
if(missing(index)){
res <- model.matrix(formula, model.frame(formula, na.action = NULL))
}else{
t.old <- t
t <<- index
formula <- formula(Formula::Formula(formula), lhs = FALSE, rhs = 1)
txt <- paste0(".dummy", paste0(as.character(formula), collapse = ""))
formula <- as.formula(txt, env = environment(formula))
res <- model.frame(formula, data = data.frame(.dummy = t), na.action = NULL)
res <- model.matrix(formula, res)
t <<- t.old
res
}
}
environment(res) <- data.env
res
}
.cat_u_delta <- function(x){
f <- function(poly){
s <- environment(poly)$nseasons
if(!is.null(s))
poly <- poly(poly_x^s)
if(all(coef(poly) == 1) && (deg <- length(coef(poly)) - 1) > 3)
res <- paste0("1 + B + ... + B^", deg)
else
res <- as.character(poly, "B")
d <- environment(poly)$d
if(is.null(d) || d == 1)
paste0("(", res, ")")
else
paste0("(", res, ")^", d)
}
paste0(sapply(x, f), collapse = "")
}
.Sarima_fixed <- function(x) x$internal$fixed
.capture_fo <- function(x) if(is.numeric(x)) x else capture.output(print(x, FALSE))
.Fo.xreg <- function(x) x$internal$Fo.xreg
.Fo.sarima <- function(x) x$internal$Fo.sarima
.Fo.regx <- function(x) if(is.null(res <- x$internal$Fo.regx)) 0 else res
print.Sarima <-
function (x, digits = max(3L, getOption("digits") - 3L), se = TRUE, ...){
cat("*Sarima model*")
cat("\nCall:", deparse(x$call, width.cutoff = 75L), "", sep = "\n")
delta <- x$internal$delta
if(length(delta) > 0){
cat("Unit root terms:\n", " ")
cat(.cat_u_delta(x$internal$delta_poly), sep = "")
cat("\n\n")
}
if (length(x$coef)) {
cat("Coefficients:\n")
coef <- round(x$coef, digits = digits)
if (se && NROW(x$var.coef)) {
ses <- rep.int(0, length(coef))
ses[x$mask] <- round(sqrt(diag(x$var.coef)), digits = digits)
coef <- matrix(coef, 1L, dimnames = list(NULL, names(coef)))
coef <- rbind(coef, s.e. = ses)
}
print.default(coef, print.gap = 2)
}
cm <- x$call$method
if(is.null(cm) || cm != "css")
cat("\nsigma^2 estimated as ", format(x$sigma2, digits = digits),
": log likelihood = ", format(round(x$loglik, 2L)),
", aic = ", format(round(x$aic, 2L)), "\n", sep = "")
else
cat("\nsigma^2 estimated as ",
format(x$sigma2, digits = digits),
": part log likelihood = ", format(round(x$loglik,2)),
"\n", sep = "")
invisible(x)
}
summary.Sarima <- function(object, ...){
cat("\nCall:\n", paste(deparse(object$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
Fo.xreg <- .Fo.xreg (object)
Fo.sarima <- .Fo.sarima(object)
Fo.regx <- .Fo.regx (object)
xfo <- .capture_fo(Fo.xreg)
fosarima <- .capture_fo(Fo.sarima)
fox <- .capture_fo(Fo.regx)
cat("Model: Y_t - xreg_t is SarimaX\n")
cat(" xreg: ", xfo, "\n")
cat(" sarima: ", fosarima, "\n")
cat(" regx: ", fox, "\n")
cat("\n")
delta <- object$internal$delta
if(length(delta) > 0){
cat("Unit root terms:\n", " ")
cat(.cat_u_delta(object$internal$delta_poly), sep = "")
cat("\n\n")
}
fixed <- .Sarima_fixed(object)
est <- object$coef[!fixed]
se <- sqrt(diag(object$var.coef))[!fixed]
zval <- est / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
coefs <- cbind(est, se, zval, pval)
dimnames(coefs) <-
list(names(est),
c("Estimate", "Std. Error", "Z value", "Pr(>|z|)") )
cat("Coefficients:\n")
printCoefmat(coefs
)
cat("\nestimated sigma^2 = ", format(object$sigma2, digits = 3),
", log-likelihood = ", format(round(object$loglik, 2)),
", aic = ", format(round(object$aic, 2L)),
sep = "")
cat("\n")
invisible(object)
}
.tsdiag_choices <- c(
"residuals",
"acf of residuals",
"p values for Ljung-Box statistic",
"p values for Li-McLeod statistic",
"p values for Box-Pierce statistic",
"pacf of residuals"
)
tsdiag.Sarima <- function(object, gof.lag = NULL, ask = FALSE, ..., plot = 1:3, layout = NULL)
{
if(is.null(gof.lag))
gof.lag <- 20
else if(!is.numeric(gof.lag))
stop("'gof.lag' must be numeric and contain positive integers")
lag.max <- max(gof.lag)
err <- object$residuals
stdres <- err / sqrt(object$sigma2)
choices <- .tsdiag_choices
chnum <- 1:length(choices)
if(!isTRUE(plot)){
choices <- choices[plot]
chnum <- chnum[plot]
if(anyNA(choices)){
warning("'plot' should be TRUE/FALSE or vector of positive integers <= ",
length(.tsdiag_choices), ",\n", "ignoring non-existent values")
chnum <- chnum[!is.na(choices)]
choices <- choices[!is.na(choices)]
}
}
if(length(choices) > 0){
old.par <- par(no.readonly = TRUE)
on.exit(par(old.par))
n_per_page <- if(is.null(layout))
layout(matrix(1:3, nrow = 3))
else
do.call("layout", layout)
choice_title <- "Select a plot number or 0 to exit"
ch_index <- if(length(choices) == 1)
1
else if(ask)
menu(choices, title = choice_title)
else if(!identical(plot, FALSE))
1
else
integer(0)
choice <- chnum[ch_index]
nlag <- gof.lag
pval <- numeric(nlag)
fitdf <- if(inherits(object, "Sarima"))
length(object$internal$nonfixed)
else if(inherits(object, "Arima"))
sum(object$arma[1:4])
else
0
sacf <- autocorrelations(err, maxlag = nlag)
res <- list(residuals = err,
"LjungBox" = NULL,
"LiMcLeod" = NULL,
"BoxPierce" = NULL)
while(length(choice) != 0){
switch(choice,
{
plot(stdres, type = "h", main = "Standardized Residuals", ylab = "")
abline(h = 0)
},
{
acf(err, plot = TRUE, main = "ACF of Residuals", lag.max = lag.max, na.action = na.pass)
},
{
acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "LjungBox",
interval = NULL)
res[["LjungBox"]] <- acftest
},
{
acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "LiMcLeod",
interval = NULL)
res[["LiMcLeod"]] <- acftest
},
{
acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "BoxPierce",
interval = NULL)
res[["BoxPierce"]] <- acftest
},
{
pacf(err, plot = TRUE, main = "PACF of Residuals", lag.max = lag.max, na.action = na.pass)
},
)
if(choice %in% 3:5){
pval <- acftest$test[ , "pvalue"]
plot(1L:nlag, pval, xlab = "lag", ylab = "p value", ylim = c(0,1),
main = .tsdiag_choices[choice])
abline(h = 0.05, lty = 2, col = "blue")
}
if(length(chnum) == 1)
break
if(interactive() && (ask || length(choices) > n_per_page)){
ch_index <- menu(choices, title = choice_title)
choice <- chnum[ch_index]
}else{
chnum <- chnum[-1]
choice <- chnum[1]
}
}
}
class(res) <- "tsdiagSarima"
invisible(res)
}
armapqss <- function(ar, ma, sigma) {
p <- length(ar)
q <- length(ma)
r <- max(p, q + 1)
ear <- c(ar, numeric(max(r - p, 0)))
ema <- c(ma, numeric(max(r - q - 1, 0)))
Tt <- cbind(ear, rbind(diag(r - 1), 0))
Rt <- matrix(c(1, ema), ncol = 1)
Zt <- matrix(c(1, numeric(r - 1)), nrow = 1)
ct <- matrix(0)
dt <- matrix(0, nrow = r, ncol = 1)
GGt <- matrix(0)
H <- Rt * sigma
HHt <- H %*% t(H)
a0 <- numeric(r)
P0 <- diag(1e6, nrow = r)
list(a0 = a0, P0 = P0, ct = ct, dt = dt,
Zt = Zt, Tt = Tt, GGt = GGt, HHt = HHt)
}
xarmaxss <- function(ar, ma, sigma, xreg, regx) {
d <- 1
p <- length(ar)
q <- length(ma)
r <- max(p, q + 1)
ear <- c(ar, numeric(max(r - p, 0)))
ema <- c(ma, numeric(max(r - q - 1, 0)))
Tt <- cbind(ear, rbind(diag(r - 1), 0))
Rt <- matrix(c(1, ema), ncol = 1)
Zt <- matrix(c(1, numeric(r - 1)), nrow = d)
ct <- if(missing(xreg) || length(xreg) == 0)
matrix(0, nrow = d)
else
xreg
dt <- if(missing(regx) || length(regx) == 0)
matrix(0, nrow = r, ncol = 1)
else if(nrow(regx) == r)
regx
else
rbind(regx, matrix(0, nrow = r - nrow(regx), ncol = ncol(regx)))
GGt <- matrix(0, nrow = d)
H <- Rt * sigma
HHt <- H %*% t(H)
a0 <- numeric(r)
P0 <- diag(1e6, nrow = r)
list(a0 = a0, P0 = P0, ct = ct, dt = dt,
Zt = Zt, Tt = Tt, GGt = GGt, HHt = HHt)
}
xarimaxss <- function(ar, ma, sigma, xreg, regx, delta = numeric(0)) {
model <- xarmaxss(ar, ma, sigma, xreg, regx)
dd <- length(delta)
if(dd == 0)
return(model)
model$dt <- c(model$dt, numeric(dd))
model$Tt <- rbind(c(delta, 1, numeric(ncol(model$Tt) - 1)),
dbind(diag(1, nrow = dd - 1, ncol = dd),
model$Tt ))
model$Ht <- dbind(matrix(0, dd, dd), model$Ht)
model$Zt <- c(model$Zt, numeric(dd))
model$a0 <- c(numeric(dd), model$a0)
model$P0 <- dbind(diag(1e6, nrow = dd), model$P0)
model
}
makeArimaGnb <- function(phi, theta, Delta, kappa = 1e6,
SSinit = "gnb",
tol = .Machine$double.eps){
if(anyNA(phi)) warning(gettextf("NAs in '%s'", "phi"), domain=NA)
if(anyNA(theta)) warning(gettextf("NAs in '%s'", "theta"), domain=NA)
p <- length(phi)
q <- length(theta)
d <- length(Delta)
r <- max(p, q + 1L)
rd <- r + d
V <- Pn <- P <- T <- matrix(0., rd, rd)
h <- 0.
a <- rep(0., rd)
Z <- c(1., rep.int(0, r-1L), Delta)
if(q > 0)
V[1:(q+1), 1:(q+1)] <- c(1, theta) %o% c(1, theta)
else
V[1, 1] <- 1.0
if(q < r - 1L)
theta <- c(theta, rep.int(0, r - 1L - q))
if(p > 0)
T[1L:p, 1L] <- phi
if(r > 1L) {
ind <- 2:r
T[cbind(ind-1L, ind)] <- 1
}
if(r > 1L)
Pn[1L:r, 1L:r] <- switch(match.arg(SSinit),
"gnb" = .Call(`_sarima_arma_Q0gnb`, phi, theta, tol),
stop("invalid 'SSinit'"))
else Pn[1L, 1L] <- if(p > 0) 1/(1 - phi^2) else 1
if(d > 0L) {
T[r + 1L, ] <- Z
if(d > 1L) {
ind <- r + 2:d
T[cbind(ind, ind-1)] <- 1
}
Pn[cbind(r + 1L:d, r + 1L:d)] <- kappa
}
list(phi = phi, theta = theta, Delta = Delta, Z = Z, a = a,
P = P, T = T, V = V, h = h, Pn = Pn)
}
sarimaReport <- function(o1, o2, ...){
list(
all.equal(coef(o1), coef(o2))
)
}
factorizeMA <- function(x, theta = NULL, tol = 1e-12, maxiter = 1000){
q <- length(x) - 1
if(is.null(theta))
theta <- c(sqrt(x[1] + 2 * sum(x[-1])), rep(0, q))
storage.mode(theta) <- "double"
r <- .Call("_sarima_MAacvf0", theta)
crit <- 1e100
iter <- 0
while(crit > tol && iter <= maxiter){
iter <- iter + 1
T <- .Call("_sarima_DAcvfWrtMA", theta)
theta <- solve(T, r + x)
r <- ltsa::tacvfARMA(theta = -theta[-1]/theta[1], maxLag = q, sigma2 = theta[1]^2)
rnew <- .Call("_sarima_MAacvf0", as.double(theta))
crit <- sum((x - r)^2)
}
list(par = theta, value.objfn = crit, fpevals = iter,
objfevals = iter, convergence = if(iter > maxiter) 1 else 0)
}
|
summary.bootwrq <-
function(object,...)
{
noms <- rownames(object)[-nrow(object)]
tabnoms <- matrix(unlist(str_split(rownames(object)[-nrow(object)], pattern="_", n=3)),ncol=3,byrow=TRUE)
tau <- unique(as.numeric(tabnoms[,2]))
dots <- list(...)
isrq <- sapply(dots,function(x) class(x) %in% c("rq","rqs"))
m <- NULL
if(any(isrq))
{
j <- which(isrq==TRUE)[1]
m <- dots[[j]]
}
if(!is.null(m))
{
if(any(tau != m$tau)) stop("Quantiles should be the same in model m as in the bootstrap results")
if(length(tau==1))
{
if(any(tabnoms[,3] != names(m$coef))) stop("Coefficients should be in the same order in the model m than in the bootstrap results")
}
else
{
if(any(tabnoms[,3] != rep(rownames(m$coef),length(tau)))) stop("Coefficients should be in the same order in the model m than in the bootstrap results")
}
}
res0 <- NULL
if(length(grep("calc0",noms)))
{
for(j in 1:length(tau))
{
x0tau <- object[grep(paste("calc0",tau[j],sep="_"),noms),,drop=FALSE]
if(is.null(m))
{
m0tau <- apply(x0tau,1,mean)
}
else
{
if(length(tau)>1)
{
m0tau <- coef(m)[,j]
}
else
{
m0tau <- coef(m)
}
}
s0tau <- apply(x0tau,1,sd)
p0tau <- 2*pnorm(abs(m0tau/s0tau),lower.tail=FALSE)
res0 <- rbind(res0,cbind(m0tau,s0tau,p0tau))
}
colnames(res0) <- c("coef","se","p-value")
rownames(res0) <- tabnoms[1:nrow(res0),3]
cat(" Without computation of the weights in each bootstrap sample :\n")
cat("\n")
k <- 0
for(j in 1:length(tau))
{
cat("Quantile regression estimates for tau =",tau[j]," :\n")
print(res0[k+1:(nrow(res0)/length(tau)),])
k <- k+nrow(res0)/length(tau)
cat("\n")
}
}
res1 <- NULL
if(length(grep("calc1",noms)))
{
for(j in 1:length(tau))
{
x1tau <- object[grep(paste("calc1",tau[j],sep="_"),noms),,drop=FALSE]
if(is.null(m))
{
m1tau <- apply(x1tau,1,mean)
}
else
{
if(length(tau)>1)
{
m1tau <- coef(m)[,j]
}
else
{
m1tau <- coef(m)
}
}
s1tau <- apply(x1tau,1,sd)
p1tau <- 2*pnorm(abs(m1tau/s1tau),lower.tail=FALSE)
res1 <- rbind(res1,cbind(m1tau,s1tau,p1tau))
}
colnames(res1) <- c("coef","se","p-value")
rownames(res1) <- tabnoms[length(tabnoms[,3])-(nrow(res1)-1):0,3]
cat(" With computation of the weights in each bootstrap sample :\n")
cat("\n")
k <- 0
for(j in 1:length(tau))
{
cat("Quantile regression estimates for tau =",tau[j]," :\n")
print(res1[k+1:(nrow(res1)/length(tau)),])
k <- k+nrow(res1)/length(tau)
cat("\n")
}
}
return(invisible(list(results0=res0,results1=res1)))
}
|
showNotification <- function(ui, action = NULL, duration = 5,
closeButton = TRUE, id = NULL,
type = c("default", "message", "warning", "error"),
session = getDefaultReactiveDomain())
{
if (is.null(id))
id <- createUniqueId(8)
res <- processDeps(ui, session)
actionRes <- processDeps(action, session)
session$sendNotification("show",
list(
html = res$html,
action = actionRes$html,
deps = c(res$deps, actionRes$deps),
duration = if (!is.null(duration)) duration * 1000,
closeButton = closeButton,
id = id,
type = match.arg(type)
)
)
id
}
removeNotification <- function(id, session = getDefaultReactiveDomain()) {
force(id)
session$sendNotification("remove", id)
id
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(readr)
library(tibble)
library(ggplot2)
theme_set(theme_dark())
library(speakr)
formants <- read_lines(system.file("extdata", "formants.csv", package = "speakr"))
cat(formants)
cat(formants)
f_tbl <- read_csv(I(formants))
class(f_tbl)
glimpse(f_tbl)
f_bark <- read_csv(system.file("extdata", "formants-bark.csv", package = "speakr"))
f_bark
f_bark %>%
ggplot(aes(F2, F1, label = vowel)) +
geom_label(size = 10) +
labs(
title = "Vowel plot",
x = "F2 (Bark)",
y = "F1 (Bark)"
) +
scale_x_reverse(position = "top", limits = c(14, 7)) +
scale_y_reverse(position = "right", limits = c(8, 2))
|
ukc_crime_no_location <- function(force, crime_category = NULL, date = NULL) {
if (missing(force)) {
stop("The police force must be specified", call. = FALSE)
} else {
force_query <- paste0("&force=", force)
}
date_query <- ukc_date_processing(date)
if (is.null(crime_category)) {
crime_query <- "all-crime&"
} else {
crime_query <- paste0(crime_category, "&")
}
query <- paste0(
"crimes-no-location?category=", crime_query,
force_query, date_query
)
df <- ukc_get_data(query)
df
}
|
gob.ar <- function(level){
if(!level %in% 1:3) return(NULL)
if(level==1)
by <- NULL
if(level==2)
by <- "prov"
if(level==3)
by <- "dep"
url.cases <- "https://sisa.msal.gov.ar/datos/descargas/covid-19/files/Covid19Casos.zip"
x.cases <- read.zip(url.cases, files = "Covid19Casos.csv", method = "wget", xsv = TRUE,
select = c("clasificacion_resumen", "fecha_apertura", "fecha_fallecimiento",
"residencia_provincia_id", "residencia_departamento_id"))
x.cases <- map_data(x.cases[[1]], c(
"clasificacion_resumen" = "type",
"fecha_apertura" = "date_confirmed",
"fecha_fallecimiento" = "date_deaths",
"residencia_provincia_id" = "prov",
"residencia_departamento_id" = "dep"
))
x.cases <- x.cases[x.cases$type=="Confirmado",]
x.cases$prov <- sprintf("%.02d", x.cases$prov)
x.cases$dep <- paste0(x.cases$prov, sprintf("%.03d", x.cases$dep))
x.confirmed <- x.cases %>%
rename(date = date_confirmed) %>%
group_by_at(c("date", by)) %>%
summarize(confirmed = n()) %>%
group_by_at(by) %>%
arrange(date) %>%
mutate(confirmed = cumsum(confirmed))
x.deaths <- x.cases %>%
rename(date = date_deaths) %>%
filter(!is.na(date)) %>%
group_by_at(c("date", by)) %>%
summarize(deaths = n()) %>%
group_by_at(by) %>%
arrange(date) %>%
mutate(deaths = cumsum(deaths))
url.tests <- "https://sisa.msal.gov.ar/datos/descargas/covid-19/files/Covid19Determinaciones.zip"
x.tests <- read.zip(url.tests, files = "Covid19Determinaciones.csv", fread = TRUE)
x.tests <- map_data(x.tests[[1]], c(
"fecha" = "date",
"codigo_indec_provincia" = "prov",
"codigo_indec_departamento" = "dep",
"positivos" = "confirmed",
"total" = "tests"
))
x.tests$prov <- sprintf("%.02d", x.tests$prov)
x.tests$dep <- paste0(x.tests$prov, sprintf("%.03d", x.tests$dep))
x.tests <- x.tests %>%
group_by_at(c("date", by)) %>%
summarise(tests = sum(tests),
confirmed = sum(confirmed)) %>%
group_by_at(by) %>%
arrange(date) %>%
mutate(tests = cumsum(tests),
confirmed = cumsum(confirmed))
url.vacc <- "https://sisa.msal.gov.ar/datos/descargas/covid-19/files/datos_nomivac_covid19.zip"
x.vacc <- read.zip(url.vacc, files = "datos_nomivac_covid19.csv", method = "wget", xsv = TRUE,
select = c("fecha_aplicacion", "jurisdiccion_residencia_id", "depto_residencia_id", "orden_dosis"))
x.vacc <- map_data(x.vacc[[1]], c(
"fecha_aplicacion" = "date",
"jurisdiccion_residencia_id" = "prov",
"depto_residencia_id" = "dep",
"orden_dosis" = "dose"
))
x.vacc$prov <- sprintf("%.02d", x.vacc$prov)
x.vacc$dep <- paste0(x.vacc$prov, sprintf("%.03d", x.vacc$dep))
x.vacc <- x.vacc %>%
group_by_at(c("date", by)) %>%
summarize(vaccines = n(),
people_vaccinated = sum(dose==1),
people_fully_vaccinated = sum(dose==2)) %>%
group_by_at(by) %>%
arrange(date) %>%
mutate(vaccines = cumsum(vaccines),
people_vaccinated = cumsum(people_vaccinated),
people_fully_vaccinated = cumsum(people_fully_vaccinated))
x <- x.deaths %>%
full_join(x.tests, by = c("date", by)) %>%
full_join(x.vacc, by = c("date", by))
if(level!=3){
x <- x %>%
select(-confirmed) %>%
full_join(x.confirmed, by = c("date", by))
}
x <- x %>%
mutate(date = as.Date(date)) %>%
filter(!is.na(date) & date>="2020-01-01")
x <- x %>%
group_by_at(by) %>%
arrange(date) %>%
fill(confirmed, deaths, tests, vaccines, people_vaccinated, people_fully_vaccinated) %>%
ungroup() %>%
mutate(confirmed = replace(confirmed, date>max(x.confirmed$date), NA),
deaths = replace(deaths, date>max(x.deaths$date), NA),
tests = replace(tests, date>max(x.tests$date), NA),
vaccines = replace(vaccines, date>max(x.vacc$date), NA),
people_vaccinated = replace(people_vaccinated, date>max(x.vacc$date), NA),
people_fully_vaccinated = replace(people_fully_vaccinated, date>max(x.vacc$date), NA))
if(level==2){
x <- x %>%
filter(prov!="99" & prov!="00") %>%
mutate(prov = as.integer(prov))
}
if(level==3){
x <- x %>%
filter(!startsWith(dep, "99") & !endsWith(dep, "999") & !startsWith(dep, "00") & !endsWith(dep, "000")) %>%
mutate(dep = as.integer(dep))
}
return(x)
}
|
setMethod("center", "RobModel", function(object) object@center)
setMethod("neighbor", "RobModel", function(object) object@neighbor)
setReplaceMethod("center", "RobModel",
function(object, value){ object@center <- value; object })
setReplaceMethod("neighbor", "RobModel",
function(object, value){ object@neighbor <- value; object })
|
get_subsample_definitions <- function(country=NULL, loadtype='t', species='PCAB') {
stopifnot(loadtype %in% c('be', 't'));
stopifnot(species %in% c('PCAB'));
gdps <- WoodSimulatR::gdp_data;
gdps <- gdps[gdps$loadtype == loadtype & gdps$species == species, ];
stopifnot(all(c('country', 'subsample', 'share', 'f_mean', 'f_sd') %in% names(gdps)))
if (is.null(country)) {
gdps$share <- 1;
} else {
if (is.character(country)) {
n <- country;
country <- rep(1, length(n))
names(country) <- n;
}
stopifnot(is.numeric(country));
stopifnot(all(country > 0));
if (length(country) == 1 && is.null(names(country))) {
country <- rep(1, country);
}
if (is.null(names(country))) {
names(country) <- paste0('C', 1 : length(country));
}
n <- names(country);
if (any(n == '')) {
names(country) <- ifelse(
n == '',
paste0('C', 1 : length(country)),
names(country)
);
}
f_mean <- range(gdps$f_mean);
f_cov <- range(gdps$f_sd / gdps$f_mean);
E_mean <- range(gdps$E_mean);
E_cov <- range(gdps$E_sd / gdps$E_mean);
rho_mean <- range(gdps$rho_mean);
rho_cov <- range(gdps$rho_sd / gdps$rho_mean);
gdps <- dplyr::left_join(
tibble::tibble(subsample = names(country), share=country),
dplyr::select(gdps, -.data$share),
by='subsample')
i <- is.na(gdps$country);
if (sum(i) > 0) {
n_subsets <- sum(i);
gdps$loadtype[i] <- loadtype;
gdps$country[i] <- gdps$subsample[i];
gdps$f_mean[i] <- stats::runif(n_subsets, f_mean[1], f_mean[2]);
gdps$f_sd[i] <- stats::runif(n_subsets, f_cov[1], f_cov[2]) * gdps$f_mean[i];
gdps$E_mean[i] <- stats::runif(n_subsets, E_mean[1], E_mean[2]);
gdps$E_sd[i] <- stats::runif(n_subsets, E_cov[1], E_cov[2]) * gdps$E_mean[i];
gdps$rho_mean[i] <- stats::runif(n_subsets, rho_mean[1], rho_mean[2]);
gdps$rho_sd[i] <- stats::runif(n_subsets, rho_cov[1], rho_cov[2]) * gdps$rho_mean[i];
gdps$literature[i] <- '<simulated>';
gdps$species[i] <- species;
}
gdps$subsample[!i] <- gdps$country[!i];
dups <- dplyr::summarise(dplyr::group_by(gdps, .data$subsample), n=dplyr::n());
nums <- dplyr::mutate(dplyr::group_by(gdps, .data$subsample), i=1, i=cumsum(i));
nums <- dplyr::left_join(dplyr::select(nums, .data$subsample, i), dups, by='subsample');
nums <- dplyr::mutate(nums, s2 = ifelse(n==1, .data$subsample, paste0(.data$subsample, '_', i)));
gdps$subsample <- nums$s2;
gdps$project <- NULL;
}
dplyr::ungroup(gdps);
}
|
coef.gensvm <- function(object, ...)
{
V <- object$V
x <- eval.parent(object$call$x)
if (!is.null(colnames(x)) && length(colnames(x)) == dim(V)[1]) {
name <- c("translation", colnames(x))
rownames(V) <- name
}
return(V)
}
|
sevennum <-
function(x){
x<-na.omit(x)
result<-matrix(c(rep(0,7)),ncol=7)
result[,1]<-min(x);result[,2]<-quantile(x,0.1);result[,3]<-quantile(x,0.25)
result[,4]<-quantile(x,0.5);result[,5]<-quantile(x,0.75)
result[,6]<-quantile(x,0.90);result[,7]<-max(x)
dimnames(result)<-list(c(" "),c("Min.","10th Quan.","25th Quan.","50th Quan.","75th Quan.",
"90th Quan.","Max."))
result
}
|
context('multivar')
x <- NULL
y <- NULL
d <- NULL
o <- NULL
local({
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
N <- 3
T <- 2
K <- 2
beta <- c(.1, -.5)
dd <- generate_data(N=N, T=T, K=K, beta=beta)
x <<- dd$x
y <<- dd$y
d <<- data.frame(i = rep(seq_len(N), each=T+1),
t = rep(seq_len(T+1), N),
matrix(aperm(x, c(1, 3, 2)), N*(T+1), K,
dimnames = list(NULL, paste0('x', seq(K)))),
y = c(y))
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
o <<- opm(y~x1+x2, d, n.samp = 10)
})
test_that('data', {
expect_equal(x, array(c(-1.31047564655221, -0.289083794010798,
-0.349228549405948, -0.679491608575424,
-1.19566197009996, 1.03691313680308,
-0.23017748948328, -1.26506123460653,
0.11068271594512, 0.129287735160946,
1.22408179743946, 0.497850478229239,
2.30870831414912, 0.0631471481064739,
0.194158865245925, 2.46506498688328,
1.10981382705736, -1.21661715662964),
dim = c(3, 2, 3)))
expect_equal(y, matrix(c(-0.0899458588038237, -0.694025238411308,
-2.52543131039704, -0.560453024256735,
-2.04477798261599, -2.94693926957052,
-1.06948536801357, -0.812226112015961,
2.05939845332596),
nrow = 3, ncol = 3))
})
test_that('default', {
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
expect_equal(opm(x, y, n = 10),
structure(list(samples = list(rho = c(0.805, 0.425,
-0.181, 0.763,
0.581, 0.965,
0.0559999999999999, 0.533,
0.648, -0.086),
sig2 = 1 / c(11.6175662271191,
0.919115793520271,
0.989369792715488,
0.00440918521157215,
1.35621264272223,
4.24440799476086,
0.0931249250470442,
1.56847551750474,
0.371922970545138,
5.00022577787265),
beta = matrix(c(0.149966256134789, -1.07201170366086,
-3.32784640301039, 6.31976053552415,
0.399370400131068, -0.409833517459282,
0.942409502841064, -1.01613441888489,
-1.06148590924992, -1.70364397749032,
-0.746392848950218, -1.22143920569537,
-1.63866906134468, 7.01947247537598,
-0.536929048279301, -0.845295844019301,
-0.565341215754439, 0.0765501718682319,
-0.171463431207414, -1.13494915857112),
10, 2)),
fitted.values = matrix(c(0.878931188971585,
-0.878931188971585, 0.665670601363721, -0.665670601363721, -0.787856768435423,
0.787856768435423), 2, 3),
residuals = matrix(c(0.0367718470212829,
-0.0367718470212828, -0.214589957886459, 0.214589957886458, -0.647955514235535,
0.647955514235536), 2, 3),
df.residual = 2*3 - 3,
logLik = 0.704787094195681,
design = "balanced",
call = quote(opm(x = x, y = y, n.samp = 10)),
.Environment = environment(),
time.indicators = FALSE),
class = 'opm'))
})
test_that('named matrix', {
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
colnames(x) <- c('x1', 'x2')
expect_equal(opm(x, y, n = 10),
structure(list(samples = list(rho = c(0.805, 0.425,
-0.181, 0.763,
0.581, 0.965,
0.0559999999999999, 0.533,
0.648, -0.086),
sig2 = 1 / c(11.6175662271191,
0.919115793520271,
0.989369792715488,
0.00440918521157215,
1.35621264272223,
4.24440799476086,
0.0931249250470442,
1.56847551750474,
0.371922970545138,
5.00022577787265),
beta = matrix(c(0.149966256134789, -1.07201170366086,
-3.32784640301039, 6.31976053552415,
0.399370400131068, -0.409833517459282,
0.942409502841064, -1.01613441888489,
-1.06148590924992, -1.70364397749032,
-0.746392848950218, -1.22143920569537,
-1.63866906134468, 7.01947247537598,
-0.536929048279301, -0.845295844019301,
-0.565341215754439, 0.0765501718682319,
-0.171463431207414, -1.13494915857112),
10, 2, dimnames = list(NULL, c('x1', 'x2')))),
fitted.values = matrix(c(0.878931188971585,
-0.878931188971585, 0.665670601363721, -0.665670601363721, -0.787856768435423,
0.787856768435423), 2, 3),
residuals = matrix(c(0.0367718470212829,
-0.0367718470212828, -0.214589957886459, 0.214589957886458, -0.647955514235535,
0.647955514235536), 2, 3),
df.residual = 2*3 - 3,
logLik = 0.704787094195681,
design = "balanced",
call = quote(opm(x = x, y = y, n.samp = 10)),
.Environment = environment(),
time.indicators = FALSE),
class = 'opm'))
})
test_that('formula', {
expected <- structure(list(samples = list(rho = c(0.805, 0.425,
-0.181, 0.763,
0.581, 0.965,
0.0559999999999999, 0.533,
0.648, -0.086),
sig2 = 1 / c(11.6175662271191,
0.919115793520271,
0.989369792715488,
0.00440918521157215,
1.35621264272223,
4.24440799476086,
0.0931249250470442,
1.56847551750474,
0.371922970545138,
5.00022577787265),
beta = matrix(c(0.149966256134789, -1.07201170366086,
-3.32784640301039, 6.31976053552415,
0.399370400131068, -0.409833517459282,
0.942409502841064, -1.01613441888489,
-1.06148590924992, -1.70364397749032,
-0.746392848950218, -1.22143920569537,
-1.63866906134468, 7.01947247537598,
-0.536929048279301, -0.845295844019301,
-0.565341215754439, 0.0765501718682319,
-0.171463431207414, -1.13494915857112),
10, 2, dimnames = list(NULL, c('x1', 'x2')))),
fitted.values = matrix(c(0.878931188971585,
-0.878931188971585, 0.665670601363721, -0.665670601363721, -0.787856768435423,
0.787856768435423), 2, 3),
residuals = matrix(c(0.0367718470212829,
-0.0367718470212828, -0.214589957886459, 0.214589957886458, -0.647955514235535,
0.647955514235536), 2, 3,
dimnames = list(t=2:3, i=1:3)),
df.residual = 2*3 - 3,
logLik = 0.704787094195681,
design = "balanced",
call = quote(opm(x = y~x1+x2, data = d, n.samp = 10)),
.Environment = environment(),
time.indicators = FALSE,
index = c('i', 't'),
terms = structure(y~x1+x2,
variables = quote(list(y, x1, x2)),
factors = matrix(c(0, 1, 0, 0, 0, 1), 3, 2,
dimnames=list(c('y', 'x1', 'x2'),
c('x1', 'x2'))),
term.labels = c('x1', 'x2'),
order = c(1L, 1L),
intercept = 0L,
response = 1L,
.Environment = parent.frame(),
predvars = quote(list(y, x1, x2)),
dataClasses = c(y='numeric', x1='numeric', x2='numeric'),
class=c('terms', 'formula'))),
class = 'opm')
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
expect_equal(opm(y~x1+x2, d,
n.samp = 10),
expected)
d <- d[,c('y', 'x1', 't', 'i', 'x2')]
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
expected$call <- quote(opm(x = y~x1+x2, data = d,
index = 4:3, n.samp = 10))
expect_equal(opm(y~x1+x2, d, index=4:3,
n.samp = 10),
expected)
set.seed(123)
expected$call <- quote(opm(x = y~x1+x2, data = d,
index = c('i', 't'), n.samp = 10))
expect_equal(opm(y~x1+x2, d, index=c('i', 't'), n.samp = 10),
expected)
})
test_that('early dropouts', {
suppressWarnings(RNGversion("3.5.0"))
set.seed(123, kind = "Mersenne-Twister", normal.kind = "Inversion")
xx <- array(NA, dim=dim(x) + c(0, 0, 1))
xx[,,seq_len(ncol(y))] <- x
yy <- matrix(NA, nrow(y), ncol(y)+1)
yy[,seq_len(ncol(y))] <- y
expect_equal(dim(xx), dim(x)+c(0,0,1))
expect_equal(dim(yy), dim(y)+c(0,1))
expect_equal(opm(xx, yy, n = 10),
structure(list(samples = list(rho = c(0.805, 0.425,
-0.181, 0.763,
0.581, 0.965,
0.0559999999999999, 0.533,
0.648, -0.086),
sig2 = 1 / c(11.6175662271191,
0.919115793520271,
0.989369792715488,
0.00440918521157215,
1.35621264272223,
4.24440799476086,
0.0931249250470442,
1.56847551750474,
0.371922970545138,
5.00022577787265),
beta = matrix(c(0.149966256134789, -1.07201170366086,
-3.32784640301039, 6.31976053552415,
0.399370400131068, -0.409833517459282,
0.942409502841064, -1.01613441888489,
-1.06148590924992, -1.70364397749032,
-0.746392848950218, -1.22143920569537,
-1.63866906134468, 7.01947247537598,
-0.536929048279301, -0.845295844019301,
-0.565341215754439, 0.0765501718682319,
-0.171463431207414, -1.13494915857112),
10, 2)),
fitted.values = matrix(c(0.878931188971585, -0.878931188971585,
0.665670601363721, -0.665670601363721,
-0.787856768435423, 0.787856768435423,
0, 0), 2, 4),
residuals = matrix(c(0.0367718470212829, -0.0367718470212828,
-0.214589957886459, 0.214589957886458,
-0.647955514235535, 0.647955514235536,
0, 0), 2, 4),
df.residual = 2*3 - 3,
logLik = 0.637475935193608,
design = "unbalanced (with dropouts)",
call = quote(opm(x = xx, y = yy, n.samp = 10)),
.Environment = environment(),
time.indicators = FALSE),
class = 'opm'))
})
test_that('confint', {
expect_equal(confint(o),
matrix(c(-0.159625, 0.111707292991574,
-2.96240085726837, -1.54479234382358,
0.929, 178.18554581309,
5.10985655317045, 5.45731495708674),
nrow = 4, ncol = 2,
dimnames = list(c("rho", "sig2", "beta.x1", "beta.x2"),
c("2.5%", "97.5%"))))
expect_equal(confint(o, 1:2, level = 0.68),
matrix(c(-0.0235200000000001, 0.215660754512765,
0.78652, 7.19646832807839),
nrow = 2, ncol = 2,
dimnames = list(c("rho", "sig2"), c("16%", "84%"))))
})
test_that('coef', {
expect_equal(coef(o),
c(rho = 0.557,
sig2 = 0.874045960780248,
beta.x1 = -0.712983968172086,
beta.x2 = -0.655867032352328))
expect_error(coef(o, probs = .6), "Arguments 'probs' and 'names' are not allowed")
expect_error(coef(o, names = TRUE), "Arguments 'probs' and 'names' are not allowed")
})
test_that('print', {
expect_equal(capture.output(o),
c('\tPanel design: balanced',
'',
'Call:',
'opm(x = y ~ x1 + x2, data = d, n.samp = 10)',
'',
'Coefficients:',
' mean (SD) med 95-CI',
'rho 0.450900 (0.39) 0.55700 (-0.16, 0.93)',
'sig2 24.422159 (71.18) 0.87405 (0.11, 178.19)',
'beta.x1 -0.077945 (2.55) -0.71298 (-3.0, 5.1)',
'beta.x2 0.023554 (2.51) -0.65587 (-1.5, 5.5)',
''))
})
test_that('summary', {
expect_equal(capture.output(summary(o)),
c('Call:',
'opm(x = y ~ x1 + x2, data = d, n.samp = 10)',
'',
'Parameter estimates:',
' <--95CI <--68CI med 68CI--> 95CI-->',
'rho -0.15962 -0.02352 0.55700 0.786520 0.9290',
'sig2 0.11171 0.21566 0.87405 7.196468 178.1855',
'beta.x1 -2.96240 -1.42573 -0.71298 0.703472 5.1099',
'beta.x2 -1.54479 -1.18338 -0.65587 -0.032576 5.4573'))
})
test_that('DIC', {
expect_equal(DIC(o),
24.8318940856621)
})
|
LKinfoUpdate<- function( LKinfo, ...){
argList<- list( ...)
nArgs<- length( argList)
if( nArgs==0 ){
return( LKinfo)
}
argNames<- names( argList)
if( (argNames[1]=="lambda")& (nArgs==1) ){
LKinfo$lambda<- argList$lambda
return( LKinfo)
}
LKinfoNames<- names( LKinfo)
LKinfoSetupArgsNames<- names( LKinfo$setupArgs)
ind1<- match( argNames, LKinfoNames)
ind2<- match( argNames, LKinfoSetupArgsNames )
bad<- is.na(ind1)& is.na( ind2)
if( any( bad)) {
stop(
cat( "No match in current LKinfo for these new argument(s) ",
argNames[bad]
)
)
}
setupArgsNew<- LKinfo$setupArgs
LKinfoNew<- LKinfo
LKinfoNew$setupArgs<- NULL
if( any( !is.na(ind1) ) ){
for( argN in LKinfoNames[ind1]){
LKinfoNew[[ argN]] <- argList[[ argN ]]
}
}
if( any( !is.na(ind2) ) ){
for( argN in LKinfoSetupArgsNames[ind2]){
setupArgsNew[[argN]] <- argList[[ argN]]
}
}
LKinfoNew <- do.call( "LKrigSetup" , c( LKinfoNew, setupArgsNew) )
return(LKinfoNew)
}
|
set.seed(1234)
test_that("quick plots render correctly", {
expect_doppelganger("ggdag_m_bias() is an M", ggdag_m_bias())
expect_doppelganger("ggdag_butterfly_bias() is a butterfly", ggdag_butterfly_bias())
expect_doppelganger("ggdag_confounder_triangle() is triangle", ggdag_confounder_triangle())
expect_doppelganger("ggdag_collider_triangle() is triangle, too", ggdag_collider_triangle())
})
|
options_b90 <- set_optionsLWFB90()
param_b90 <- set_paramLWFB90()
standprop <- make_standprop(options_b90,
param_b90,
out_yrs = 2002:2004)
plot(standprop$dates, standprop$lai, type = "l")
|
"er_network"
|
context('test stats')
test_that('fortify.stl works for AirPassengers', {
fortified <- ggplot2::fortify(stats::stl(AirPassengers, s.window = 'periodic'))
expect_true(is.data.frame(fortified))
expected_names <- c('Index', 'Data', 'seasonal', 'trend', 'remainder')
expect_equal(names(fortified), expected_names)
expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']]))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
fortified <- ggplot2::fortify(stats::decompose(AirPassengers))
expect_true(is.data.frame(fortified))
expected_names <- c('Index', 'Data', 'seasonal', 'trend', 'remainder')
expect_equal(names(fortified), expected_names)
expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']]))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
})
test_that('fortify.Arima works for AirPassengers', {
skip_if_not_installed("forecast")
skip_if_not_installed("fGarch")
fortified <- ggplot2::fortify(ar(AirPassengers))
expect_true(is.data.frame(fortified))
expected_names <- c('Index', 'Data', 'Fitted', 'Residuals')
expect_equal(names(fortified), expected_names)
expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']]))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
x <- AirPassengers
m <- stats::ar(x)
x <- NULL
fortified2 <- ggplot2::fortify(m, data = AirPassengers)
expect_equal(fortified, fortified2)
ggplot2::autoplot(m, data = AirPassengers)
fortified <- ggplot2::fortify(stats::arima(AirPassengers))
expect_true(is.data.frame(fortified))
expected_names <- c('Index', 'Data', 'Fitted', 'Residuals')
expect_equal(names(fortified), expected_names)
expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']]))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
ggplot2::autoplot(stats::arima(AirPassengers))
x <- AirPassengers
m <- stats::arima(x)
x <- NULL
fortified2 <- ggplot2::fortify(m, data = AirPassengers)
expect_equal(fortified, fortified2)
ggplot2::autoplot(m, data = AirPassengers)
fortified <- ggplot2::fortify(stats::HoltWinters(AirPassengers))
expect_true(is.data.frame(fortified))
expected_names <- c('Index', 'Data', 'xhat', 'level', 'trend', 'season', 'Residuals')
expect_equal(names(fortified), expected_names)
expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']]))
expect_equal(fortified$Index[1], as.Date('1949-01-01'))
expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01'))
library(fGarch)
d.fGarch <- fGarch::garchFit(formula = ~arma(1, 1) + garch(1, 1), data = UKgas, trace = FALSE)
fortified <- ggplot2::fortify(d.fGarch)
expected_names <- c('Index', 'Data', 'Fitted', 'Residuals')
expect_equal(names(fortified), expected_names)
})
test_that('fortify.prcomp works for iris', {
df <- iris[c(1, 2, 3, 4)]
pcs <- c('PC1', 'PC2', 'PC3', 'PC4')
expected_names <- c(names(df), pcs)
fortified <- ggplot2::fortify(stats::prcomp(df, center = TRUE, scale = TRUE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df)
expect_equal(rownames(fortified), rownames(df))
fortified <- ggplot2::fortify(stats::prcomp(df, center = FALSE, scale = TRUE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df)
expect_equal(rownames(fortified), rownames(df))
fortified <- ggplot2::fortify(stats::prcomp(df, center = TRUE, scale = FALSE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df)
expect_equal(rownames(fortified), rownames(df))
fortified <- ggplot2::fortify(stats::prcomp(df, center = FALSE, scale = FALSE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df)
expect_equal(rownames(fortified), rownames(df))
expected_names <- c(names(df), 'Species', pcs)
fortified <- ggplot2::fortify(stats::prcomp(df), data = iris)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4, 5)]), iris)
expect_equal(rownames(fortified), rownames(df))
tmp <- stats::prcomp(df)
class(tmp) <- 'unsupportedClass'
expect_error(ggplot2::fortify(tmp, data = iris))
})
test_that('fortify.princomp works for iris', {
df <- iris[c(1, 2, 3, 4)]
pcs <- c('Comp.1', 'Comp.2', 'Comp.3', 'Comp.4')
expected_names <- c(names(df), pcs)
fortified <- ggplot2::fortify(stats::princomp(df))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df)
expect_equal(rownames(fortified), rownames(df))
expected_names <- c(names(df), 'Species', pcs)
fortified <- ggplot2::fortify(stats::princomp(df), data = iris)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4, 5)]), iris)
expect_equal(rownames(fortified), rownames(df))
p <- ggplot2::autoplot(stats::princomp(df), data = iris, colour = 'Species')
expect_true(is(p, 'ggplot'))
p <- ggplot2::autoplot(stats::princomp(df), data = iris, loadings.label = TRUE)
expect_true(is(p, 'ggplot'))
p <- ggplot2::autoplot(stats::princomp(df), data = iris, frame.type = 'convex')
expect_true(is(p, 'ggplot'))
expect_error(ggplot2::autoplot(stats::princomp(df), frame.type = 'invalid'))
})
test_that('fortify.factanal works for state.x77', {
d.factanal <- stats::factanal(state.x77, factors = 3, scores = 'regression')
pcs <- c('Factor1', 'Factor2', 'Factor3')
fortified <- ggplot2::fortify(d.factanal)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), pcs)
expect_equal(rownames(fortified), rownames(state.x77))
fortified <- ggplot2::fortify(d.factanal, data = state.x77)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), c(colnames(state.x77), pcs))
expect_equal(rownames(fortified), rownames(state.x77))
})
test_that('fortify.prcomp works for USArrests', {
pcs <- c('PC1', 'PC2', 'PC3', 'PC4')
expected_names <- c(names(USArrests), pcs)
fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = TRUE, scale = TRUE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = FALSE, scale = TRUE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = TRUE, scale = FALSE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = FALSE, scale = FALSE))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
fortified <- ggplot2::fortify(stats::prcomp(USArrests), data = USArrests)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
})
test_that('fortify.princomp works for USArrests', {
pcs <- c('Comp.1', 'Comp.2', 'Comp.3', 'Comp.4')
expected_names <- c(names(USArrests), pcs)
fortified <- ggplot2::fortify(stats::princomp(USArrests))
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
fortified <- ggplot2::fortify(stats::princomp(USArrests), data = USArrests)
expect_true(is.data.frame(fortified))
expect_equal(names(fortified), expected_names)
expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests)
expect_equal(rownames(fortified), rownames(USArrests))
})
test_that('autoplot.prcomp works for iris with scale (default)', {
skip_on_cran()
obj <- stats::prcomp(iris[-5])
exp_x <- c(-0.10658039, -0.10777226, -0.11471510, -0.10901118, -0.10835099, -0.09056763)
exp_y <- c(-0.05293913, 0.02933742, 0.02402493, 0.05275710, -0.05415858, -0.12287329)
p <- ggplot2::autoplot(obj)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep('black', 6))
p <- ggplot2::autoplot(obj, data = iris, colour = 'Species')
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("
p <- ggplot2::autoplot(obj, data = iris, loadings = TRUE, loadings.label = FALSE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- ggplot2:::layer_data(p, 2)
expect_equal(ld$x, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$xend, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4)
expect_equal(ld$y, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$colour, rep("
p <- ggplot2::autoplot(obj, data = iris, loadings.label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 3)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
expect_true('GeomText' %in% class(p$layers[[3]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- ggplot2:::layer_data(p, 2)
expect_equal(ld$x, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$xend, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4)
expect_equal(ld$y, rep(0, 4))
expect_equal(ld$colour, rep("
ld <- ggplot2:::layer_data(p, 3)
expect_equal(ld$x, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4)
expect_equal(ld$y, c(-0.09241228, -0.10276734, 0.02440152, 0.01062366), tolerance = 1e-4)
expect_equal(ld$colour, rep("
expect_equal(ld$label, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"))
p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex')
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, c(0.15071626, 0.13846286, 0.12828254, -0.09474406, -0.10501689, -0.12769748), tolerance = 1e-4)
expect_equal(ld$y, c(-0.04265051, -0.19487526, -0.22776373, -0.22177981, -0.19537669, -0.02212193), tolerance = 1e-4)
expect_equal(ld$fill, rep("grey20", 6))
expect_equal(ld$alpha, rep(0.2, 6))
p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex', shape = FALSE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomText' %in% class(p$layers[[1]]$geom))
expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("
expect_equal(ld$label, c('1', '2', '3', '4', '5', '6'))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, c(0.15071626, 0.13846286, 0.12828254, -0.09474406, -0.10501689, -0.12769748), tolerance = 1e-4)
expect_equal(ld$y, c(-0.04265051, -0.19487526, -0.22776373, -0.22177981, -0.19537669, -0.02212193), tolerance = 1e-4)
expect_equal(ld$fill, rep("grey20", 6))
expect_equal(ld$alpha, rep(0.2, 6))
})
test_that('autoplot.prcomp works for iris without scale', {
skip_on_cran()
obj <- stats::prcomp(iris[-5])
exp_x <- c(-2.684126, -2.714142, -2.888991, -2.745343, -2.728717, -2.280860)
exp_y <- c(-0.3193972, 0.1770012, 0.1449494, 0.3182990, -0.3267545, -0.7413304)
p <- ggplot2::autoplot(obj, scale = 0.)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep('black', 6))
p <- ggplot2::autoplot(obj, scale = 0., data = iris, colour = 'Species')
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("
p <- ggplot2::autoplot(obj, scale = 0, data = iris,
loadings = TRUE, loadings.label = FALSE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- ggplot2:::layer_data(p, 2)
expect_equal(ld$x, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$xend, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4)
expect_equal(ld$y, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$colour, rep("
p <- ggplot2::autoplot(obj, scale = 0., data = iris,
loadings.label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 3)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
expect_true('GeomText' %in% class(p$layers[[3]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- ggplot2:::layer_data(p, 2)
expect_equal(ld$x, rep(0, 4), tolerance = 1e-4)
expect_equal(ld$xend, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4)
expect_equal(ld$y, rep(0, 4))
expect_equal(ld$colour, rep("
ld <- ggplot2:::layer_data(p, 3)
expect_equal(ld$x, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4)
expect_equal(ld$y, c(-0.9885610, -1.0993321, 0.2610301, 0.1136443), tolerance = 1e-4)
expect_equal(ld$colour, rep("
expect_equal(ld$label, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"))
p <- ggplot2::autoplot(obj, scale = 0., data = iris,
frame.type = 'convex')
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, c(3.795645, 3.487055, 3.230674, -2.386039, -2.644750, -3.215939), tolerance = 1e-4)
expect_equal(ld$y, c(-0.2573230, -1.1757393, -1.3741651, -1.3380623, -1.1787646, -0.1334681), tolerance = 1e-4)
expect_equal(ld$fill, rep("grey20", 6))
expect_equal(ld$alpha, rep(0.2, 6))
p <- ggplot2::autoplot(obj, scale = 0., data = iris,
frame.type = 'convex', shape = FALSE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomText' %in% class(p$layers[[1]]$geom))
expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("
expect_equal(ld$label, c('1', '2', '3', '4', '5', '6'))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, c(3.795645, 3.487055, 3.230674, -2.386039, -2.644750, -3.215939), tolerance = 1e-4)
expect_equal(ld$y, c(-0.2573230, -1.1757393, -1.3741651, -1.3380623, -1.1787646, -0.1334681), tolerance = 1e-4)
expect_equal(ld$fill, rep("grey20", 6))
expect_equal(ld$alpha, rep(0.2, 6))
})
test_that('autoplot.prcomp works for USArrests', {
skip_on_cran()
obj <- stats::prcomp(USArrests)
exp_x <- c(0.10944879, 0.15678261, 0.20954726, 0.03097574, 0.18143395, 0.05907333)
exp_y <- c(-0.11391408, -0.17894035, 0.08786745, -0.16621327, 0.22408730, 0.13651754)
p <- ggplot2::autoplot(obj, label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomText' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$label, c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"))
expect_equal(ld$colour, rep("
exp_x <- c(64.80216, 92.82745, 124.06822, 18.34004, 107.42295, 34.97599)
exp_y <- c(-11.448007, -17.982943, 8.830403, -16.703911, 22.520070, 13.719584)
p <- ggplot2::autoplot(obj, scale = 0., label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomText' %in% class(p$layers[[2]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep("black", 6))
ld <- head(ggplot2:::layer_data(p, 2))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$label, c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"))
expect_equal(ld$colour, rep("
})
test_that('autoplot.princomp works for iris', {
obj <- stats::princomp(iris[-5])
p <- ggplot2::autoplot(obj, data = iris, colour = 'Species')
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
p <- ggplot2::autoplot(obj, data = iris, loadings = TRUE, loadings.label = FALSE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
p <- ggplot2::autoplot(obj, data = iris, loadings.label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 3)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomSegment' %in% class(p$layers[[2]]$geom))
expect_true('GeomText' %in% class(p$layers[[3]]$geom))
p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex')
expect_true(is(p, 'ggplot'))
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom))
})
test_that('autoplot.prcomp plots the desired components', {
skip_on_cran()
obj <- stats::prcomp(iris[-5])
exp_x <- c(-0.0529391329513015, 0.0293374206773287, 0.0240249314006331,
0.0527570984441502, -0.0541585777198945, -0.1228732921883)
exp_y <- c(0.00815003672083961, 0.0614473273321588, -0.00522617400592586,
-0.00921410146450414, -0.0262996114135432, -0.0492472720451544
)
p <- ggplot2::autoplot(obj, x = 2, y = 3)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$x, exp_x, tolerance = 1e-4)
expect_equal(ld$y, exp_y, tolerance = 1e-4)
expect_equal(ld$colour, rep('black', 6))
expect_equal(p$labels$x, "PC2 (5.31%)")
expect_equal(p$labels$y, "PC3 (1.71%)")
})
test_that('autoplot.princomp plots the desired components', {
skip_on_travis()
skip_on_cran()
obj <- stats::princomp(iris[-5])
exp_x <- c(-0.0531164839772263, 0.0294357037689672, 0.0241054171584106,
0.052933839637522, -0.0543400139993682, -0.123284929161055)
exp_y <- c(-0.00817734010291634, -0.0616531816016784, 0.00524368217559065,
0.00924496956257505, 0.0263877175612184, 0.0494122549931978)
p <- ggplot2::autoplot(obj, x = 2, y = 3)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
ld <- head(ggplot2:::layer_data(p, 1))
expect_equal(ld$colour, rep('black', 6))
expect_equal(p$labels$x, "Comp.2 (5.31%)")
expect_equal(p$labels$y, "Comp.3 (1.71%)")
})
test_that('autoplot.factanal works for state.x77', {
obj <- stats::factanal(state.x77, factors = 3, scores = 'regression')
p <- ggplot2::autoplot(obj)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
p <- ggplot2::autoplot(obj, label = TRUE)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 2)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_true('GeomText' %in% class(p$layers[[2]]$geom))
})
test_that('autoplot.factanal plots the desired components', {
obj <- stats::factanal(state.x77, factors = 3, scores = 'regression')
p <- ggplot2::autoplot(obj, x = 2, y = 3)
expect_true(is(p, 'ggplot'))
expect_equal(length(p$layers), 1)
expect_true('GeomPoint' %in% class(p$layers[[1]]$geom))
expect_equal(p$labels$x, "Factor2 (20.15%)")
expect_equal(p$labels$y, "Factor3 (18.24%)")
})
test_that('fortify.dist works for eurodist', {
fortified <- ggplot2::fortify(eurodist)
expect_true(is.data.frame(fortified))
expect_equal(dim(fortified), c(21, 21))
})
test_that('fortify.lfda works for iris', {
skip_on_cran()
library(lfda)
k <- iris[, -5]
y <- iris[, 5]
r <- 3
model <- lfda(k, y, r, metric = "plain")
fortified <- ggplot2::fortify(model)
expect_true(is.data.frame(fortified))
model <- klfda(kmatrixGauss(k), y, r, metric = "plain")
fortified <- ggplot2::fortify(model)
expect_true(is.data.frame(fortified))
model <- self(k, y, beta=0.1, r, metric = "plain")
fortified <- ggplot2::fortify(model)
expect_true(is.data.frame(fortified))
})
test_that('autoplot.lfda works for iris', {
skip_on_cran()
k <- iris[, -5]
y <- iris[, 5]
r <- 4
model <- lfda::lfda(k, y, r, metric = "plain")
p <- autoplot(model, data=iris, frame = TRUE, frame.colour='Species')
expect_true(is(p, 'ggplot'))
})
test_that('autoplot.acf works', {
p <- autoplot(stats::acf(AirPassengers, plot = FALSE))
expect_true(is(p, 'ggplot'))
p <- autoplot(stats::acf(AirPassengers, plot = FALSE), conf.int.type = 'ma')
expect_true(is(p, 'ggplot'))
p <- autoplot(stats::pacf(AirPassengers, plot = FALSE))
expect_true(is(p, 'ggplot'))
p <- autoplot(stats::ccf(AirPassengers, AirPassengers, plot = FALSE))
expect_true(is(p, 'ggplot'))
})
test_that('autoplot.stepfun works', {
p <- autoplot(stepfun(c(1, 2, 3), c(4, 5, 6, 7)))
expect_true(is(p, 'ggplot'))
fortified <- fortify(stepfun(c(1, 2, 3), c(4, 5, 6, 7)))
expected <- data.frame(x = c(0, 1, 1, 2, 2, 3, 3, 4),
y = c(4, 4, 5, 5, 6, 6, 7, 7))
expect_equal(fortified, expected)
fortified <- fortify(stepfun(c(1), c(4, 5)))
expected <- data.frame(x = c(0.9375, 1.0000, 1.0000, 1.0625),
y = c(4, 4, 5, 5))
expect_equal(fortified, expected)
fortified <- fortify(stepfun(c(1, 3, 4, 8), c(4, 5, 2, 3, 5)))
expected <- data.frame(x = c(-1, 1, 1, 3, 3, 4, 4, 8, 8, 10),
y = c(4, 4, 5, 5, 2, 2, 3, 3, 5, 5))
expect_equal(fortified, expected)
fortified <- fortify(stepfun(c(1, 2, 3, 4, 5, 6, 7, 8, 10),
c(4, 5, 6, 7, 8, 9, 10, 11, 12, 9)))
expected <- data.frame(x = c(0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 10, 10, 11),
y = c(4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 9, 9))
expect_equal(fortified, expected)
})
test_that('autoplot.spec works', {
result <- stats::spec.ar(AirPassengers)
p <- autoplot(result)
expect_true(is(p, 'ggplot'))
expect_equal(sum(fortify(result)[1]), 1500, tolerance = 0.01)
expect_equal(sum(fortify(result)[2]), 684799.7, tolerance = 0.01)
})
|
coefficients.boots <- function(object, ncomp = object$ncomp, conf = .95) {
if ((object$val.method == "none" | object$val.method == "loo")) {
stop("No bootstrapping was done for this model")
}
conf <- conf
coefficients.boot.a <- do.call("rbind", object$validation$coefficients)
coefficients.boot <- as.matrix(coefficients.boot.a)
Upper <- 1 - (((1 - conf)/2))
Lower <- 1 - Upper
coefficients.boot.cis <- llply(ncomp, function(y) {
do.call("rbind", as.list(
by(coefficients.boot[, y], list(row.names(coefficients.boot)), function(x){
c(ncomp = y, boot.mean = mean(x, na.rm = T), Skewness = skewness(x, na.rm = T),
quantile(x, c(Lower, Upper), na.rm = T), 'Bootstrap Error' = sd(x, na.rm = T))
}
)))
})
names(coefficients.boot.cis) <- ncomp
OC <- data.frame(object$coefficients[, ncomp])
names(OC) <- ncomp
A <- llply(1:length(coefficients.boot.cis), function(x) {
x. <- names(coefficients.boot.cis)[x]
coefficients.boot.cis2 <- as.data.frame(coefficients.boot.cis[[x.]])
coefficients.boot.cis2$variable <- row.names(coefficients.boot.cis[[x.]])
row.names(coefficients.boot.cis2) <- NULL
Out <- coefficients.boot.cis2[as.factor(row.names(OC)), ]
Out$Actual <- OC[, x.]
Out$Bias <- Out$boot.mean - Out$Actual
Out$'t value' <- Out$Actual / Out$'Bootstrap Error'
Out$'bias t value' <- Out$Bias / Out$'Bootstrap Error'
Out[, c(1, 7, 8, 4:5, 2, 3, 9, 6, 10:11)]
})
A
}
|
get_genius_song_lyrics<-function(song_id, output = 'tibble', url = NULL,
access_token = Sys.getenv('GENIUS_API_TOKEN')){
output<-match.arg(output, c('tibble', 'text'))
if(is.null(url)){
url<-get_genius_song(song_id = song_id, access_token = access_token) %>% .$url
} else {url<-url}
lyrics<-read_html(url) %>% html_nodes('p') %>% html_text()
removing<-purrr::partial(str_replace_all, pattern = '\\[.*?\\]', replacement = '')
removing2<-purrr::partial(str_replace_all, pattern = '\n', replacement = ' ')
if(output == 'text'){
lyrics<-lyrics[1] %>% removing() %>% removing2()
} else{
lyrics<- str_split(lyrics, pattern = '\n')[[1]] %>%
enframe(name = NULL, value = 'Lyrics') %>%
apply(., 2, removing) %>% as_tibble() %>% filter(Lyrics != '')
}
return(lyrics)
}
|
utils::globalVariables(c("dscore", "donor_proportion", "ctypes", "AUC", "Specificity",
"Precision", "subtype_names","subtype_associations","dsc",
"prop", "cell_types", "myx", "myy"))
get_subtype_prop_associations <- function(container, max_res, stat_type,
integration_var=NULL, min_cells_group=50,
use_existing_subc=FALSE,
alt_ct_names=NULL,n_col=2) {
if (!(stat_type %in% c("fstat","adj_rsq","adj_pval"))) {
stop("stat_type parameter is not one of the three options")
}
if (is.null(integration_var)) {
if (!use_existing_subc) {
if (is.null(container$embedding)) {
stop("need to set integration_var parameter to get an embedding")
}
}
} else {
container <- reduce_dimensions(container,integration_var)
}
container$embedding$clusters$leiden$groups <- factor(container$embedding$clusters$leiden$groups,
levels=unique(container$embedding$clusters$leiden$groups))
donor_scores <- container$tucker_results[[1]]
res <- data.frame(matrix(ncol = 4, nrow = 0))
colnames(res) <- c(stat_type,'resolution','factor','ctype')
if (use_existing_subc) {
subc_all <- container$subclusters
} else {
subc_all <- list()
}
for (ct in container$experiment_params$ctypes_use) {
scMinimal <- container[["scMinimal_ctype"]][[ct]]
cluster_res <- seq(.5,max_res,by=.1)
for (r in cluster_res) {
if (!use_existing_subc) {
subclusts <- get_subclusters(container,ct,r,min_cells_group=min_cells_group,
small_clust_action='remove')
subclusts <- subclusts + 1
subc_all[[ct]][[paste0('res:',as.character(r))]] <- subclusts
} else {
if (!is.null(alt_ct_names)) {
ct_ndx <- which(container$experiment_params$ctypes_use==ct)
ct_new <- alt_ct_names[ct_ndx]
subclusts <- container$subclusters[[ct_new]][[paste0('res:',as.character(r))]]
} else {
subclusts <- container$subclusters[[ct]][[paste0('res:',as.character(r))]]
}
}
num_subclusts <- length(unique(subclusts))
if (num_subclusts > 1) {
cell_intersect <- intersect(names(subclusts),rownames(scMinimal$metadata))
sub_meta_tmp <- scMinimal$metadata[cell_intersect,]
donor_props <- compute_donor_props(subclusts,sub_meta_tmp)
donor_balances <- coda.base::coordinates(donor_props)
rownames(donor_balances) <- rownames(donor_props)
reg_stats <- compute_associations(donor_balances,donor_scores,stat_type)
colnames(donor_props) <- sapply(1:ncol(donor_props),function(x){paste0(ct,'_',x)})
} else {
if (stat_type=='fstat' || stat_type=='adj_rsq') {
reg_stats <- rep(0,ncol(container$tucker_results[[1]]))
} else if (stat_type=='adj_pval') {
reg_stats <- rep(1,ncol(container$tucker_results[[1]]))
}
}
for (i in 1:length(reg_stats)) {
new_row <- as.data.frame(list(reg_stats[i], r, paste0("Factor ", as.character(i)), ct),stringsAsFactors = F)
colnames(new_row) <- colnames(res)
res <- rbind(res,new_row)
}
}
}
if (stat_type=='adj_pval') {
res$adj_pval <- p.adjust(res$adj_pval,method = 'fdr')
}
reg_stat_plots <- plot_subclust_associations(res,n_col=n_col)
container$plots$subtype_prop_factor_associations <- reg_stat_plots
container$subclusters <- subc_all
container$subc_factor_association_res <- res
return(container)
}
get_subclusters <- function(container,ctype,resolution,min_cells_group=50,small_clust_action='merge') {
con <- container$embedding
clusts <- conos::findSubcommunities(con,method=conos::leiden.community, resolution=resolution, target.clusters=ctype)
ctype_bcodes <- rownames(container$scMinimal_ctype[[ctype]]$metadata)
clusts <- clusts[names(clusts) %in% ctype_bcodes]
if (small_clust_action=='remove') {
clust_sizes <- table(clusts)
clusts_keep <- names(clust_sizes)[clust_sizes > min_cells_group]
large_clusts <- clusts[clusts %in% clusts_keep]
} else if (small_clust_action=='merge') {
large_clusts <- merge_small_clusts(con,clusts,min_cells_group)
}
large_clusts <- sapply(large_clusts,function(x) {
return(as.numeric(strsplit(x,split='_')[[1]][2]))
})
return(large_clusts)
}
merge_small_clusts <- function(con,clusts,min_cells_group) {
clust_sizes <- table(clusts)
clusts_keep <- names(clust_sizes)[clust_sizes > min_cells_group]
clusts_merge <- names(clust_sizes)[clust_sizes <= min_cells_group]
coords <- con[["embedding"]]
get_centroid <- function(clust_name) {
ndx <- names(clusts)[clusts==clust_name]
x_y <- coords[ndx,]
if (length(ndx)>1) {
x_med <- stats::median(x_y[,1])
y_med <- stats::median(x_y[,2])
return(c(x_med,y_med))
} else {
return(x_y)
}
}
main_centroids <- lapply(clusts_keep,get_centroid)
names(main_centroids) <- clusts_keep
small_centroids <- lapply(clusts_merge,get_centroid)
names(small_centroids) <- clusts_merge
get_nearest_large_clust <- function(clust_name) {
cent <- small_centroids[[clust_name]]
c_distances <- c()
for (big_clust in names(main_centroids)) {
clust_dist <- sqrt(sum((main_centroids[[big_clust]] - cent)**2))
c_distances[big_clust] <- clust_dist
}
nearest_big_clust <- names(main_centroids)[which(c_distances == min(c_distances))]
return(nearest_big_clust)
}
for (cmerge in clusts_merge) {
merge_partner <- get_nearest_large_clust(cmerge)
clusts[clusts==cmerge] <- merge_partner
}
return(clusts)
}
get_ctype_prop_associations <- function(container,stat_type,n_col=2) {
all_cells <- c()
for (ct in container$experiment_params$ctypes_use) {
cells_in_ctype <- rownames(container$scMinimal_ctype[[ct]]$metadata)
all_cells <- c(all_cells,cells_in_ctype)
}
container$scMinimal_full$metadata <- container$scMinimal_full$metadata[all_cells,]
container$scMinimal_full$count_data <- container$scMinimal_full$count_data[,all_cells]
scMinimal <- container$scMinimal_full
donor_scores <- container$tucker_results[[1]]
metadata <- scMinimal$metadata
all_ctypes <- unique(as.character(metadata$ctypes))
cell_clusters <- sapply(as.character(metadata$ctypes),function(x){
return(which(all_ctypes %in% x))
})
names(cell_clusters) <- rownames(metadata)
donor_props <- compute_donor_props(cell_clusters,metadata)
donor_balances <- coda.base::coordinates(donor_props)
rownames(donor_balances) <- rownames(donor_props)
sig_res <- compute_associations(donor_balances,donor_scores,stat_type)
prop_figure <- plot_donor_props(donor_props, donor_scores, sig_res, all_ctypes,
stat_type, n_col=n_col)
container$plots$ctype_prop_factor_associations <- prop_figure
return(container)
}
get_ctype_subc_prop_associations <- function(container,ctype,res,n_col=2,alt_name=NULL) {
scMinimal <- container$scMinimal_ctype[[ctype]]
donor_scores <- container$tucker_results[[1]]
metadata <- scMinimal$metadata
if (!is.null(alt_name)) {
cell_clusters <- container[["subclusters"]][[alt_name]][[paste0('res:',as.character(res))]]
} else {
cell_clusters <- container[["subclusters"]][[ctype]][[paste0('res:',as.character(res))]]
}
cells_both <- intersect(names(cell_clusters),rownames(metadata))
cell_clusters <- cell_clusters[cells_both]
metadata <- metadata[cells_both,]
donor_props <- compute_donor_props(cell_clusters,metadata)
donor_balances <- coda.base::coordinates(donor_props)
rownames(donor_balances) <- rownames(donor_props)
sig_res <- compute_associations(donor_balances,donor_scores,'adj_pval')
all_ctypes <- sapply(1:ncol(donor_props), function(x) {
paste0(ctype,"_",x)
})
prop_figure <- plot_donor_props(donor_props, donor_scores, sig_res, all_ctypes,
'adj_pval', n_col=n_col)
container$plots$ctype_prop_factor_associations <- prop_figure
return(container)
}
reduce_dimensions <- function(container, integration_var, ncores =container$experiment_params$ncores) {
all_cells <- c()
for (ct in container$experiment_params$ctypes_use) {
cells_in_ctype <- rownames(container$scMinimal_ctype[[ct]]$metadata)
all_cells <- c(all_cells,cells_in_ctype)
}
container$scMinimal_full$metadata <- container$scMinimal_full$metadata[all_cells,]
container$scMinimal_full$count_data <- container$scMinimal_full$count_data[,all_cells]
panel <- list()
meta <- as.character(container$scMinimal_full$metadata[,integration_var])
var_vals <- unique(meta)
for (v in var_vals) {
cell_ndx <- which(meta == v)
panel[[v]] <- container$scMinimal_full$count_data[,cell_ndx]
}
panel.preprocessed <- lapply(panel, pagoda2::basicP2proc, n.cores=ncores,
min.cells.per.gene=0, n.odgenes=2e3,
get.largevis=FALSE, make.geneknn=FALSE)
con <- conos::Conos$new(panel.preprocessed, n.cores=ncores)
con$buildGraph()
con$embedGraph(method="UMAP", min.dist=0.01, spread=15, min.prob.lower=1e-3)
con$findCommunities(method=conos::leiden.community, resolution=1)
cell_assigns <- container$scMinimal_full$metadata[,"ctypes"]
names(cell_assigns) <- rownames(container$scMinimal_full$metadata)
con$clusters$leiden$groups <- cell_assigns[names(con$clusters$leiden$groups)]
container$embedding <- con
return(container)
}
compute_donor_props <- function(clusts,metadata) {
names(clusts) <- metadata[names(clusts),"donors"]
all_donors <- unique(as.character(metadata$donors))
donor_props <- data.frame(matrix(0,ncol=length(unique(clusts)),nrow = length(all_donors)))
colnames(donor_props) <- sapply(1:ncol(donor_props),function(x) {
paste0('K',as.character(x))
})
rownames(donor_props) <- all_donors
for (d in all_donors) {
tmp_clusts <- clusts[names(clusts)==d]
counts <- table(tmp_clusts)
names(counts) <- sapply(names(counts),function(x) {
paste0('K',as.character(x))
})
for (j in 1:length(counts)) {
donor_props[d,names(counts)[j]] <- counts[j]
}
}
donor_props <- donor_props + 1
donor_props <- t(apply(donor_props, 1, function(i) i/sum(i)))
return(donor_props)
}
compute_associations <- function(donor_balances, donor_scores, stat_type) {
all_reg_stats <- c()
for (f in 1:ncol(donor_scores)) {
tmp <- as.data.frame(cbind(donor_scores[,f],donor_balances[rownames(donor_scores),]))
if (ncol(tmp)==2) {
colnames(tmp) <- c('dscore','ilr1')
} else {
colnames(tmp)[1] <- "dscore"
}
if (ncol(donor_balances)==1) {
prop_model <- stats::as.formula('ilr1 ~ dscore')
} else {
prop_model <- stats::as.formula(paste0("dscore ~ ",
paste(colnames(donor_balances),collapse=" + ")))
}
if (rowSums(donor_balances)[1]==1) {
breg <- betareg::betareg(prop_model, data = tmp)
tmp <- summary(breg)
reg_stat <- tmp$coefficients$mean['dscore','Pr(>|z|)']
} else {
lmres <- stats::lm(prop_model, data=tmp)
if (stat_type == 'fstat') {
reg_stat <- summary(lmres)$fstatistic[[1]]
} else if (stat_type == 'adj_rsq') {
reg_stat <- summary(lmres)$adj.r.squared
} else if (stat_type == 'adj_pval') {
x <- summary(lmres)
reg_stat <- stats::pf(x$fstatistic[1],x$fstatistic[2],x$fstatistic[3],lower.tail=FALSE)
}
}
all_reg_stats <- c(all_reg_stats,reg_stat)
}
return(all_reg_stats)
}
get_subclust_enr_fig <- function(container,all_ctypes,all_res) {
container <- get_subclust_enr_hmap(container,all_ctypes,all_res,1:ncol(container$tucker_results[[1]]))
enr_hmap <- container$plots$subc_enr_hmap
enr_hmap <- grid::grid.grabExpr(draw(enr_hmap))
de_hmaps <- get_subclust_de_hmaps(container,all_ctypes,all_res)
container <- get_subclust_umap(container,all_ctypes=all_ctypes,all_res=all_res)
all_umaps <- list()
for (j in 1:length(all_ctypes)) {
ctype <- all_ctypes[j]
res <- all_res[j]
ct_res <- paste0(ctype,':',as.character(res))
all_umaps[[j]] <- container$plots$subc_umaps[[ct_res]]
}
r1 <- cowplot::plot_grid(plotlist=all_umaps,nrow=1,scale = 0.97)
r2 <- cowplot::plot_grid(plotlist=de_hmaps,nrow=1)
fig <- cowplot::plot_grid(r1,r2,enr_hmap,ncol=1,rel_heights=c(1,1.65,1))
container$plots$subc_fig <- fig
return(container)
}
get_subclust_enr_hmap <- function(container,all_ctypes,all_res,all_factors) {
res_df <- data.frame(matrix(ncol=length(all_factors),nrow=0))
hmap_groupings <- c()
for (j in 1:length(all_ctypes)) {
ctype <- all_ctypes[j]
res <- all_res[j]
resolution_name <- paste0('res:',as.character(res))
subclusts <- container$subclusters[[ctype]][[resolution_name]]
subclusts <- sapply(subclusts,function(x){paste0(ctype,'_',x)})
donor_scores <- container$tucker_results[[1]]
donor_vec <- container$scMinimal_full$metadata[names(subclusts),'donors']
subclusts <- subclusts[donor_vec %in% rownames(donor_scores)]
subclusts_num <- sapply(subclusts,function(x){as.numeric(strsplit(x,split="_")[[1]][[2]])})
scMinimal <- container$scMinimal_ctype[[ctype]]
sub_meta_tmp <- scMinimal$metadata[names(subclusts),]
donor_props <- compute_donor_props(subclusts_num,sub_meta_tmp)
tmp_df <- data.frame(matrix(ncol=length(all_factors),nrow=length(unique(subclusts))))
rownames(tmp_df) <- rownames(tmp_df) <- sapply(1:length(unique(subclusts)),function(x){
paste0(ctype,"_",x)})
hmap_groupings <- c(hmap_groupings, rep(ctype,length(unique(subclusts))))
for (factor_use in all_factors) {
subtype_associations <- get_indv_subtype_associations(container,donor_props,factor_use)
for (i in 1:length(subtype_associations)) {
subc_name <- names(subtype_associations)[i]
subc_name <- strsplit(subc_name,split="_")[[1]][1]
scores_eval <- donor_scores[,factor_use]
cutoffs <- stats::quantile(scores_eval, c(.25, .75))
donors_low <- names(scores_eval)[scores_eval < cutoffs[1]]
donors_high <- names(scores_eval)[scores_eval > cutoffs[2]]
donors_high_props <- donor_props[donors_high,subc_name]
donors_low_props <- donor_props[donors_low,subc_name]
donors_high_props_mean <- mean(donors_high_props)
donors_low_props_mean <- mean(donors_low_props)
subtype_associations[i] <- -log10(subtype_associations[i])
if (donors_high_props_mean < donors_low_props_mean) {
subtype_associations[i] <- subtype_associations[i] * -1
}
}
tmp_df[,factor_use] <- subtype_associations
}
res_df <- rbind(res_df,tmp_df)
}
hmap_groupings <- factor(hmap_groupings,levels=all_ctypes)
neg_vals <- res_df < 0
res_df <- abs(res_df)
res_df <- 10**-res_df
res_vec <- unlist(res_df)
res_vec <- stats::p.adjust(res_vec, method = 'fdr')
res_df_adj <- matrix(res_vec, nrow = nrow(res_df), ncol = ncol(res_df))
colnames(res_df_adj) <- colnames(res_df)
rownames(res_df_adj) <- rownames(res_df)
res_df_adj <- -log10(res_df_adj)
res_df_adj[neg_vals] <- res_df_adj[neg_vals] * -1
res_df_adj <- t(res_df_adj)
rownames(res_df_adj) <- sapply(all_factors,function(x) {
paste0('Factor',x)
})
col_fun = colorRamp2(c(-8, log10(.05), 0, -log10(.05), 8), c("blue", "white", "white", "white", "red"))
res_df_adj <- as.matrix(res_df_adj)
p <- Heatmap(res_df_adj, name='enr',
cluster_columns = FALSE,
cluster_rows = FALSE,
column_names_gp = gpar(fontsize = 8),
row_names_gp = gpar(fontsize = 10),
col = col_fun, column_split = hmap_groupings,
border=TRUE, row_names_side='left',
cluster_column_slices=FALSE, column_gap = unit(8, "mm"))
container$subc_associations <- res_df_adj
container$plots$subc_enr_hmap <- p
return(container)
}
get_subclust_enr_dotplot <- function(container,ctype,res,subtype,factor_use,ctype_cur=ctype) {
resolution_name <- paste0('res:',as.character(res))
subclusts <- container$subclusters[[ctype]][[resolution_name]]
names_stored <- names(subclusts)
subclusts <- sapply(subclusts,function(x){paste0(ctype,'_',x)})
names(subclusts) <- names_stored
donor_scores <- container$tucker_results[[1]]
cell_intersect <- intersect(names(subclusts),rownames(container$scMinimal_full$metadata))
donor_vec <- container$scMinimal_full$metadata[cell_intersect,'donors']
subclusts <- subclusts[cell_intersect]
subclusts <- subclusts[donor_vec %in% rownames(donor_scores)]
subclusts_num <- sapply(subclusts,function(x){as.numeric(strsplit(x,split="_")[[1]][[2]])})
scMinimal <- container$scMinimal_ctype[[ctype_cur]]
sub_meta_tmp <- scMinimal$metadata[names(subclusts),]
donor_props <- compute_donor_props(subclusts_num,sub_meta_tmp)
donor_props <- donor_props[,subtype,drop=FALSE]
colnames(donor_props) <- 'prop'
donor_props2 <- cbind(donor_props,donor_scores[rownames(donor_props),factor_use])
colnames(donor_props2)[ncol(donor_props2)] <- 'dsc'
donor_props2 <- as.data.frame(donor_props2)
donor_props2$dsc <- as.numeric(donor_props2$dsc)
donor_props2$prop <- as.numeric(donor_props2$prop)
lmres <- lm(prop~dsc,data=donor_props2)
line_range <- seq(min(donor_props2$dsc),max(donor_props2$dsc),.001)
line_dat <- c(line_range*lmres$coefficients[[2]] + lmres$coefficients[[1]])
line_df <- cbind.data.frame(line_range,line_dat)
line_df <- cbind.data.frame(line_df,rep('1',nrow(line_df)))
colnames(line_df) <- c('myx','myy')
p <- ggplot(donor_props2,aes(x=dsc,y=prop)) +
geom_point(alpha = 0.5,pch=19,size=2) +
geom_line(data=line_df,aes(x=myx,y=myy)) +
xlab(paste0('Factor ',as.character(factor_use),' Donor Score')) +
ylab(paste0('Proportion of All ',ctype)) +
ylim(0,1) +
ggtitle(paste0(ctype,'_',as.character(subtype),' Proportions')) +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5),
axis.text=element_text(size=12),
axis.title=element_text(size=14))
ndx_mark <- which(subclusts_num==subtype)
ndx_other <- which(subclusts_num!=subtype)
subclusts_num[ndx_mark] <- 1
subclusts_num[ndx_other] <- 2
donor_props <- compute_donor_props(subclusts_num,sub_meta_tmp)
donor_balances <- coda.base::coordinates(donor_props)
rownames(donor_balances) <- rownames(donor_props)
f1 <- get_one_factor(container,factor_use)
f1_dsc <- f1[[1]]
tmp <- cbind.data.frame(f1_dsc[rownames(donor_balances),1,drop=FALSE],donor_balances)
colnames(tmp) <- c('dsc','my_balance')
lmres <- summary(lm(my_balance~dsc,data=tmp))
pval <- stats::pf(lmres$fstatistic[1],lmres$fstatistic[2],lmres$fstatistic[3],lower.tail=FALSE)
message(paste0('p-value = ',pval))
return(p)
}
get_subclust_de_hmaps <- function(container,all_ctypes,all_res) {
all_plots <- list()
con <- container$embedding
for (j in 1:length(all_ctypes)) {
ctype <- all_ctypes[j]
res <- all_res[j]
ct_res <- paste0(ctype,':',as.character(res))
resolution_name <- paste0('res:',as.character(res))
if (is.null(container$plots$subtype_de[[ct_res]])) {
subclusts <- container$subclusters[[ctype]][[resolution_name]]
subclusts <- sapply(subclusts,function(x){paste0(ctype,'_',x)})
donor_scores <- container$tucker_results[[1]]
donor_vec <- container$scMinimal_full$metadata[names(subclusts),'donors']
subclusts <- subclusts[donor_vec %in% rownames(donor_scores)]
orig_embed <- con[["embedding"]]
orig_clusts <- con$clusters$leiden$groups
con$clusters$leiden$groups <- as.factor(subclusts)
con[["embedding"]] <- orig_embed[names(subclusts),]
myde <- con$getDifferentialGenes(groups=as.factor(subclusts),append.auc=TRUE,z.threshold=0,upregulated.only=TRUE)
subc_de_hmap <- plotDEheatmap_conos(con, groups=as.factor(subclusts), de=myde, container,
row.label.font.size=8)
subc_hmap_grob <- grid::grid.grabExpr(draw(subc_de_hmap,annotation_legend_side = "bottom"))
container$plots$subtype_de[[ct_res]] <- subc_hmap_grob
all_plots[[j]] <- subc_hmap_grob
con$clusters$leiden$groups <- orig_clusts
con[["embedding"]] <- orig_embed
} else {
all_plots[[j]] <- container$plots$subtype_de[[ct_res]]
}
}
return(all_plots)
}
get_subclust_umap <- function(container,all_ctypes,all_res,n_col=3) {
all_plts <- list()
plots_store <- list()
for (i in 1:length(all_ctypes)) {
ctype <- all_ctypes[i]
res <- all_res[i]
con <- container[["embedding"]]
ct_res <- paste0(ctype,':',as.character(res))
resolution_name <- paste0('res:',as.character(res))
subclusts <- container$subclusters[[ctype]][[resolution_name]]
subclusts <- sapply(subclusts,function(x){paste0(ctype,'_',x)})
orig_embed <- con[["embedding"]]
orig_clusts <- con$clusters$leiden$groups
donor_scores <- container$tucker_results[[1]]
donor_vec <- container$scMinimal_full$metadata[names(subclusts),'donors']
subclusts <- subclusts[donor_vec %in% rownames(donor_scores)]
con$clusters$leiden$groups <- as.factor(subclusts)
con[["embedding"]] <- orig_embed[names(subclusts),]
qt_x <- stats::quantile(con[["embedding"]][,1], c(.25,.75))
qt_y <- stats::quantile(con[["embedding"]][,2], c(.25,.75))
iqr_x <- qt_x[2] - qt_x[1]
iqr_y <- qt_y[2] - qt_y[1]
outlier_up_lim_x <- qt_x[2] + 1.5 * iqr_x
outlier_down_lim_x <- qt_x[1] - 1.5 * iqr_x
outlier_up_lim_y <- qt_y[2] + 1.5 * iqr_y
outlier_down_lim_y <- qt_y[1] - 1.5 * iqr_y
n_throw_out <- sum(con[["embedding"]][,1] > outlier_up_lim_x)
while (n_throw_out > 100) {
xlimits <- outlier_up_lim_x - outlier_down_lim_x
move_by <- .05 * xlimits
outlier_up_lim_x <- outlier_up_lim_x + move_by
n_throw_out <- sum(con[["embedding"]][,1] > outlier_up_lim_x)
}
n_throw_out <- sum(con[["embedding"]][,1] < outlier_down_lim_x)
while (n_throw_out > 100) {
xlimits <- outlier_up_lim_x - outlier_down_lim_x
move_by <- .05 * xlimits
outlier_down_lim_x <- outlier_down_lim_x - move_by
n_throw_out <- sum(con[["embedding"]][,1] < outlier_down_lim_x)
}
n_throw_out <- sum(con[["embedding"]][,2] > outlier_up_lim_y)
while (n_throw_out > 100) {
ylimits <- outlier_up_lim_y - outlier_down_lim_y
move_by <- .05 * ylimits
outlier_up_lim_y <- outlier_up_lim_y + move_by
n_throw_out <- sum(con[["embedding"]][,2] > outlier_up_lim_y)
}
n_throw_out <- sum(con[["embedding"]][,2] < outlier_down_lim_y)
while (n_throw_out > 100) {
ylimits <- outlier_up_lim_y - outlier_down_lim_y
move_by <- .05 * ylimits
outlier_down_lim_y <- outlier_down_lim_y - move_by
n_throw_out <- sum(con[["embedding"]][,2] < outlier_down_lim_y)
}
subc_embed_plot <- con$plotGraph()
subc_embed_plot <- subc_embed_plot +
ggtitle(paste0(ctype,' res = ',as.character(res))) +
xlab('UMAP 1') +
ylab('UMAP 2') +
xlim(outlier_down_lim_x,outlier_up_lim_x) +
ylim(outlier_down_lim_y,outlier_up_lim_y) +
theme(plot.title = element_text(hjust = 0.5),
axis.title.y = element_text(size = rel(.8)),
axis.title.x = element_text(size = rel(.8)))
all_plts[[i]] <- subc_embed_plot
plots_store[[ct_res]] <- subc_embed_plot
con$clusters$leiden$groups <- orig_clusts
con[["embedding"]] <- orig_embed
}
container$plots$subc_umaps <- plots_store
container$plots$subc_umap_fig <- cowplot::plot_grid(plotlist=all_plts,
ncol=n_col, scale = 0.95)
return(container)
}
get_indv_subtype_associations <- function(container, donor_props, factor_select) {
reg_stats_all <- list()
for (j in 1:ncol(donor_props)) {
prop_test <- donor_props[,j,drop=FALSE]
colnames(prop_test) <- 'ilr1'
rownames(prop_test) <- rownames(donor_props)
reg_stats <- compute_associations(prop_test,container$tucker_results[[1]],"adj_pval")
names(reg_stats) <- as.character(c(1:ncol(container$tucker_results[[1]])))
reg_stats_all[[paste0("K",j,"_")]] <- reg_stats
}
reg_stats_all <- unlist(reg_stats_all)
parsed_name <- sapply(names(reg_stats_all),function(x){
return(as.numeric(strsplit(x,split="_.")[[1]][2]))
})
reg_stats_all <- reg_stats_all[parsed_name==factor_select]
return(reg_stats_all)
}
plot_donor_props <- function(donor_props, donor_scores, significance,
ctype_mapping=NULL, stat_type='adj_pval', n_col=2) {
if (stat_type == 'adj_pval') {
significance <- stats::p.adjust(significance)
}
all_plots <- list()
for (f in 1:ncol(donor_scores)) {
tmp <- cbind(donor_scores[,f],as.data.frame(donor_props[rownames(donor_scores),]))
colnames(tmp)[1] <- "dscore"
tmp2 <- reshape2::melt(data=tmp, id.vars = 'dscore',
variable.name = 'ctypes', value.name = 'donor_proportion')
if (!is.null(ctype_mapping)) {
tmp2$ctypes <- sapply(tmp2$ctypes,function(x){
return(ctype_mapping[x])
})
}
colnames(tmp2)[2] <- 'cell_types'
if (stat_type=='fstat') {
plot_stat_name <- 'F-Statistic'
round_digits <- 3
} else if (stat_type=='adj_rsq') {
plot_stat_name <- 'adj r-sq'
round_digits <- 3
} else if (stat_type == 'adj_pval') {
plot_stat_name <- 'adj p-val'
round_digits <- 4
}
p <- ggplot(tmp2, aes(x=dscore,y=donor_proportion,color=cell_types)) +
geom_smooth(method='lm', formula= y~x) +
ggtitle(paste0("Factor ",as.character(f))) +
labs(color = "Cell Type") +
xlab("Donor Factor Score") +
ylab("Cell Type Proportion") +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5),legend.position="bottom") +
annotate(geom="text", x=Inf, y=Inf, hjust=1,vjust=1, col="black",
label=paste0(plot_stat_name,': ',format(significance[f], scientific = TRUE, digits=2)))
legend <- cowplot::get_legend(
p + theme(legend.box.margin = margin(0, 0, 30, 0))
)
p <- p + theme(legend.position="none")
all_plots[[f]] <- p
}
fig <- cowplot::plot_grid(plotlist=all_plots, ncol=n_col)
fig <- cowplot::plot_grid(fig, legend, ncol = 1, rel_heights = c(1, .1))
return(fig)
}
plot_subclust_associations <- function(res,n_col=2) {
stat_type <- colnames(res)[1]
if (stat_type == 'adj_pval') {
res[,stat_type] <- -log10(res[,stat_type])
}
if (stat_type=='fstat') {
y_axis_name <- 'F-Statistic'
} else if (stat_type=='adj_rsq') {
y_axis_name <- 'adj r-sq'
} else if (stat_type == 'adj_pval') {
y_axis_name <- '-log10(adj p-val)'
}
num_factors <- length(unique(res$factor))
ctypes <- unique(res$ctype)
plot_list <- list()
for (f in 1:num_factors) {
factor_name <- paste0("Factor ",as.character(f))
res_factor <- res[res$factor==factor_name,]
p <- ggplot(res_factor,aes_string(x='resolution',y=stat_type,color='ctype')) +
geom_line() +
xlab("Leiden Resolution") +
ylab(y_axis_name) +
labs(color = "Cell Type") +
ggtitle(factor_name) +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5),
legend.position="bottom")
if (stat_type == 'adj_rsq') {
p <- p + ylim(c(-.1,1))
}
if (stat_type == 'adj_pval') {
p <- p + geom_hline(yintercept=-log10(.01), linetype="dashed", color = "red")
}
legend <- cowplot::get_legend(
p + theme(legend.box.margin = margin(0, 0, 30, 0))
)
p <- p + theme(legend.position="none")
plot_list[[factor_name]] <- p
}
fig <- cowplot::plot_grid(plotlist=plot_list, ncol=n_col)
fig <- cowplot::plot_grid(fig, legend, ncol = 1, rel_heights = c(1, .1))
return(fig)
}
plotDEheatmap_conos <- function(con,groups,container,de=NULL,min.auc=NULL,min.specificity=NULL,min.precision=NULL,n.genes.per.cluster=10,additional.genes=NULL,exclude.genes=NULL, labeled.gene.subset=NULL, expression.quantile=0.99,pal=grDevices::colorRampPalette(c('dodgerblue1','grey95','indianred1'))(1024),ordering='-AUC',column.metadata=NULL,show.gene.clusters=TRUE, remove.duplicates=TRUE, column.metadata.colors=NULL, show.cluster.legend=TRUE, show_heatmap_legend=FALSE, border=TRUE, return.details=FALSE, row.label.font.size=10, order.clusters=FALSE, split=FALSE, split.gap=0, cell.order=NULL, averaging.window=0, ...) {
if (!requireNamespace("ComplexHeatmap", quietly = TRUE) || utils::packageVersion("ComplexHeatmap") < "2.4") {
stop("ComplexHeatmap >= 2.4 package needs to be installed to use plotDEheatmap. Please run \"devtools::install_github('jokergoo/ComplexHeatmap')\".")
}
getGeneExpression <- utils::getFromNamespace("getGeneExpression", "conos")
groups <- as.factor(groups)
if(is.null(de)) {
de <- con$getDifferentialGenes(groups=groups,append.auc=TRUE,z.threshold=0,upregulated.only=TRUE)
}
de <- de[unlist(lapply(de,nrow))>0]
de <- de[names(de) %in% levels(groups)]
de <- de[order(match(names(de),levels(groups)))]
if(!is.null(min.auc)) {
if(!is.null(de[[1]]$AUC)) {
de <- lapply(de,function(x) x %>% dplyr::filter(AUC>min.auc))
} else {
warning("AUC column lacking in the DE results - recalculate with append.auc=TRUE")
}
}
if(!is.null(min.specificity)) {
if(!is.null(de[[1]]$Specificity)) {
de <- lapply(de,function(x) x %>% dplyr::filter(Specificity>min.specificity))
} else {
warning("Specificity column lacking in the DE results - recalculate append.specificity.metrics=TRUE")
}
}
if(!is.null(min.precision)) {
if(!is.null(de[[1]]$Precision)) {
de <- lapply(de,function(x) x %>% dplyr::filter(Precision>min.precision))
} else {
warning("Precision column lacking in the DE results - recalculate append.specificity.metrics=TRUE")
}
}
if(n.genes.per.cluster==0) {
if(is.null(additional.genes)) stop("if n.genes.per.cluster is 0, additional.genes must be specified")
additional.genes.only <- TRUE;
n.genes.per.cluster <- 30;
} else {
additional.genes.only <- FALSE;
}
de <- lapply(de,function(x) x%>%dplyr::arrange(!!rlang::parse_expr(ordering))%>%head(n.genes.per.cluster))
de <- de[unlist(lapply(de, nrow))>0]
gns <- lapply(de,function(x) as.character(x$Gene)) %>% unlist
sn <- function(x) stats::setNames(x,x)
expl <- lapply(de,function(d) do.call(rbind,lapply(sn(as.character(d$Gene)),function(gene) getGeneExpression(con,gene))))
if(!is.null(additional.genes)) {
genes.to.add <- setdiff(additional.genes,unlist(lapply(expl,rownames)))
if(length(genes.to.add)>0) {
x <- setdiff(genes.to.add,conos::getGenes(con)); if(length(x)>0) warning('the following genes are not found in the dataset: ',paste(x,collapse=' '))
age <- do.call(rbind,lapply(sn(genes.to.add),function(gene) getGeneExpression(con,gene)))
acc <- do.call(rbind,lapply(expl,function(og) rowMeans(cor(t(age),t(og)),na.rm=TRUE)))
acc <- acc[,apply(acc,2,function(x) any(is.finite(x))),drop=FALSE]
acc.best <- stats::na.omit(apply(acc,2,which.max))
for(i in 1:length(acc.best)) {
gn <- names(acc.best)[i];
expl[[acc.best[i]]] <- rbind(expl[[acc.best[i]]],age[gn,,drop=FALSE])
}
if(additional.genes.only) {
expl <- lapply(expl,function(d) d[rownames(d) %in% additional.genes,,drop=FALSE])
expl <- expl[unlist(lapply(expl,nrow))>0]
}
}
}
if(!is.null(exclude.genes)) {
expl <- lapply(expl,function(x) {
x[!rownames(x) %in% exclude.genes,,drop=FALSE]
})
}
exp <- do.call(rbind,expl)
exp <- stats::na.omit(exp[,colnames(exp) %in% names(stats::na.omit(groups))])
if(order.clusters) {
xc <- do.call(cbind,tapply(1:ncol(exp),groups[colnames(exp)],function(ii) rowMeans(exp[,ii,drop=FALSE])))
hc <- stats::hclust(stats::as.dist(2-cor(xc)),method='ward.D2')
groups <- factor(groups,levels=hc$labels[hc$order])
expl <- expl[levels(groups)]
exp <- do.call(rbind,expl)
exp <- stats::na.omit(exp[,colnames(exp) %in% names(stats::na.omit(groups))])
}
if(averaging.window>0) {
if(requireNamespace("zoo", quietly = TRUE)) {
exp <- do.call(cbind,tapply(1:ncol(exp),as.factor(groups[colnames(exp)]),function(ii) {
xa <- t(zoo::rollapply(as.matrix(t(exp[,ii,drop=FALSE])),averaging.window,mean,align='left',partial=TRUE))
colnames(xa) <- colnames(exp)[ii]
xa
}))
} else {
warning("window averaging requires zoo package to be installed. skipping.")
}
}
x <- t(apply(as.matrix(exp), 1, function(xp) {
if(expression.quantile<1) {
qs <- stats::quantile(xp,c(1-expression.quantile,expression.quantile))
if(diff(qs)==0) {
xps <- unique(xp)
if(length(xps)<3) { qs <- range(xp) }
xpm <- stats::median(xp)
if(sum(xp<xpm) > sum(xp>xpm)) {
qs[1] <- max(xp[xp<xpm])
} else {
qs[2] <- min(xps[xps>xpm])
}
}
xp[xp<qs[1]] <- qs[1]
xp[xp>qs[2]] <- qs[2]
}
xp <- xp-min(xp);
if(max(xp)>0) xp <- xp/max(xp);
xp
}))
if(!is.null(cell.order)) {
o <- cell.order[cell.order %in% colnames(x)]
} else {
o <- order(groups[colnames(x)])
}
x=x[,o]
annot <- data.frame(clusters=groups[colnames(x)],row.names = colnames(x))
if(!is.null(column.metadata)) {
if(is.data.frame(column.metadata)) {
annot <- cbind(annot,column.metadata[colnames(x),])
} else if(is.list(column.metadata)) {
annot <- cbind(annot,data.frame(do.call(cbind.data.frame,lapply(column.metadata,'[',rownames(annot)))))
} else {
warning('column.metadata must be either a data.frame or a list of cell-named factors')
}
}
annot <- annot[,rev(1:ncol(annot)),drop=FALSE]
if(is.null(column.metadata.colors)) {
column.metadata.colors <- list();
} else {
if(!is.list(column.metadata.colors)) stop("column.metadata.colors must be a list in a format accepted by HeatmapAnnotation col argument")
if(!is.null(column.metadata.colors[['clusters']])) {
if(!all(levels(groups) %in% names(column.metadata.colors[['clusters']]))) {
stop("column.metadata.colors[['clusters']] must be a named vector of colors containing all levels of the specified cell groups")
}
column.metadata.colors[['clusters']] <- column.metadata.colors[['clusters']][levels(groups)]
}
}
if(is.null(column.metadata.colors[['clusters']])) {
uc <- unique(annot$clusters);
column.metadata.colors$clusters <- stats::setNames(grDevices::rainbow(length(uc)),uc)
}
tt <- unlist(lapply(expl,nrow));
rannot <- stats::setNames(rep(names(tt),tt),unlist(lapply(expl,rownames)))
rannot <- rannot[!duplicated(names(rannot))]
rannot <- rannot[names(rannot) %in% rownames(x)]
rannot <- data.frame(clusters=factor(rannot,levels=names(expl)))
if(remove.duplicates) { x <- x[!duplicated(rownames(x)),] }
ha <- ComplexHeatmap::HeatmapAnnotation(df=annot,border=border,
col=column.metadata.colors,
show_legend=TRUE,
show_annotation_name=FALSE,
annotation_legend_param = list(nrow=1))
if(show.gene.clusters) {
ra <- ComplexHeatmap::HeatmapAnnotation(df=rannot,which='row',show_annotation_name=FALSE, show_legend=FALSE, border=border,col=column.metadata.colors)
} else { ra <- NULL }
ht_opt$message = FALSE
if(split) {
ha <- ComplexHeatmap::Heatmap(x, name='expression', row_title=" ", row_title_gp = gpar(fontsize = 50), col=pal, row_labels=convert_gn(container,rownames(x)), cluster_rows=FALSE, cluster_columns=FALSE, show_row_names=is.null(labeled.gene.subset), show_column_names=FALSE, top_annotation=ha , left_annotation=ra, border=border, show_heatmap_legend=show_heatmap_legend, row_names_gp = grid::gpar(fontsize = row.label.font.size), column_split=groups[colnames(x)], row_split=rannot[,1], row_gap = unit(split.gap, "mm"), column_gap = unit(split.gap, "mm"), ...);
} else {
ha <- ComplexHeatmap::Heatmap(x, name='expression', col=pal,
row_labels=convert_gn(container,rownames(x)),
row_title=" ", row_title_gp = gpar(fontsize = 50),
cluster_rows=FALSE, cluster_columns=FALSE,
show_row_names=is.null(labeled.gene.subset),
show_column_names=FALSE, top_annotation=ha,
left_annotation=ra, border=border,
show_heatmap_legend=show_heatmap_legend,
row_names_gp = grid::gpar(fontsize = row.label.font.size), ...);
}
if(!is.null(labeled.gene.subset)) {
if(is.numeric(labeled.gene.subset)) {
labeled.gene.subset <- unique(unlist(lapply(de,function(x) x$Gene[1:min(labeled.gene.subset,nrow(x))])))
}
gene.subset <- which(rownames(x) %in% labeled.gene.subset)
labels <- rownames(x)[gene.subset];
ha <- ha + ComplexHeatmap::rowAnnotation(link = ComplexHeatmap::anno_mark(at = gene.subset, labels = labels, labels_gp = grid::gpar(fontsize = row.label.font.size)))
}
if(return.details) {
return(list(ha=ha,x=x,annot=annot,rannot=rannot,expl=expl,pal=pal,labeled.gene.subset=labeled.gene.subset))
}
return(ha)
}
|
library("ggplot2")
library("plotly")
library("gganimate")
library("tidyverse")
library('PEcAn.all')
library("RCurl")
source("/fs/data3/kzarada/NEFI/Willow_Creek/forecast.graphs.R")
WLEF.num = 678
WLEF.abv = "WLEF"
WLEF.outdir = '/fs/data3/kzarada/NEFI/US_WLEF/output/'
WLEF.db.num = "0-678"
WCR.num = 676
WCR.abv = "WCr"
WCR.outdir = '/fs/data3/kzarada/output/'
WCR.db.num = "0-676"
Potato.num = 1000026756
Potato.abv = 'Potato'
Potato.outdir = '/fs/data3/kzarada/NEFI/US_Potato/output/'
Potato.db.num = "1-26756"
Syv.num = 622
Syv.abv = "Syv"
Syv.outdir = '/fs/data3/kzarada/NEFI/US_Syv/output/'
Syv.db.num = "0-622"
Los.num = 679
Los.abv = "Los"
Los.outdir = '/fs/data3/kzarada/NEFI/US_Los/output/'
Los.db.num = "0-679"
Harvard.num = 646
Harvard.abv = "Harvard"
Harvard.outdir = '/fs/data3/kzarada/NEFI/US_Harvard/output/'
Harvard.db.num = '0-646'
tower.graphs <- function(site.num, site.abv, outdir, db.num){
frame_end = Sys.Date() + lubridate::days(16)
frame_start = Sys.Date() - lubridate::days(10)
ftime = seq(as.Date(frame_start), as.Date(frame_end), by="days")
ctime = seq(as.Date(frame_start), Sys.Date(), by = "days")
vars = c("NEE", "LE", "soil")
for(j in 1:length(vars)){
for(i in 1:length(ctime)){
args = c(as.character(ctime[i]), vars[j], site.num, outdir)
assign(paste0(ctime[i], "_", vars[j]), forecast.graphs(args))
}
}
NEE.index <- ls(pattern = paste0("_NEE"), envir=environment())
LE.index <- ls(pattern = paste0("_LE"), envir=environment())
soil.index <- ls(pattern = paste0("_soil"), envir=environment())
nee.data = get(NEE.index[1])
for(i in 2:length(NEE.index)){
nee.data = rbind(nee.data, get(NEE.index[i]))
}
le.data = get(LE.index[1])
for(i in 2:length(LE.index)){
le.data = rbind(le.data, get(LE.index[i]))
}
soil.data = get(soil.index[1])
for(i in 2:length(LE.index)){
soil.data = rbind(soil.data, get(soil.index[i]))
}
nee.data$Time <- as.POSIXct(paste(nee.data$date, nee.data$Time, sep = " "), format = "%Y-%m-%d %H")
nee.data$Time <- lubridate::force_tz(nee.data$Time, "UTC")
nee.data$start_date <- as.factor(nee.data$start_date)
le.data$Time <- as.POSIXct(paste(le.data$date, le.data$Time, sep = " "), format = "%Y-%m-%d %H")
le.data$Time <- lubridate::force_tz(le.data$Time, "UTC")
le.data$start_date <- as.factor(le.data$start_date)
soil.data$Time <- as.POSIXct(paste(soil.data$date, soil.data$Time, sep = " "), format = "%Y-%m-%d %H")
soil.data$Time <- lubridate::force_tz(soil.data$Time, "UTC")
soil.data$start_date <- as.factor(soil.data$start_date)
source(paste0('/fs/data3/kzarada/NEFI/US_', site.abv,"/download_", site.abv, ".R"))
real_data <- do.call(paste0("download_US_", site.abv), list(frame_start, frame_end))
real_data$Time = lubridate::with_tz(as.POSIXct(real_data$Time, format = "%Y-%m-%d %H:%M:%S", tz = "UTC"), "UTC")
real_data_nee <- as_tibble(real_data %>% dplyr::select(Time, NEE))
real_data_le <- as_tibble(real_data %>% dplyr::select(Time, LE))
nee.data <- left_join(as_tibble(nee.data), real_data_nee, by = c("Time"), suffix = c("nee", "real"))
le.data <- left_join(as_tibble(le.data), real_data_le, by = c("Time"), suffix = c("le", "real"))
ftime = lubridate::with_tz(as.POSIXct(ftime), tz = "UTC")
x.breaks <- match(ftime, nee.data$Time)
x.breaks <- x.breaks[!is.na(x.breaks)]
nee_upper = max(nee.data %>% dplyr::select(Upper, Lower, Predicted, NEE), na.rm = TRUE)
nee_lower = min(nee.data %>% dplyr::select(Upper, Lower, Predicted, NEE), na.rm = TRUE)
qle_upper = max(le.data %>% dplyr::select(Upper, Predicted, LE) %>% drop_na())
qle_lower = min(le.data %>% dplyr::select(Lower, Predicted, LE) %>% drop_na())
p <-ggplot(nee.data, aes(group = start_date, ids = start_date, frame = start_date)) +
geom_ribbon(aes(x = Time, ymin=Lower, ymax=Upper, fill="95% Confidence Interval"), alpha = 0.4) +
geom_line(aes(x = Time, y = NEE, color = "Observed Data"), size = 1) +
geom_line(aes(x = Time, y = Predicted, color = "Predicted Mean")) +
ggtitle(paste0("Net Ecosystem Exchange for ", frame_start, " to ", frame_end, ", at ", site.abv)) +
scale_color_manual(name = "Legend", labels = c("Predicted Mean", "Observed Data"), values=c("Predicted Mean" = "skyblue1", "Observed Data" = "firebrick4")) +
scale_fill_manual(labels = c("95% Confidence Interval"), values=c("95% Confidence Interval" = "blue1")) +
scale_y_continuous(name="NEE (kg C m-2 s-1)", limits = c(nee_lower, nee_upper)) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5, size = 16), legend.title = element_blank(), legend.text = element_text(size = 12), axis.text.x = element_text(size = 12, angle = 45), axis.text.y = element_text(size = 13), axis.title.y = element_text(size = 16))
q <- ggplot(le.data, aes(group = start_date, ids = start_date, frame = start_date)) +
geom_ribbon(aes(x = Time, ymin=Lower, ymax=Upper, fill="95% Confidence Interval"), alpha = 0.4) +
geom_line(aes(x = Time, y = LE, color = "Observed Data"), size = 1) +
geom_line(aes(x = Time, y = Predicted, color = "Predicted Mean")) +
ggtitle(paste0("Latent Energy for ", frame_start, " to ", frame_end, ", at ", site.abv)) +
scale_color_manual(name = "Legend", labels = c("Predicted Mean", "Observed Data"), values=c("Predicted Mean" = "skyblue1", "Observed Data" = "firebrick4")) +
scale_fill_manual(labels = c("95% Confidence Interval"), values=c("95% Confidence Interval" = "blue1")) +
scale_y_continuous(name="LE (W m-2 s-1)") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5, size = 16), legend.title = element_blank(), legend.text = element_text(size = 12), axis.text.x = element_text(size = 12, angle = 45), axis.text.y = element_text(size = 13), axis.title.y = element_text(size = 16))
ggplot.nee<-ggplotly(p, tooltip = 'all') %>%
animation_opts(frame = 1200, easing = 'linear-in', transition = 0, redraw = F, mode = "next") %>%
animation_slider(x = 0, y = -0.1, visible = T, currentvalue = list(prefix = "Forecast Date:", font = list(color = 'black'))) %>%
animation_button(x = 0, xanchor = "left", y = 1.5, yanchor= "top") %>%
layout(legend = list(orientation = "h", x = 0.25, y = 1.1)) %>%
layout(showlegend = T, margin = c(30,50,30,50))
ggplot.nee$x$data[[1]]$name <-"95% Confidence Interval"
ggplot.nee$x$data[[2]]$name <- "Observed Data"
ggplot.nee$x$data[[3]]$name <- "Predicted Mean"
ggplot.le<-ggplotly(q, tooltip = 'all', layerData = 2) %>%
animation_opts(frame = 1200, easing = 'linear-in', transition = 0, redraw = F, mode = "next") %>%
animation_slider(x = 0, y = -0.1, visible = T, currentvalue = list(prefix = "Forecast Date:", font = list(color = 'black'))) %>%
animation_button(x = 0, xanchor = "left", y = 1.5, yanchor= "top") %>%
layout(legend = list(orientation = "h", x = 0.25, y = 1.1)) %>%
layout(showlegend = T, margin = c(30,50,30,50))
ggplot.le$x$data[[1]]$name <-"95% Confidence Interval"
ggplot.le$x$data[[2]]$name <- "Observed Data"
ggplot.le$x$data[[3]]$name <- "Predicted Mean"
if(file.exists(paste0("/fs/data3/kzarada/NEFI/US_", site.abv, "/download_", site.abv,"_met.R"))){
source(paste0("/fs/data3/kzarada/NEFI/US_", site.abv, "/download_", site.abv,"_met.R"))
met = do.call(paste0("download_US_", site.abv,"_met"), list(frame_start, Sys.Date()))
if("Tsoil" %in% names(met)){
met <- as_tibble(met) %>% mutate(Time = as.POSIXct(date)) %>% dplyr::select(Time, Tair,Tsoil, rH)
}else{met <- as_tibble(met) %>% mutate(Time = as.POSIXct(date)) %>% dplyr::select(Time, Tair, rH)}
nee.met <- nee.data %>% inner_join(met,nee.data, by = c("Time"))
nee.met$error <- (nee.met$NEE - nee.met$Predicted)
}
nee.data$error = nee.data$NEE - nee.data$Predicted
le.data$error = le.data$LE - le.data$Predicted
library(ncdf4)
if(dir.exists(paste0("/fs/data3/kzarada/pecan.data/dbfiles/NOAA_GEFS_downscale_site_", db.num, "/"))){
forecast.path <-paste0("/fs/data3/kzarada/pecan.data/dbfiles/NOAA_GEFS_downscale_site_", db.num, "/")
}else(forecast.path <- paste0("/fs/data3/kzarada/pecan.data/dbfiles/NOAA_GEFS_site_", db.num, "/"))
forecasted_data <- data.frame()
dirs <- list.dirs(path = forecast.path)
dir.1 <- dirs[grepl(paste0(".21.", Sys.Date(), "T*"), dirs)]
nc.files = list()
index = list()
dir.index = list()
index= strsplit(dir.1[1], split = ".21.20")[[1]][2]
dir.index= dirs[grepl(index[1], dirs)]
for(k in 1:21){
nc.files[k]<- list.files(path = dir.index[k], pattern = '*.nc' )
}
forecasted_data <- data.frame()
for(i in 1:21){
setwd(dir.index[i])
nc <- nc_open(nc.files[[i]][1])
sec <- nc$dim$time$vals
sec <- udunits2::ud.convert(sec, unlist(strsplit(nc$dim$time$units, " "))[1], "seconds")
dt <- mean(diff(sec), na.rm=TRUE)
tstep <- round(86400 / dt)
dt <- 86400 / tstep
Tair <-ncdf4::ncvar_get(nc, "air_temperature")
Tair_C <- udunits2::ud.convert(Tair, "K", "degC")
Qair <-ncdf4::ncvar_get(nc, "specific_humidity")
ws <- try(ncdf4::ncvar_get(nc, "wind_speed"))
if (!is.numeric(ws)) {
U <- ncdf4::ncvar_get(nc, "eastward_wind")
V <- ncdf4::ncvar_get(nc, "northward_wind")
ws <- sqrt(U ^ 2 + V ^ 2)
PEcAn.logger::logger.info("wind_speed absent; calculated from eastward_wind and northward_wind")
}
Rain <- ncdf4::ncvar_get(nc, "precipitation_flux")
pres <- ncdf4::ncvar_get(nc,'air_pressure')
SW <- ncdf4::ncvar_get(nc, "surface_downwelling_shortwave_flux_in_air")
LW <- ncdf4::ncvar_get(nc, "surface_downwelling_longwave_flux_in_air")
RH <- PEcAn.data.atmosphere::qair2rh(Qair, Tair_C, press = 950)
file.name <- nc.files[[i]][1]
hour <- strsplit(strsplit(index, split = "T")[[1]][2], split = ".20")[[1]][1]
start_date <- as.POSIXct(paste0(strsplit(strsplit(nc$dim$time$units, " ")[[1]][3], split = "T")[[1]][1]," ", hour), format = "%Y-%m-%d %H:%M")
sec <- nc$dim$time$vals
timestamp <- seq(from = start_date + lubridate::hours(6), by = "1 hour", length.out = length(sec))
ensemble <- rep(i, times = length(timestamp))
tmp <- as.data.frame(cbind(
ensemble,
Tair_C,
Qair,
RH,
Rain = Rain * dt,
ws,
SW,
LW
))
tmp$timestamp <- timestamp
nc_close(nc)
forecasted_data <- rbind(forecasted_data, tmp)
}
forecasted_data$ensemble = as.factor(forecasted_data$ensemble)
save(list = ls(), file = paste0("/srv/shiny-server/Flux_Dashboard/data/", site.abv, ".RData"))
save(list = ls(), file = paste0("/fs/data3/kzarada/NEFI/", site.abv, ".RData"))
print(ls())
}
try(tower.graphs(WLEF.num,
WLEF.abv,
WLEF.outdir,
WLEF.db.num))
try(tower.graphs(WCR.num,
WCR.abv,
WCR.outdir,
WCR.db.num))
try(tower.graphs(Potato.num,
Potato.abv,
Potato.outdir,
Potato.db.num))
try(tower.graphs(Syv.num,
Syv.abv,
Syv.outdir,
Syv.db.num))
try(tower.graphs(Los.num,
Los.abv,
Los.outdir,
Los.db.num))
try(tower.graphs(Harvard.num,
Harvard.abv,
Harvard.outdir,
Harvard.db.num))
|
context("commands - transactions")
test_that("DISCARD", {
expect_equal(redis_cmds$DISCARD(), list("DISCARD"))
})
test_that("EXEC", {
expect_equal(redis_cmds$EXEC(), list("EXEC"))
})
test_that("MULTI", {
expect_equal(redis_cmds$MULTI(), list("MULTI"))
})
test_that("UNWATCH", {
expect_equal(redis_cmds$UNWATCH(), list("UNWATCH"))
})
test_that("WATCH", {
expect_equal(redis_cmds$WATCH("aa"), list("WATCH", "aa"))
expect_equal(redis_cmds$WATCH(c("aa", "bb")), list("WATCH", c("aa", "bb")))
})
|
[
{
"title": "R2admb",
"href": "http://sgsong.blogspot.com/2009/12/r2admb.html"
},
{
"title": "Data analysis example with ggplot and dplyr (analyzing ‘supercar’ data, part 2)",
"href": "http://sharpsightlabs.com/blog/2014/12/23/data-analysis-example-r-supercars-part2/"
},
{
"title": "Fama/French Factors in 1 line of code",
"href": "http://timelyportfolio.blogspot.com/2014/08/famafrench-factors-in-1-line-of-code.html"
},
{
"title": "Getting started with MongoDB in R",
"href": "https://www.opencpu.org/posts/mongolite-release-0-3/"
},
{
"title": "R Ec2",
"href": "http://cbwheadon.github.io/R/2012/01/17/r-ec2/"
},
{
"title": "A look at market returns by month",
"href": "http://blog.datapunks.com/2011/11/returns-by-month/"
},
{
"title": "R is a language",
"href": "http://www.quantumforest.com/2012/01/r-is-a-language/"
},
{
"title": "Dynamically annotate graphs with Shiny",
"href": "http://blog.rolffredheim.com/2013/01/annotating-graphs-with-shiny.html"
},
{
"title": "Crashed!!",
"href": "http://strugglingthroughproblems.blogspot.com/2011/06/crashed.html"
},
{
"title": "I thought R was a letter…intro/installation",
"href": "https://learningomics.wordpress.com/2013/01/28/i-thought-r-was-a-letter-an-introduction/"
},
{
"title": "More on R-Studio",
"href": "http://quantitativeecology.blogspot.com/2011/03/more-on-r-studio.html"
},
{
"title": "Using Inkscape to Post-edit Labels in R Graphs",
"href": "https://web.archive.org/web/http://blog.carlislerainey.com/2011/09/26/using-inkscape-to-post-edit-labels-in-r-graphs/?utm_source=rss&utm_medium=rss&utm_campaign=using-inkscape-to-post-edit-labels-in-r-graphs"
},
{
"title": "Maps of changes in area boundaries, with R",
"href": "http://civilstat.com/2012/06/maps-of-changes-in-area-boundaries-with-r/"
},
{
"title": "MCMSki IV (call for proposals)",
"href": "https://xianblog.wordpress.com/2012/10/15/mcmski-iv-call-for-proposals/"
},
{
"title": "Spring Cleaning Data: 6 of 6- Saving the Data",
"href": "http://0utlier.blogspot.com/2013/04/spring-cleaning-data-6-of-6-saving-data.html"
},
{
"title": "another lottery coincidence",
"href": "https://xianblog.wordpress.com/2011/08/30/another-lottery-coincidence/"
},
{
"title": "I, Rbot: Tweeting from R",
"href": "https://johnbaumgartner.wordpress.com/2011/08/19/rbot/"
},
{
"title": "Third, and Hopefully Final, Post on Correlated Random Normal Generation (Cholesky Edition)",
"href": "http://www.cerebralmastication.com/2010/09/cholesk-post-on-correlated-random-normal-generation/"
},
{
"title": "Geomorph and MacOS X",
"href": "http://ww1.geomorph.net/2014/01/geomorph-and-macos-x.html"
},
{
"title": "Yet Another plyr Example",
"href": "https://casoilresource.lawr.ucdavis.edu/"
},
{
"title": "R for dummies",
"href": "https://xianblog.wordpress.com/2013/05/02/r-for-dummies-2/"
},
{
"title": "Updated tty Connection for R",
"href": "http://biostatmatt.com/archives/1029"
},
{
"title": "R Developer",
"href": "https://www.r-users.com/jobs/r-developer/"
},
{
"title": "abc",
"href": "https://xianblog.wordpress.com/2010/10/22/abc/"
},
{
"title": "“Data Mining with R” Course | May 17-18",
"href": "http://www.milanor.net/blog/data-mining-with-r-course-may-17-18/"
},
{
"title": "The Evolution of Distributed Programming in R",
"href": "http://www.mango-solutions.com/wp/2016/01/the-evolution-of-distributed-programming-in-r/"
},
{
"title": "Multivariate Medians",
"href": "http://davegiles.blogspot.com/2014/12/the-multivariate-median.html"
},
{
"title": "Predicting Wine Quality with Azure ML and R",
"href": "http://blog.revolutionanalytics.com/2016/04/predicting-wine-quality.html"
},
{
"title": "Simple Regime Change Detection with t-test",
"href": "http://hameddaily.blogspot.com/2015/05/simple-regime-change-detection-with-t.html"
},
{
"title": "Usage of R functions \"table\" & \"ifelse\" when NA’s exist",
"href": "http://costaleconomist.blogspot.com/2011/01/usage-of-r-functions-table-ifelse-when.html"
},
{
"title": "ML-Class Ex 7 – kMeans clustering",
"href": "https://web.archive.org/web/http://ygc.name/2011/12/24/ml-class-7-kmeans-clustering/"
},
{
"title": "knitcitations",
"href": "http://www.carlboettiger.info/2012/05/30/knitcitations.html"
},
{
"title": "Three tips for posting good questions to R-help and Stack Overflow",
"href": "https://web.archive.org/web/http://www.sigmafield.org/2011/01/18/three-tips-for-posting-good-questions-to-r-help-and-stack-overflow"
},
{
"title": "New video course: Campaign Response Testing",
"href": "http://www.win-vector.com/blog/2015/04/new-video-course-campaign-response-testing/"
},
{
"title": "Parallel computation [back]",
"href": "https://xianblog.wordpress.com/2011/02/13/parallel-computation-back/"
},
{
"title": "Hadley Wickham’s \"Ask Me Anything\" on Reddit",
"href": "http://blog.revolutionanalytics.com/2015/10/hadley-wickhams-ask-me-anything-on-reddit.html"
},
{
"title": "sab-R-metrics Sidetrack: Bubble Plots",
"href": "http://princeofslides.blogspot.com/2011/03/sab-r-metrics-sidetrack-bubble-plots.html"
},
{
"title": "useR 2015: Romain Francois: My R adventures",
"href": "https://csgillespie.wordpress.com/2015/07/01/user-2015-romain-francois-my-r-adventures/"
},
{
"title": "Your flight is moving …",
"href": "http://www.decisionsciencenews.com/2009/03/02/your-flight-is-moving/"
},
{
"title": "dplyr 0.1.1",
"href": "https://blog.rstudio.org/2014/01/30/dplyr-0-1-1/"
},
{
"title": "High-Performance in Cloud Computing",
"href": "https://web.archive.org/web/http://cloudnumbers.com/high-performance-in-cloud-computing"
},
{
"title": "Extract values from numerous rasters in less time",
"href": "http://r-video-tutorial.blogspot.com/2015/05/extract-values-from-numerous-rasters-in.html"
},
{
"title": "A phylogenetic ordination in one line: magrittr Challenge!",
"href": "http://www.mepheoscience.com/magrittr-challenge/"
},
{
"title": "satRday Cape Town: Call for Submissions",
"href": "http://www.exegetic.biz/blog/2016/10/satrday-cape-town-call-submissions/"
},
{
"title": "Mango at RBelgium: Analytical Web Services",
"href": "http://www.mango-solutions.com/wp/2015/10/mango-at-rbelgium-analytical-web-services/"
},
{
"title": "head and tail for strings",
"href": "http://factbased.blogspot.com/2010/10/head-and-tail-for-strings.html"
},
{
"title": "Rooks in the cloud",
"href": "https://web.archive.org/web/http://empty-moon-9726.heroku.com//blog/2012/01/19/rooks-in-the-cloud/"
},
{
"title": "Near-instant high quality graphs in R",
"href": "https://seriousstats.wordpress.com/2012/09/05/highqualitygraphs/"
},
{
"title": "SIR Model – The Flue Season – Dynamic Programming",
"href": "http://www.econometricsbysimulation.com/2013/05/sir-model-flue-season-dynamic.html"
},
{
"title": "R tutorials",
"href": "https://www.r-bloggers.com/"
}
]
|
addToLog <- function(fullLog, ..., showLog = FALSE) {
if (showLog) {
cat(paste0(..., collapse="\n"))
}
return(paste0(fullLog, "\n", paste0(..., collapse="\n")));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.