code
stringlengths 1
13.8M
|
---|
plot.catpredi.survival <-
function(x, ...){
formula <- update(x$formula, as.formula(paste("~ . + pspline(", x$cat.var, ")", sep = "")))
formula <- as.formula(Reduce(paste, deparse(formula)))
fit.survival <- coxph(formula, data = x$data)
pos <- attr(terms.formula(formula, specials = c("pspline")),"specials")$pspline - 1
termplot(fit.survival, terms = pos, se = TRUE, ylabs = paste("f(",x$cat.var,")"))
for(i in x$results$cutpoints) {
abline(v = i, lty = 2)
}
} |
NULL
as_tbl <- function(x, ..., validate = FALSE) {
tibble::as_tibble(x, ..., validate = FALSE)
}
tbl_frame <- function(...) {
xs <- rlang::quos(..., .named = TRUE)
if (length(xs) == 1L) {
x <- eval_tidy(xs[[1]])
if (is.data.frame(x)) {
return(as_tbl(x))
}
}
as_tbl(tibble:::lst_quos(xs, expand = TRUE))
}
is_robust <- function(expr) {
f <- rlang::expr_text(expr[[1]])
("estimator" %in% names(expr) && expr$estimator == "mlr") ||
grepl("^robust\\:\\:glmRob$|^glmRob$|^MASS\\:\\:rlm$|^rlm$|^robustlmm\\:\\:rlmer$|^rlmer$", f)
}
is_ttest <- function(x) {
grepl("^t|^htest|^ttest$", x, ignore.case = TRUE)
}
is_ols <- function(x) {
grepl("^ols$|ordinary\\s?least\\s?squares", x, ignore.case = TRUE)
}
is_anova <- function(x) {
grepl("anova|analysis of variance", x, ignore.case = TRUE)
}
is_log <- function(x) {
grepl("^log$|^logistic|^binomial$", x, ignore.case = TRUE)
}
is_qlog <- function(x) {
grepl("^quasi.?binom", x, ignore.case = TRUE)
}
is_pois <- function(x) {
grepl("^pois$|poisson", x, ignore.case = TRUE)
}
is_qpois <- function(x) {
grepl("^quasi.?pois", x, ignore.case = TRUE)
}
is_negbin <- function(x) {
grepl("^negbin$|^negbinom$|negative\\s?binomial", x, ignore.case = TRUE)
}
is_sem <- function(x) {
grepl("^sem$|structural equation|latent", x, ignore.case = TRUE)
}
is_mlm <- function(x) {
grepl("^mlm$|multi.?level", x, ignore.case = TRUE)
}
std_model_type <- function(type) {
if (is_ttest(type)) {
type <- "ttest"
} else if (is_ols(type)) {
type <- "ols"
} else if (is_log(type)) {
type <- "log"
} else if (is_qlog(type)) {
type <- "qlog"
} else if (is_pois(type)) {
type <- "pois"
} else if (is_qpois(type)) {
type <- "qpois"
} else if (is_negbinom(type)) {
type <- "negbin"
} else if (is_anova(type)) {
type <- "anova"
} else if (is_sem(type)) {
type <- "sem"
} else if (is_mlm(type)) {
type <- "mlm"
}
type
} |
staticPlot <- function(expr, width = 600, height = 400) {
expr <- substitute(expr)
file <- tempfile(fileext = ".png")
png(file, width, height)
eval(expr, envir = parent.frame())
dev.off()
staticImage(file)
}
staticImage <- function(file, style = "max-width:100%%;max-height:100%%") {
data <- base64enc::base64encode(readBin(file, "raw", file.info(file)[1, "size"]))
ext <- tools::file_ext(file)
tags$img(
src = sprintf("data:image/%s;base64,%s", ext, data),
style = style
)
} |
save_spec = function (object, file = file.path(tempdir(), "spec.RData")) {
if (inherits(object, c("regarima","regarima_spec","SA","SA_spec"))==FALSE)
stop("The function must only be used with \"regarima\", \"regarima_spec\", \"SA\" and \"SA_spec\" objects", call. = FALSE)
estimate <- s_estimate(object)
transform <- s_transform(object)
usrdef <- s_usrdef(object)
predef.outliers <- s_preOut(object)
predef.variables <- s_preVar(object)
trading.days <- s_td(object)
easter <- s_easter(object)
outliers <- s_out(object)
arima.dsc <- s_arima(object)
predef.coef <- s_arimaCoef(object)
forecast <- s_fcst(object)
span <- s_span(object)
if (inherits(object,c("SA","SA_spec")) & inherits(object,"X13")){
decomp <- s_x11(object)
cspec <- "SA_saveX13"
} else if (inherits(object,c("SA","SA_spec")) & inherits(object,"TRAMO_SEATS")){
decomp <- s_seats(object)
cspec <- "SA_saveTS"
} else if (inherits(object,"X13")) {
decomp <- NA
cspec <- "regarima_saveX13"
} else {
decomp <- NA
cspec <- "regarima_saveTS"
}
spec <- list(estimate=estimate, transform=transform, usrdef = usrdef,predef.outliers=predef.outliers,
predef.variables=predef.variables, trading.days=trading.days,easter= easter,
outliers=outliers, arima.dsc=arima.dsc, predef.coef=predef.coef,
forecast = forecast,span=span, decomp=decomp)
class(spec) <- cspec
save(spec, file = file)
}
load_spec <- function (file = "spec.RData") {
object <- get(load(file = file))
if (inherits(object,c("SA_saveX13","SA_saveTS","regarima_saveX13","regarima_saveTS"))==FALSE)
stop("No model specification was found in the file!\n")
s.estimate <- object$estimate
s.transform <- object$transform
s.usrdef <- object$usrdef
s.predef.outliers <- object$predef.outliers
s.predef.variables <- object$predef.variables
s.trading.days <- object$trading.days
s.easter <- object$easter
s.outliers <- object$outliers
s.arima.dsc <- object$arima.dsc
s.predef.coef <- object$predef.coef
s.forecast <- object$forecast
span <- object$span
s.decomp <- object$decomp
estimate<- rbind(s.estimate,rep(NA,length(s.estimate)),s.estimate)
transform <- rbind(s.transform,rep(NA,length(s.transform)),s.transform)
usrdef <- rbind(s.usrdef,rep(NA,length(s.usrdef)),s.usrdef)
trading.days <- rbind(s.trading.days,rep(NA,length(s.trading.days)),s.trading.days)
easter <- rbind(s.easter,rep(NA,length(s.easter)),s.easter)
outliers <- rbind(s.outliers,rep(NA,length(s.outliers)),s.outliers)
arima.dsc <- rbind(s.arima.dsc,rep(NA,length(s.arima.dsc)),s.arima.dsc)
forecast <- rbind(s.forecast,rep(NA,length(s.estimate)),s.forecast)
rownames(estimate)=c("Loaded","User_modif","Final")
rownames(transform)=c("Loaded","User_modif","Final")
rownames(usrdef)=c("Loaded","User_modif","Final")
rownames(trading.days)=c("Loaded","User_modif","Final")
rownames(easter)=c("Loaded","User_modif","Final")
rownames(outliers)=c("Loaded","User_modif","Final")
rownames(arima.dsc)=c("Loaded","User_modif","Final")
rownames(forecast)=c("Loaded","User_modif","Final")
userdef <-list(specification = usrdef, outliers = list(Predefined = s.predef.outliers, Final = s.predef.outliers),
variables = list(Predefined = s.predef.variables, Final = s.predef.variables))
regression <- list(userdef=userdef, trading.days=trading.days, easter = easter)
arima <- list(specification = arima.dsc, coefficients = list(Predefined = s.predef.coef, Final = s.predef.coef))
regarima <- list(estimate=estimate, transform=transform, regression=regression,
outliers=outliers, arima=arima, forecast = forecast , span=span)
if (inherits(object,"regarima_saveX13")){
class(regarima) <- c("regarima_spec","X13")
return(regarima)
} else if (inherits(object,"regarima_saveTS")){
class(regarima) <- c("regarima_spec","TRAMO_SEATS")
return(regarima)
} else if (inherits(object,"SA_saveX13")){
class(regarima) <- c("regarima_spec","X13")
x11 <- rbind(s.decomp,rep(NA,length(s.decomp )),s.decomp)
rownames(x11)=c("Loaded","User_modif","Final")
class(x11) <- c("X11_spec","data.frame")
z <- list(regarima = regarima, x11 = x11)
class(z) <- c("SA_spec","X13")
return(z)
} else {
class(regarima) <- c("regarima_spec","TRAMO_SEATS")
seats <- rbind(s.decomp,rep(NA,length(s.decomp )),s.decomp)
rownames(seats)=c("Loaded","User_modif","Final")
class(seats) <- c("seats_spec","data.frame")
z <- list(regarima = regarima, seats = seats)
class(z) <- c("SA_spec","TRAMO_SEATS")
return(z)
}
} |
background.points.buffer <- function(points, radius, n, mask){
return(background.buffer(points = points, buffer.width = radius,
mask = mask, return.type = "points", n = n))
} |
GMLAbstractObject <- R6Class("GMLAbstractObject",
inherit = ISOAbstractObject,
private = list(
xmlElement = "AbstractObject",
xmlNamespacePrefix = "GML"
),
public = list(
initialize = function(xml = NULL, element = NULL, attrs = list(), defaults = list(), wrap = FALSE){
if(is.null(element)) element <- private$xmlElement
super$initialize(xml, element, namespace = private$xmlNamespacePrefix,
attrs = attrs, defaults = defaults,
wrap = wrap)
}
)
) |
"HDD_Minneapolis" |
context("GET functions")
skip_if_not(interactive(), "This set of tests should only be run manually")
experigit <- create_repo_ref('emilyriederer', 'experigit')
projmgr <- create_repo_ref('emilyriederer', 'projmgr')
test_that( "zero item output is returned as type character (vs list)", {
expect_type( projmgr:::get_engine("/issues", experigit, since = '4000-12-31'), "character")
expect_type( get_issues(experigit, since = '4000-12-31'), "character")
})
test_that( "single item output is wrapped into list of length 1", {
expect_equal( length(projmgr:::get_engine("/issues/1", experigit)), 1)
expect_equal( length(get_issues(experigit, number = 1)), 1)
})
test_that( "get_issues gives message when hitting page limit", {
expect_message( get_issues(experigit, limit = 1, state = "all"))
})
test_that( "Issue number appended to events / comments only when positive length", {
expect_true( all(vapply( get_issue_comments(projmgr, 9) , function(x) "number" %in% names(x), logical(1))) )
expect_null( names( get_issue_comments(projmgr, 1) ))
}) |
plot.CountsEPPM <-
function (x, which = 1:4, caption = c("Residuals vs indices of obs.",
"Cook's distance plot", "Leverage vs predicted values",
"Residuals vs linear predictor", "Normal Q-Q plot of residuals",
"Predicted vs observed values"), sub.caption = " ", main = "",
ask = prod(par("mfcol"), 1) < length(which) && dev.interactive(),
..., type = "spearson")
{
if (!is.numeric(which) || any(which < 1) || any(which > 6))
stop("'which' must be in 1:6")
types <- c("pearson", "deviance", "response", "likelihood",
"sdeviance", "spearson")
Types <- c("Pearson residuals", "Deviance residuals", "Raw response residuals",
"Likelihood residuals", "Standardized deviance residuals",
"Standardized Pearson residuals")
type <- match.arg(type, types)
Type <- Types[type == types]
res <- residuals(x, type = type)
n <- length(res)
k <- length(x$coefficients$mean)
show <- rep(FALSE, 6)
show[which] <- TRUE
Main <- rep("", 6)
Main[which] <- rep(main, length.out = sum(show))
one.fig <- prod(par("mfcol")) == 1
if (ask) { op <- par(ask = TRUE)
on.exit(par(op)) }
if (show[1]) {
plot(1:n, res, xlab = "Obs. number", ylab = Type, main = Main[1],
...)
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[1], 3, 0.25)
abline(h = 0, lty = 3, col = "gray")
}
if (show[2]) {
plot(1:n, cooks.distance(x), xlab = "Obs. number", ylab = "Cook's distance",
type = "h", main = Main[2])
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[2], 3, 0.25)
}
if (show[3]) {
if (x$data.type==TRUE) {
fitted.values <- fitted.CountsEPPM(x)
} else {
fitted.values <- c(rep(0,n))
nstart <- 1
nend <- 0
for (ilist in 1:length(fitted.CountsEPPM(x))) {
ninlist <- sum(x$list.data[[ilist]])
for ( i in 1:length(x$list.data[[ilist]])) {
nt <- x$list.data[[ilist]][i]
if (nt>0) {
nend <- nend + nt
fitted.values[nstart:nend] <- fitted.CountsEPPM(x)[ilist]
nstart <- nstart + nt } }
}
}
plot(fitted.values, hatvalues.CountsEPPM(x), xlab = "Predicted values",
ylab = "hatvalues as leverage", main = Main[3], ...)
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[3], 3, 0.25)
}
if (show[4]) {
if (x$data.type==TRUE) {
linear.predictor <- predict(x, type = "linear.predictor.mean")
} else {
linear.predictor <- c(rep(0,n))
nstart <- 1
nend <- 0
for (ilist in 1:length(predict(x, type = "linear.predictor.mean"))) {
ninlist <- sum(x$list.data[[ilist]])
for ( i in 1:length(x$list.data[[ilist]])) {
nt <- x$list.data[[ilist]][i]
if (nt>0) {
nend <- nend + nt
linear.predictor[nstart:nend] <- predict(x, type = "linear.predictor.mean")[ilist]
nstart <- nstart + nt } }
}
}
plot(linear.predictor, res, xlab = "Linear predictor mean",
ylab = Type, main = Main[4], ...)
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[4], 3, 0.25)
abline(h = 0, lty = 3, col = "gray")
}
if (show[5]) {
qqnorm(y = as.vector(residuals.CountsEPPM(x, type)),
main = Main[5], xlab = "Normal quantiles", ylab = Type)
qqline(y = as.vector(residuals.CountsEPPM(x, type)),
distribution = qnorm)
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[5], 3, 0.25)
}
if (show[6]) {
y <- if (is.null(x$y))
model.response(model.frame(x))
else x$y
plot(y, fitted(x), xlab = "Observed values", ylab = "Predicted values",
main = Main[6], ...)
if (one.fig) { title(sub = sub.caption, ...) }
mtext(caption[6], 3, 0.25)
abline(0, 1, lty = 2, col = "gray")
}
if (!one.fig && par("oma")[3] >= 1)
mtext(sub.caption, outer = TRUE, cex = 1.25)
invisible() } |
mergeBenchmarkResults = function(bmrs) {
assertList(bmrs, types = "BenchmarkResult")
unique.tt = unique(unlist(lapply(bmrs, function(x) getBMRObjects(x, fun = getTaskType))))
if (length(unique.tt) != 1) {
stopf("Different task types found: %s", collapse(unique.tt))
}
task.rin = peelList(lapply(bmrs, function(bmr) getBMRObjects(bmr, fun = function(x) getRRPredictions(x)$instance$desc)))
task.rin = groupNamedListByNames(task.rin)
unique.rin = vlapply(task.rin, function(x) length(unique(x)) == 1)
if (any(!unique.rin)) {
stopf("Different resample description found for tasks: %s", collapse(names(unique.rin)[!unique.rin]))
}
learner.ids = unique(unlist(lapply(bmrs, getBMRLearnerIds)))
task.ids = unique(unlist(lapply(bmrs, getBMRTaskIds)))
all.combos = expand.grid(task.id = task.ids, learner.id = learner.ids)
all.combos = stri_paste(all.combos$task.id, all.combos$learner.id, sep = " - ")
existing.combos = rbindlist(lapply(bmrs, function(bmr) {
getBMRAggrPerformances(bmr, as.df = TRUE)[, c("task.id", "learner.id")]
}), use.names = TRUE)
existing.combos = stri_paste(existing.combos$task.id, existing.combos$learner.id, sep = " - ")
if (!identical(sort(existing.combos), sort(all.combos))) {
dupls = existing.combos[duplicated(existing.combos)]
diff = setdiff(all.combos, existing.combos)
msg = collapse(unique(c(dupls, diff)), "\n* ")
stopf("The following task - learner combination(s) occur either multiple times or are missing: \n* %s\n", msg)
}
lrns.merged = peelList(lapply(bmrs, getBMRLearners))
lrns.merged = unique(lrns.merged)
res.merged = peelList(extractSubList(bmrs, "results", simplify = FALSE))
res.merged = groupNamedListByNames(res.merged)
measures.merged = peelList(lapply(bmrs, getBMRMeasures))
measures.merged = unique(measures.merged)
for (i in seq_along(res.merged)) {
for (j in seq_along(res.merged[[i]])) {
res.merged[[i]][[j]] = addRRMeasure(res.merged[[i]][[j]], measures.merged)
}
}
makeS3Obj("BenchmarkResult",
results = res.merged,
measures = measures.merged,
learners = lrns.merged)
}
peelList = function(x) {
unlist(x, recursive = FALSE)
}
groupNamedListByNames = function(xs, name = sort(unique(names(xs)))) {
assertList(xs, names = "named")
assertCharacter(name)
res = lapply(name, function(x) {
ret = xs[names(xs) == x]
names(ret) = NULL
peelList(ret)
})
names(res) = name
res[order(names(res))]
} |
test_that("compute_iat recognize the rigth class", {
data("raw_data")
sciat_data <- clean_sciat(raw_data, sbj_id = "Participant",
block_id = "blockcode",
latency_id = "latency",
accuracy_id = "correct",
block_sciat_1 = c("test.sc_dark.Darkbad",
"test.sc_dark.Darkgood"),
block_sciat_2 = c("test.sc_milk.Milkbad",
"test.sc_milk.Milkgood"),
trial_id = "trialcode",
trial_eliminate = c("reminder",
"reminder1"),
demo_id = "blockcode",
trial_demo = "demo")
expect_error(compute_iat(raw_data), Dscore = "d1")
expect_error(compute_iat(sciat_data[[1]]), Dscore = "d2")
})
test_that("compute_iat stops if Dscore is not specified", {
data("raw_data")
iat_cleandata <- clean_iat(raw_data, sbj_id = "Participant",
block_id = "blockcode",
mapA_practice = "practice.iat.Milkbad",
mapA_test = "test.iat.Milkbad",
mapB_practice = "practice.iat.Milkgood",
mapB_test = "test.iat.Milkgood",
latency_id = "latency",
accuracy_id = "correct",
trial_id = "trialcode",
trial_eliminate = c("reminder", "reminder1"))
expect_error(compute_iat(iat_cleandata[[1]]))
})
test_that("compute_iat produce a dataframe of class dscore (all scores)", {
skip_on_cran()
data("raw_data")
iat_cleandata <- clean_iat(raw_data, sbj_id = "Participant",
block_id = "blockcode",
mapA_practice = "practice.iat.Milkbad",
mapA_test = "test.iat.Milkbad",
mapB_practice = "practice.iat.Milkgood",
mapB_test = "test.iat.Milkgood",
latency_id = "latency",
accuracy_id = "correct",
trial_id = "trialcode",
trial_eliminate = c("reminder", "reminder1"))
ds <- paste0(rep("d",6), 1:6 )
check_compD <- list()
scores <- list()
for(i in 1:length(ds)){
scores[[i]] <- compute_iat(iat_cleandata[[1]], Dscore = ds[i])
expect_equal(class(scores[[i]])[2], "dscore")
}
})
test_that("compute_iat produce a dataframe with the same number of sbjs for all", {
skip_on_cran()
data("raw_data")
iat_cleandata <- clean_iat(raw_data, sbj_id = "Participant",
block_id = "blockcode",
mapA_practice = "practice.iat.Milkbad",
mapA_test = "test.iat.Milkbad",
mapB_practice = "practice.iat.Milkgood",
mapB_test = "test.iat.Milkgood",
latency_id = "latency",
accuracy_id = "correct",
trial_id = "trialcode",
trial_eliminate = c("reminder", "reminder1"))
ds <- paste0(rep("d",6), 1:6 )
check_compD <- list()
scores <- list()
for(i in 1:length(ds)){
scores[[i]] <- compute_iat(iat_cleandata[[1]], Dscore = ds[i])
expect_equal(nrow(scores[[i]]), length(unique(iat_cleandata[[1]]$participant)) )
}
}) |
gtm_triggers_list <- function(account_id, container_id, workspace_id) {
if (any(missing(account_id),
missing(container_id),
missing(workspace_id)
)) {
stop("Account Id, Container Id and Workspace Id are all required for this function")
}
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = ""
)
res <- gtm_list(path_args = path_args, type = "trigger")
return(res)
}
gtm_triggers_get <- function(account_id, container_id, workspace_id, trigger_id) {
if (any(missing(account_id),
missing(container_id),
missing(workspace_id),
missing(trigger_id)
)) {
stop("Account Id, Container Id, Workspace Id and Trigger Id are all required for this function")
}
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = trigger_id
)
res <- gtm_get(path_args = path_args)
return(res)
}
gtm_triggers_create <- function(account_id, container_id, workspace_id, trigger_object) {
if (any(missing(account_id),
missing(container_id),
missing(workspace_id)
)) {
stop("Account Id, Container Id and Workspace Id are all required for this function")
}
if (missing(trigger_object)) stop("A Trigger Object is required for this function")
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = ""
)
res <- gtm_create(path_args = path_args, body = trigger_object)
myMessage(sprintf('Trigger "%s" (%s) has been created', res$name,res$triggerId) ,level=3)
return(res)
}
gtm_triggers_update <- function(account_id, container_id, workspace_id, trigger_id, trigger_object) {
if (any(missing(account_id),
missing(container_id),
missing(workspace_id),
missing(trigger_id)
)) {
stop("Account Id, Container Id, Workspace Id and Trigger Id are all required for this function")
}
if (missing(trigger_object)) stop("A Trigger Object is required for this function")
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = trigger_id
)
res <- gtm_update(path_args = path_args, body = trigger_object)
myMessage(sprintf('Trigger %s - "%s" has been updated',res$triggerId, res$name) ,level=3)
return(res)
}
gtm_triggers_delete <- function(account_id, container_id, workspace_id, trigger_id, force = c(TRUE,FALSE)) {
if(any(missing(account_id),
missing(container_id),
missing(workspace_id),
missing(trigger_id)
)) {
stop("Account Id, Container Id, Workspace Id and Trigger Id are all required for this function")
}
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = trigger_id
)
if (missing(force)) force <- "FALSE"
force <- as.character(force)
force <- match.arg(force)
force <- as.logical(force)
if (force) {
res<-gtm_delete(path_args = path_args)
} else {
switch(
menu(c("Yes", "No"),
title = sprintf("This will delete Trigger %s. Are you sure you want to continue?", trigger_id)),
{
res<-gtm_delete(path_args = path_args)
},
{
cancelled()
}
)
}
if (length(res) == 0) {
myMessage(sprintf("Trigger %s has been deleted", trigger_id), level = 3)
}
}
gtm_triggers_revert <- function(account_id, container_id, workspace_id, trigger_id) {
if(any(missing(account_id),
missing(container_id),
missing(workspace_id),
missing(trigger_id)
)) {
stop("Account Id, Container Id, Workspace Id and Trigger Id are all required for this function")
}
path_args <- list(
accounts = account_id,
containers = container_id,
workspaces = workspace_id,
triggers = trigger_id
)
res <- gtm_action(path_args = path_args, action = "revert")
myMessage(sprintf("Changes to trigger %s (%s) have been reverted", res$trigger$name, res$zone$triggerId), level = 3)
return(res$trigger)
} |
context("SplitCall")
test_that("SplitCall works", {
call1 <- SortArgs(
PasteAndDep(substitute(UKAnophelesPlumbeus)),
PasteAndDep(substitute(UKAir)),
PasteAndDep(substitute(OneHundredBackground)),
PasteAndDep(substitute(LogisticRegression)),
PasteAndDep(substitute(PrintMap)),
TRUE
)
split1 <- SplitCall(call1)
expect_true(inherits(split1, "character"))
expect_equal(length(split1), 6)
call2 <- SortArgs(
PasteAndDep(substitute(UKAnophelesPlumbeus)),
PasteAndDep(substitute("UKAir")),
PasteAndDep(substitute(BackgroundAndCrossvalid(k = 2))),
PasteAndDep(substitute(list(LogisticRegression,
LogisticRegression))),
PasteAndDep(substitute(Chain(PrintMap, PrintMap))),
TRUE
)
split2 <- SplitCall(call2)
expect_true(inherits(split2, "character"))
expect_equal(length(split2), 6)
call3 <- SortArgs(
PasteAndDep(substitute(UKAnophelesPlumbeus(k = "awd", v = 2))),
PasteAndDep(substitute(Chain("UKAir", "UKAir"))),
PasteAndDep(substitute(list(BackgroundAndCrossvalid(k = 2),
BackgroundAndCrossvalid(k = 2, l = 3)))),
PasteAndDep(substitute(list(LogisticRegression,
LogisticRegression))),
PasteAndDep(substitute(Chain(PrintMap(l = 2),
PrintMap(l = 2, k = 3, r = "23")))),
TRUE
)
split3 <- SplitCall(call3)
expect_true(inherits(split3, "character"))
expect_equal(length(split3), 6)
}) |
renv_difftime_format <- function(time, digits = 2L) {
units <- attr(time, "units") %||% ""
if (units == "secs" && time < 0.1) {
time <- time * 1000
units <- "milliseconds"
}
units <- switch(
units,
secs = "seconds",
mins = "minutes",
hours = "hours",
days = "days",
weeks = "weeks",
units
)
elapsed <- format(unclass(signif(time, digits = digits)))
paste(elapsed, units)
}
renv_difftime_format_short <- function(time, digits = 2L) {
elapsed <- signif(time, digits = digits)
if (nchar(elapsed) == 1L)
elapsed <- paste(elapsed, ".0", sep = "")
units <- switch(
attr(time, "units"),
secs = "s",
mins = "m",
hours = "h",
days = "d",
weeks = "w"
)
paste(elapsed, units, sep = "")
} |
tbl_survfit <- function(x, ...) {
UseMethod("tbl_survfit", x)
}
tbl_survfit.list <- function(x, times = NULL, probs = NULL,
statistic = NULL, label = NULL, label_header = NULL,
estimate_fun = NULL, missing = NULL,
conf.level = 0.95, reverse = FALSE, quiet = NULL, ...) {
ci.sep <- get_theme_element("pkgwide-str:ci.sep", default = ", ")
statistic <-
statistic %||%
get_theme_element("tbl_survfit-arg:statistic") %||%
paste0("{estimate} ({conf.low}", ci.sep, "{conf.high})")
missing <- missing %||% "\U2014"
quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE
if (rlang::is_string(label)) {
label <- inject(everything() ~ !!label)
lifecycle::deprecate_warn(
"1.3.6", "gtsummary::tbl_survfit(label=)",
details = "`label=` argument no longer accepts a single string. Pass formula list.")
}
assert_package("survival", "tbl_survfit()")
if (purrr::every(x, ~ !inherits(.x, "survfit"))) {
stop("Argument `x=` must be class 'survfit' created from the `survival::survfit()` function.",
call. = FALSE
)
}
if (c(is.null(times), is.null(probs)) %>% sum() != 1) {
stop("One and only one of `times=` and `probs=` must be specified.", call. = FALSE)
}
if (!rlang::is_string(statistic) || !rlang::is_string(label_header %||% "")) {
stop("`statistic=` and `label_header=` arguments must be strings of length one.",
call. = FALSE
)
}
if (reverse == TRUE && !is.null(probs)) {
rlang::inform("`reverse=TRUE` argument ignored for survival quantile estimation.")
}
estimate_type <- ifelse(is.null(times), "probs", "times")
estimate_fun <-
estimate_fun %||%
switch(estimate_type,
probs = getOption("gtsummary.tbl_survfit.probs.estimate_fun") %||%
partial(style_sigfig, digits = 2),
times = getOption("gtsummary.tbl_survfit.times.estimate_fun") %||%
partial(style_percent, symbol = TRUE)
) %>%
gts_mapper("tbl_survfit(estimate_fun=)")
tbl_survfit_inputs <- as.list(environment())
meta_data <-
tibble(
survfit = x,
tidy = map(.data$survfit, ~broom::tidy(.x)),
stratified = map_lgl(.data$tidy, ~ "strata" %in% names(.x)),
variable = survfit_to_var(.data$survfit, .data$stratified, .data$tidy, quiet)
)
label <-
.formula_list_to_named_list(
x = label,
var_info = meta_data_to_var_info(meta_data),
arg_name = "label",
type_check = chuck(type_check, "is_string", "fn"),
type_check_msg = chuck(type_check, "is_string", "msg")
)
meta_data <-
meta_data %>%
mutate(
var_label = survfit_to_label(.data$survfit, .data$variable, .data$stratified, label)
)
meta_data <-
meta_to_df_stats(meta_data,
inputs = tbl_survfit_inputs,
estimate_type = estimate_type, estimate_fun = estimate_fun,
missing = missing, statistic = statistic
)
if (quiet == FALSE && !identical(meta_data$variable, unique(meta_data$variable))) {
paste(
"tbl_survfit: The variable list in `.$meta_data` is not unique.",
"This could pose a problem with subsequent `tbl_survfit` calls,",
"e.g. `tbl_survfit() %>% add_p()`"
) %>%
stringr::str_wrap() %>%
rlang::inform()
}
table_body <-
meta_data %>%
select(.data$var_label, .data$table_body) %>%
unnest(.data$table_body) %>%
select(.data$variable, .data$var_label, everything())
x <-
.create_gtsummary_object(
table_body = table_body,
meta_data = meta_data,
inputs = tbl_survfit_inputs
)
lbls <-
meta_data$df_stats[[1]] %>%
select(.data$col_name, .data$col_label) %>%
distinct() %>%
tibble::deframe() %>%
as.list()
x <-
expr(modify_header(x, label = !!paste0("**", translate_text("Characteristic"), "**"), !!!lbls)) %>%
eval()
x$call_list <- list(tbl_survfit = match.call())
class(x) <- c("tbl_survfit", "gtsummary")
x
}
tbl_survfit.survfit <- function(x, ...) {
tbl_survfit.list(list(x), ...)
}
tbl_survfit.data.frame <- function(x, y, include = everything(), ...) {
include <- dplyr::select(x, {{ include }}) %>% names()
check_haven_labelled(x)
y <- enexpr(y)
y_surv <-
tryCatch(
expr(with(!!x, !!y)) %>% eval(),
error = function(e) {
paste(
"There was are error constructing the `y = Surv()` object from the",
"data frame passed in `x=`, and the outcome passed in `y=`.",
"All columns in `y=` should appear in `x=`.\n\n"
) %>%
stringr::str_wrap() %>%
c(as.character(e)) %>%
stop(call. = FALSE)
}
)
if (!inherits(y_surv, "Surv")) {
paste(
"Together, the data frame in `x=`, and the survival outcome in `y=`",
"must construct `Surv` oject, e.g. `with(trial, Surv(ttdeath, death))`"
) %>%
stringr::str_wrap() %>%
stop(call. = FALSE)
}
y_vars <- inject(all.vars(~ !!y))
x_vars <- include %>% setdiff(y_vars)
survfit_expr_list <-
tryCatch(
map(
x_vars,
function(.x) expr(survival::survfit(!!y ~ !!sym(.x), data = !!x)) %>% eval()
),
error = function(e) {
paste(
"There was are error constructing the list `survfit()` objects from the",
"data frame passed in `x=`, and the outcome passed in `y=`."
) %>%
stringr::str_wrap() %>%
stop(call. = FALSE)
}
)
tbl_survfit.list(x = survfit_expr_list, ...)
}
meta_to_df_stats <- function(meta_data, inputs, estimate_type, estimate_fun,
missing, statistic) {
meta_data %>%
mutate(
df_stats = pmap(
list(.data$survfit, .data$variable, .data$tidy, .data$var_label),
~ switch(estimate_type,
"times" = survfit_time(..1,
variable = ..2, times = inputs$times,
label_header = inputs$label_header,
conf.level = inputs$conf.level,
reverse = inputs$reverse,
quiet = inputs$quiet, tidy = ..3,
var_label = ..4,
estimate_fun = estimate_fun
),
"probs" = survfit_prob(..1,
variable = ..2, probs = inputs$probs,
label_header = inputs$label_header,
conf.level = inputs$conf.level,
quiet = inputs$quiet, tidy = ..3,
var_label = ..4,
estimate_fun = estimate_fun
)
)
),
table_body = map2(
.data$df_stats, .data$var_label,
function(df_stats, var_label) {
strata <- intersect("strata", names(df_stats)) %>%
list() %>%
compact()
table_body <-
df_stats %>%
mutate_at(
vars(.data$estimate, .data$conf.low, .data$conf.high),
~ coalesce(as.character(estimate_fun(.)), missing)
) %>%
mutate(
statistic = glue(.env$statistic) %>% as.character(),
row_type = switch(length(strata) == 0,
"label"
) %||% "level"
) %>%
select(c("variable", "row_type", "label", "col_name", "statistic")) %>%
tidyr::pivot_wider(
id_cols = c(.data$variable, .data$row_type, .data$label),
names_from = c(.data$col_name),
values_from = c(.data$statistic)
)
if (nrow(table_body) > 1) {
table_body <-
table_body %>%
select(.data$variable) %>%
distinct() %>%
mutate(
row_type = "label",
label = var_label
) %>%
bind_rows(table_body)
}
table_body
}
)
)
}
survfit_prob <- function(x, variable, probs, label_header, conf.level, quiet,
tidy, var_label, estimate_fun) {
strata <- intersect("strata", names(tidy)) %>%
list() %>%
compact()
df_stat <- purrr::map2_dfr(
probs, seq_along(probs),
~ stats::quantile(x, probs = .x) %>%
as.data.frame() %>%
tibble::rownames_to_column() %>%
set_names(c("strata", "estimate", "conf.low", "conf.high")) %>%
mutate(
prob = .x,
col_name = paste("stat", .y, sep = "_")
)
) %>%
mutate(
variable = .env$variable,
label = switch(length(.env$strata) == 0,
var_label
) %||%
str_sub(strata, str_locate(strata, fixed("="))[1] + 1),
col_label = .env$label_header %||%
switch(get_theme_element("pkgwide-str:language", default = "en") %in% "es",
"**{style_percent(prob, symbol = TRUE)} {translate_text('Percentile')}**"
) %||%
"**{style_percent(prob, symbol = TRUE)} {translate_text('Percentile')}**" %>%
glue() %>% as.character()
)
if (length(strata) > 0) {
df_stat$variable_levels = df_stat$label
}
if (length(strata) == 0) df_stat <- select(df_stat, -.data$strata)
for (column in c("estimate", "conf.low", "conf.high")) {
attr(df_stat[[column]], "fmt_fun") <- estimate_fun
}
df_stat
}
survfit_time <- function(x, variable, times, label_header, conf.level,
reverse, quiet, tidy, var_label, estimate_fun) {
strata <- intersect("strata", names(tidy)) %>%
list() %>%
compact()
multi_state <- inherits(x, "survfitms")
if (multi_state == TRUE) {
state <- unique(tidy$state) %>%
setdiff("(s0)") %>%
purrr::pluck(1)
if (identical(quiet, FALSE)) {
rlang::inform(glue(
"tbl_survfit: Multi-state model detected. Showing probabilities into state '{state}'"
))
}
tidy <- dplyr::filter(tidy, .data$state == .env$state)
}
tidy <-
tidy %>%
mutate_at(vars(!!!strata), ~ factor(., levels = unique(.))) %>%
mutate_at(
vars(.data$conf.high, .data$conf.low),
~ ifelse(is.na(.) & .data$std.error == 0, .data$estimate, .)
) %>%
select(any_of(c("time", "estimate", "conf.high", "conf.low", "strata"))) %>%
bind_rows(
group_by(., !!!syms(strata)) %>%
slice(1) %>%
mutate(
time = 0,
estimate = ifelse(multi_state, 0, 1),
conf.low = ifelse(multi_state, 0, 1),
conf.high = ifelse(multi_state, 0, 1)
)
) %>%
ungroup()
df_stat <-
tidy %>%
group_by(., !!!syms(strata)) %>%
mutate(time_max = max(.data$time)) %>%
ungroup() %>%
full_join(
select(tidy, !!!syms(strata)) %>%
distinct() %>%
mutate(
time = list(.env$times),
col_name = list(paste("stat", seq_len(length(.env$times)), sep = "_"))
) %>%
unnest(cols = c(.data$time, .data$col_name)),
by = unlist(c(strata, "time"))
) %>%
arrange(!!!syms(strata), .data$time) %>%
group_by(!!!syms(strata)) %>%
tidyr::fill(.data$estimate, .data$conf.high, .data$conf.low,
.data$time_max,
.direction = "down"
) %>%
ungroup() %>%
filter(!is.na(.data$col_name)) %>%
mutate_at(
vars(.data$estimate, .data$conf.high, .data$conf.low),
~ ifelse(.data$time > .data$time_max, NA_real_, .)
) %>%
mutate(
variable = .env$variable,
label = switch(length(.env$strata) == 0,
var_label
) %||%
str_sub(strata, str_locate(strata, fixed("="))[1] + 1),
col_label = .env$label_header %||% paste0("**", translate_text("Time"), " {time}**") %>% glue() %>% as.character()
) %>%
select(
any_of(c("variable", "label", "strata", "col_name", "col_label")),
everything(), -.data$time_max
)
if (length(strata) > 0) {
df_stat$variable_levels = df_stat$label
}
if (reverse == TRUE) {
df_stat <-
df_stat %>%
mutate_at(vars(.data$estimate, .data$conf.low, .data$conf.high), ~ 1 - .) %>%
dplyr::rename(conf.low = .data$conf.high, conf.high = .data$conf.low)
}
for (column in c("estimate", "conf.low", "conf.high")) {
attr(df_stat[[column]], "fmt_fun") <- estimate_fun
}
df_stat
}
survfit_to_var <- function(survfit_list, stratified, tidy, quiet) {
purrr::pmap_chr(
list(survfit_list, seq_along(survfit_list), stratified, tidy),
function(x, i, stratified, tidy) {
if (stratified == FALSE) {
return(
ifelse(length(survfit_list) == 1, "..overall..", glue("..overall_{i}.."))
)
}
var <- word(tidy$strata[1], 1, sep = fixed("="))
if (quiet == FALSE &&
stringr::str_count(tidy$strata[1], pattern = fixed("=")) > 1 &&
stringr::str_count(tidy$strata[1], pattern = fixed(", ")) >= 1) {
paste(
"The `tbl_survfit()` function supports `survfit()` objects with a",
"single stratifying variable, and it looks like you may have more.",
"Errors or unexpected output may occur."
) %>%
str_wrap() %>%
inform()
}
var
}
)
}
survfit_to_label <- function(survfit_list, varlist, stratified, label) {
purrr::pmap_chr(
list(survfit_list, varlist, seq_along(survfit_list), stratified),
function(x, v, i, stratified) {
if (!is.null(label[[v]])) {
return(label[[v]])
}
if (stratified == FALSE) {
return(translate_text("Overall"))
}
data <- x$call %>%
as.list() %>%
pluck("data")
label <- NULL
if (!is.null(data)) {
label <- tryCatch(rlang::eval_tidy(data)[[v]] %>% attr("label"),
warning = function(w) NULL,
error = function(e) NULL
)
}
label %||% v
}
)
}
safe_survfit_eval <- function(x) {
tryCatch(
eval(x),
error = function(e) {
paste(
"There was an error executing {.code add_n()} or {.code add_p()}.",
"The error may be a due to the construction of the original",
"{.code survival::survfit()} object.",
"Please visit this help file for a possible solution:",
"{.code ?tbl_survfit_errors}"
) %>%
cli_alert_danger()
e
}
)
} |
test_that("can predict over polygons in plane", {
library("sp")
library("dplyr")
data("meuse")
meuse$std <- sqrt(0.05066)
coordinates(meuse) = ~x+y
data("meuse.grid")
gridded(meuse.grid) = ~x + y
HexPts <- spsample(meuse.grid, type = "hexagonal", cellsize = 200)
HexPols <- HexPoints2SpatialPolygons(HexPts)
HexPts_df <- SpatialPointsDataFrame(HexPts,data.frame(fs=rep(1,length(HexPts))))
HexPols_df <- SpatialPolygonsDataFrame(HexPols,
over(HexPols,meuse.grid))
G <- auto_basis(manifold = plane(),data=meuse,nres = 2,prune=10,type = "Gaussian")
expect_is(G, "Basis")
S1 <- eval_basis(G,HexPts_df)
S2 <- eval_basis(G,HexPols_df)
expect_is(S1, "Matrix")
expect_is(S2, "Matrix")
expect_identical(dim(S1), c(length(HexPols), nbasis(G)))
expect_identical(dim(S2), c(length(HexPols), nbasis(G)))
HexPols_df <- auto_BAUs(manifold = plane(),
cellsize = c(400,400),
type = "grid",
data = meuse,
convex=-0.05,
nonconvex_hull=FALSE)
HexPols_df$fs <- 1
expect_is(HexPols_df, "SpatialPixelsDataFrame")
f <- log(zinc) ~ 1
S <- SRE(f,data = list(meuse),
basis = G,
BAUs = HexPols_df,
est_error = FALSE)
S <- SRE.fit(S, n_EM = 10, print_lik=F)
expect_is(S, "SRE")
HexPols_df <- predict(S)
expect_is(HexPols_df, "SpatialPixelsDataFrame")
expect_true(all(c("var","mu","sd") %in% names(HexPols_df)))
S@sigma2fshat <- 0
HexPols_df2 <- predict(S)
expect_is(HexPols_df2, "SpatialPixelsDataFrame")
expect_true(all(c("var","mu","sd") %in% names(HexPols_df2)))
}) |
library("dplyr")
library("seplyr")
starwars %>%
group_by_se("homeworld") %>%
summarize_se(c("mean_height" := "mean(height, na.rm = TRUE)",
"mean_mass" := "mean(mass, na.rm = TRUE)",
"count" := "n()"))
grouped_mean <- function(data,
grouping_variables,
value_variables,
count_name = "count") {
result_names <- paste0("mean_",
value_variables)
expressions <- paste0("mean(",
value_variables,
", na.rm = TRUE)")
calculation <- result_names := expressions
data %>%
group_by_se(grouping_variables) %>%
summarize_se(c(calculation,
count_name := "n()")) %>%
ungroup()
}
starwars %>%
grouped_mean(grouping_variables = c("eye_color", "skin_color"),
value_variables = c("mass", "birth_year")) |
expected <- eval(parse(text="2819"));
test(id=0, code={
argv <- eval(parse(text="list(2819.50000004)"));
do.call(`trunc`, argv);
}, o=expected); |
simplify_conditional <- function(x, ...){
x <- check_validator(x)
is_cond <- is_conditional(x) | is_categorical(x)
vals <- to_exprs(x)
for (i in which(is_cond)){
cond <- vals[[i]]
cond <- simplify_non_constraining(cond, vals)
vals[[i]] <- cond
cond <- simplify_non_relaxing(cond, vals)
vals[[i]] <- cond
}
do.call(validate::validator, vals)
}
simplify_non_relaxing <- function(cond_expr, vals){
clauses <- as_dnf(cond_expr)
clauses[] <- lapply(clauses, function(clause){
test_rules <- do.call(validate::validator, c(vals, clause))
if (is_infeasible(test_rules)){
return(NULL)
}
clause
})
is_null <- sapply(clauses, is.null)
as.expression(clauses[!is_null], as_if = TRUE)[[1]]
}
simplify_non_constraining <- function(cond_expr, vals){
clauses <- as_dnf(cond_expr)
for (clause in clauses){
clause_neg <- invert_or_negate(clause)
test_rules <- do.call(validate::validator, c(vals, clause_neg))
if (is_infeasible(test_rules)){
return(clause)
}
}
cond_expr
} |
collection_deletealias <- function(conn, alias, raw = FALSE, callopts = list()) {
conn$collection_deletealias(alias, raw, callopts)
} |
readWMDData <- function(fid, fileInfo, data, skipLarge=FALSE, debug=FALSE) {
error <- FALSE
tryCatch({
dataLength <- pamBinRead(fid, 'int32', n=1)
startPos <- seek(fid)
if(dataLength==0) {
return(list(data=data, error=error))
}
version <- fileInfo$moduleHeader$version
if(version <= 1) {
data$startSample <- pamBinRead(fid, 'int64', n=1)
data$channelMap <- pamBinRead(fid, 'int32', n=1)
}
data$nSlices <- pamBinRead(fid, 'int16', n=1)
if(version >= 1) {
data$amplitude <- pamBinRead(fid, 'int16', n=1) / 100
}
if(version == 1) {
data$nDelays <- pamBinRead(fid, 'int8', n=1)
data$delays <- pamBinRead(fid, 'int16', n = data$nDelays)
data$delays <- data$delays / fileInfo$moduleHeader$delayScale
}
if(skipLarge) {
seek(fid, startPos + dataLength, origin='start')
return(list(data=data, error=error))
}
data$sliceData <- list()
data$contour <- rep(0, data$nSlices)
data$contWidth <- rep(0, data$nSlices)
for(i in 1:data$nSlices) {
aSlice <- list()
aSlice$sliceNumber <- pamBinRead(fid, 'int32', n=1, seek=skipLarge)
aSlice$nPeaks <- pamBinRead(fid, 'int8', n=1)
aSlice$peakData <- matrix(0, nrow=4, ncol=aSlice$nPeaks)
for(p in 1:aSlice$nPeaks) {
sss <- pamBinRead(fid, 'int16', n=4, seek=skipLarge)
aSlice$peakData[,p] <- sss
}
data$sliceData[[i]] <- aSlice
data$contour[i] <- aSlice$peakData[2,1]
data$contWidth[i] <- aSlice$peakData[3,1] - aSlice$peakData[1,1] + 1
}
data$meanWidth <- mean(data$contWidth)
return(list(data=data, error=error))
}, error = function(e) {
if(debug) {
print(paste0('Error reading ', fileInfo$fileHeader$moduleType, ' Data read:'))
print(data)
print(e)
}
error <- TRUE
return(list(data=data, error=error))
})
} |
search.history <-
function(list1, diagnose=FALSE, verbose=TRUE)
{
MC <- match.call()
if(verbose) {
print("", quote = FALSE)
print("Running search.history", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
print("Call:", quote = FALSE)
print(MC)
print("", quote = FALSE)
}
x1 <- list1$"Rows in stage"
lenx1 <- length(x1)
if(diagnose) {Hmisc::prn(x1); Hmisc::prn(lenx1)}
IN <- OUT <- vector("list",lenx1)
lenIN <- rep(0,lenx1)
uu <- x1[[1]]
if(!is.null(uu)) IN[[1]] <- uu
for(i in 2:lenx1){
if(diagnose) Hmisc::prn(i)
uu <- x1[[i]]
if(!is.null(uu)){
vv <- x1[[i-1]]
if(is.null(vv)) IN[[i]] <- uu
else{
rr <- match(vv, uu, nomatch = 0)
IN[[i]] <- uu[-1*rr]
tt <- match(uu, vv, nomatch=0)
OUT[[i]] <- vv[-1*tt]
}
}
}
for(i in 1:lenx1){
lenIN[i] <- length(IN[[i]])
}
maxIN <- max(lenIN)
histIN <- matrix(0,nrow=lenx1,ncol=maxIN)
histOUT <- matrix(0,nrow=lenx1,ncol=(maxIN-1))
for(i in 1:lenx1){
uu <- c(IN[[i]],rep(0,maxIN))
uu <- uu[1:maxIN]
histIN[i,] <- uu
vv <- c(OUT[[i]],rep(0,lenx1))
vv <- vv[1:(maxIN-1)]
histOUT[i,] <- vv
}
lasthist <- dim(histOUT)[2]
INname <- paste("IN",1:maxIN,sep="")
histIN <- as.data.frame(histIN)
names(histIN) <- INname
history <- histIN
if(sum(histOUT)>0){
orijOUT <- dim(histOUT)[2]
for(j in (maxIN-1):2){
if(sum(histOUT[,j])==0) {histOUT <- histOUT[,-j]}
else {break}
}
histOUT <- as.matrix(histOUT,nrow=maxIN)
dimOUT2 <- dim(histOUT)[2]
if(dimOUT2 > 0){
history <- cbind(histIN,histOUT)
history <- as.data.frame(history)
OUTname <- paste("OUT",1:dimOUT2,sep="")
names(history) <- c(INname,OUTname)
}
}
if(verbose) {
print("", quote = FALSE)
print("Finished running search.history", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
}
list(history=history, Call=MC)
} |
knitr::opts_chunk$set(
collapse = TRUE,
warning = FALSE,
message = FALSE,
fig.retina = 3,
comment = "
)
library("logitr")
mnl_pref <- logitr(
data = yogurt,
outcome = 'choice',
obsID = 'obsID',
pars = c('price', 'feat', 'brand')
)
summary(mnl_pref)
coef(mnl_pref)
wtp_mnl_pref <- wtp(mnl_pref, price = "price")
wtp_mnl_pref
mnl_wtp <- logitr(
data = yogurt,
outcome = 'choice',
obsID = 'obsID',
pars = c('feat', 'brand'),
price = 'price',
modelSpace = 'wtp',
numMultiStarts = 10,
startVals = wtp_mnl_pref$Estimate
)
summary(mnl_wtp)
coef(mnl_wtp)
wtpCompare(mnl_pref, mnl_wtp, price = 'price') |
fmply <- function(input, outputs, FUN, ...,
key.sep = "\t", sep = "\t", skip = 0, header = TRUE,
nblocks = Inf, stringsAsFactors = FALSE, colClasses = NULL,
select = NULL, drop = NULL, col.names = NULL,
parallel = 1) {
input <- OpenInput(input, skip)
head <- GetHeader(input, col.names, header, sep)
dtstrsplit <- DefineFormatter(sep, colClasses, stringsAsFactors, head, select, drop)
if (parallel > 1 && .Platform$OS.type != "unix") {
warning("parallel > 1 is not supported on non-unix systems")
parallel <- 1
}
cr <- iotools::chunk.reader(input, sep = key.sep)
i <- 0
res <- list()
if (parallel == 1) {
while (i < nblocks && length(r <- iotools::read.chunk(cr))) {
d <- dtstrsplit(r)
u <- unique(d[[1]])
d <- d[d[[1]] %in% u[1:(min(nblocks - i, length(u)))]]
l <- by(d, d[, 1], FUN, ...)
m <- lapply(seq_along(outputs), function(j) {
rbindlist(lapply(l, "[[", j))
})
if (length(l[[1]]) > length(outputs)) {
n <- lapply(l, "[[", length(l[[1]]))
res <- append(res, n)
}
if (i == 0) {
lapply(seq_along(outputs), function(j) {
if (is.null(m[[j]]) || ncol(m[[j]]) == 0L)
return()
if (all(names(m[[j]]) == paste0("V", 1:length(m[[j]])))) {
fwrite(m[[j]], file = outputs[j], col.names = FALSE,
sep = sep, quote = FALSE)
} else {
fwrite(m[[j]], file = outputs[j], col.names = TRUE,
sep = sep, quote = FALSE)
}
})
} else {
lapply(seq_along(outputs), function(j) {
if (is.null(m[[j]]) || ncol(m[[j]]) == 0L)
return()
fwrite(m[[j]], file = outputs[j], append = TRUE,
sep = sep, quote = FALSE, col.names = FALSE)
})
}
i <- i + length(l)
}
} else {
worker_queue = list()
for (j in 1:max(parallel, 1)) {
r <- iotools::read.chunk(cr)
if (length(r) == 0)
break
worker_queue[[j]] <- parallel::mcparallel({
d <- dtstrsplit(r);
by(d, d[, 1], FUN, ...)
})
}
if (length(worker_queue) == 0)
return(NULL)
if (length(r) > 0)
r <- iotools::read.chunk(cr)
while (i < nblocks && length(worker_queue)) {
l <- parallel::mccollect(worker_queue[[1]])[[1]]
l <- l[1:(min(nblocks - i, length(l)))]
m <- lapply(seq_along(outputs), function(j) {
rbindlist(lapply(l, "[[", j))
})
if (length(l[[1]]) > length(outputs)) {
n <- lapply(l, "[[", length(l[[1]]))
res <- append(res, n)
}
if (i == 0) {
lapply(seq_along(m), function(j) {
if (is.null(m[[j]]) || ncol(m[[j]]) == 0L)
return()
if (all(names(m[[j]]) == paste0("V", 1:length(m[[j]])))) {
fwrite(m[[j]], file = outputs[j], col.names = FALSE,
sep = sep, quote = FALSE)
} else {
fwrite(m[[j]], file = outputs[j], col.names = TRUE,
sep = sep, quote = FALSE)
}
})
} else {
lapply(seq_along(m), function(j) {
if (is.null(m[[j]]) || ncol(m[[j]]) == 0L)
return()
fwrite(m[[j]], file = outputs[j], append = TRUE,
sep = sep, quote = FALSE, col.names = FALSE)
})
}
worker_queue[1] = NULL
i <- i + length(l)
if (length(r) > 0) {
worker_queue[[length(worker_queue) + 1]] <- parallel::mcparallel({
d <- dtstrsplit(r);
by(d, d[, 1], FUN, ...)
})
r <- iotools::read.chunk(cr)
}
}
}
close(input)
if (length(res))
res
else
invisible(i)
} |
CorrSNSol <- function(Nres,SNres,CvCase,Conf,Xscld,Xmean,Xsd,XsdOutPrd,lglikdif,limlnk2,OptCntrl,getvcov=TRUE,bordertol=1e-2,maxsk=0.99527)
{
GetvcovSingD <- function(Res)
{
SngDparnam <- paste("mu_",Xnames,sep="")
for (i in 1:p) SngDparnam <- c(SngDparnam,paste("Sigma_",Xnames[i],"_",Xnames[i:p],sep=""))
SngDparnam <- c(SngDparnam,paste("gamma1_",Xnames,sep=""))
npar <- SKnpar(Conf,p,p/2)
InFData <- try( sn.infoMv( dp=list(xi=Res$ksi,Omega=Res$Omega,alpha=Res$alpha), y=Xscld, x=matrix(1,nrow=n,ncol=1) ) )
if ( is.null(InFData) || class(InFData)[1] == "try-error" || is.null(InFData$asyvar.cp) ) {
return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL,status="Invalid") )
}
if (Conf==1) {
mleCPvcov <- InFData$asyvar.cp
rownames(mleCPvcov) <- colnames(mleCPvcov) <- SngDparnam
} else {
nparC1 <- 2*p + p*(p+1)/2
parind <- c(1:p,p+SigCind(Conf,p/2),(nparC1-p+1):nparC1)
mleCPvcov <- Safepdsolve(InFData$info.cp[parind,parind],maxlnk2=limlnk2,scale=TRUE)
if ( !is.null(mleCPvcov) ) { rownames(mleCPvcov) <- colnames(mleCPvcov) <- SngDparnam[parind] }
}
if (is.null(mleCPvcov)) return( list(mleCPvcov=NULL,muEse=NULL,SigmaEse=NULL,gamma1Ese=NULL) )
mleCPvcov <- mleCPvcov * SNVCovscaling(Conf,p,Xsd,k=1)
CPStderr <- sqrt(diag(mleCPvcov))
muEse <- CPStderr[1:p]
gammaind <- (npar-p+1):npar
gamma1Ese <- CPStderr[gammaind]
SigmaEse <- matrix(nrow=p,ncol=p)
cnt <- p
for (j1 in 1:p) for (j2 in j1:p)
{
if (FreePar(q,j1,j2,Conf))
{
cnt <- cnt+1
SigmaEse[j1,j2] <- SigmaEse[j2,j1] <- CPStderr[cnt]
}
}
names(gamma1Ese) <- rownames(SigmaEse) <- colnames(SigmaEse) <- names(muEse) <- Xnames
list(mleCPvcov=mleCPvcov,muEse=muEse,SigmaEse=SigmaEse,gamma1Ese=gamma1Ese,status="Regular")
}
p <- ncol(Xscld)
q <- p/2
n <- nrow(Xscld)
n1scvct <- rep(1,n)
Xnames <- names(Xmean)
zmu <- (Nres@mleNmuE-Xmean)/Xsd
if (Conf==1) {
zSigma <- Nres@CovConfCases[[CvCase]]$mleSigE/XsdOutPrd
DP <- cnvCPtoDP(p,zmu,zSigma,rep(0.,p),limlnk2=limlnk2)
newpar <- c(DP$ksi,DP$alpha/DP$omega)
SNStdDtRes <- SNCnf1MaxLik(Xscld,initpar=newpar,grouping=NULL,limlnk2=limlnk2,OptCntrl=OptCntrl)
} else {
zSigma <- Nres@CovConfCases[[CvCase]]$mleSigE/XsdOutPrd
SigmaSrpar <- GetCovPar(zSigma,Conf,test=FALSE)
newpar <- c(zmu,SigmaSrpar,rep(0.,p))
SNStdDtRes <- SNCMaxLik(Xscld,Config=Conf,initpar=newpar,grouping=NULL,limlnk2=limlnk2,OptCntrl=OptCntrl)
}
NewSNres <- list()
NewSNres$muE <- Xmean + Xsd*SNStdDtRes$mu
NewSNres$ksiE <- Xmean + Xsd*SNStdDtRes$ksi
NewSNres$SigmaE <- XsdOutPrd*SNStdDtRes$Sigma
NewSNres$gamma1E <- SNStdDtRes$gamma1
NewSNres$OmegaE <- XsdOutPrd*SNStdDtRes$Omega
NewSNres$alphaE <- SNStdDtRes$alpha
NewSNres$logLik <- SNStdDtRes$lnLik + lglikdif
names(NewSNres$muE) <- names(NewSNres$ksiE) <- Xnames
if ( !is.null(NewSNres$gamma1E) && !is.null(NewSNres$alphaE) && !is.null(NewSNres$SigmaE) && !is.null(NewSNres$OmegaE) )
{
names(NewSNres$gamma1E) <- names(NewSNres$alphaE) <-
dimnames(NewSNres$SigmaE)[[1]] <- dimnames(NewSNres$SigmaE)[[2]] <-
dimnames(NewSNres$OmegaE)[[1]] <- dimnames(NewSNres$OmegaE)[[2]] <- Xnames
}
if (getvcov) {
if ( (SNStdDtRes$c2 > bordertol) || (maxsk-max(abs(SNStdDtRes$gamma1)) < bordertol) )
{
vcovl <- GetvcovSingD(SNStdDtRes)
NewSNres$status <- vcovl$status
NewSNres$mleCPvcov <- vcovl$mleCPvcov
NewSNres$muEse <- vcovl$muEse
NewSNres$SigmaEse <- vcovl$SigmaEse
NewSNres$gamma1Ese <- vcovl$gamma1Ese
} else {
NewSNres$status <- "Onborder"
}
} else {
NewSNres$status <- "OnHold"
NewSNres$mleCPvcov <- NewSNres$muEse <- NewSNres$SigmaEse <- NewSNres$gamma1Ese <- NULL
}
NewSNres
} |
.runThisTest <- Sys.getenv("RunAllRcppTests") == "yes"
if (.runThisTest) {
context(desc = "Testing make_model")
testthat::test_that(
desc = "Observational equivalence corresponds to model equivalence.",
code = {
m1 <- make_model("X -> Y -> Z <- U")
m2 <- make_model("U -> Z <- Y <- X")
expect_equal(m1$dag, m2$dag)
expect_equal(m1$nodes, m2$nodes)
expect_equal(m1$nodal_types, m2$nodal_types)
expect_equal(m1$parameters_df, m2$parameters_df)
expect_equal(m1$causal_types, m2$causal_types)
}
)
context(desc = "Testing make_data")
model <- make_model("X -> M -> Y")
testthat::test_that(
desc = "data strategy works",
code = {
strat <- make_data(model, n = 8)
expect_equal(nrow(strat), 8)
set.seed(1)
strat <- make_data(
model,
n = 20,
nodes = list(c("X", "Y"), "M"),
probs = list(1, .5),
subsets = list(NULL, "X==1 & Y==0"))
subsetM <- strat[!is.na(strat$M), ]
expect_equal(subsetM$X, rep(1, nrow(subsetM)))
expect_equal(subsetM$Y, rep(0, nrow(subsetM)))
})
testthat::test_that(
desc = "make_data errors and messages when it should.",
code = {
model <- make_model("X -> M -> Y")
expect_error(make_data(model, nodes = c("X","Y"), probs = c(1,2), subsets = c("X==1", "Y==1", "X==0")))
expect_error(make_data(model, nodes = list("X","M","Y"), n_steps = 1))
expect_warning(
make_data(
model,
n = 8,
n_steps = c(2,2),
nodes = list(c("X", "Y"), "M"),
probs = list(1, .5),
subsets = list(NULL, "X==1 & Y==0")))
}
)
} |
.onAttach <- function(lib, pkg)
{
packageStartupMessage("
\n Welcome to enviPick version 1.4
\n -> For large file.mzXML, have enough memory allocated to R - e.g. use memory.limit(size=xy) on windows.
\n -> Ensure to provide centroided & baseline-corrected data.
\n -> Type webpick() to use the browser UI - use a default browser other than Internet Explorer, e.g. Firefox, Google Chrome
\n ");
} |
error.table <-
function(data, Raw_Ind=1){
check_cov <- recode.check(data, Raw_Ind)
Error_Ind <- check_cov$Error_Ind
RR_Star <- relative.risk(data,Raw_Ind)
RR_Star1 <- RR_Star$RR_Star1
RR_Star2 <- RR_Star$RR_Star2
PatternNumber <- RR_Star$PatternNumber
AbsRisk <- absolute.risk(data, Raw_Ind, Avg_White=0)
R_Hyp <- as.numeric(as.character(check_cov$R_Hyp))
NB_Cat <- as.character(check_cov$NB_Cat)
AM_Cat <- as.character(check_cov$AM_Cat)
AF_Cat <- as.character(check_cov$AF_Cat)
NR_Cat <- as.character(check_cov$NR_Cat)
CharRace <- as.character(check_cov$CharRace)
set_T1_missing <- as.numeric(as.character(check_cov$set_T1_missing))
set_T2_missing <- as.numeric(as.character(check_cov$set_T2_missing))
set_HyperP_missing <- as.character(check_cov$set_HyperP_missing)
set_R_Hyp_missing <- as.character(check_cov$set_R_Hyp_missing)
if (length(which(Error_Ind!=0))==0){
error_table <- NULL
print("NO ERROR!")
}
if (length(which(Error_Ind!=0))!=0){
error_table <- array("*", dim=c(2*length(which(is.na(AbsRisk))),14))
origin_update <- cbind(data$ID, data$T1, data$T2, data$N_Biop, data$HypPlas, R_Hyp, data$AgeMen, data$Age1st, data$N_Rels, data$Race, RR_Star1, RR_Star2, AbsRisk, PatternNumber)
compare_update <- cbind(data$ID, set_T1_missing, set_T2_missing, NB_Cat, set_HyperP_missing, set_R_Hyp_missing, AM_Cat, AF_Cat, NR_Cat, CharRace, RR_Star1, RR_Star2, AbsRisk, PatternNumber)
ID_update <- which(is.na(AbsRisk))
origin_update <- origin_update[ID_update,]
compare_update <- compare_update[ID_update,]
if (length(ID_update)==1){
error_table[1,] <- origin_update
error_table[2,] <- compare_update
error_table[2, 11:14] <- ""
}
if (length(ID_update)>1){
for (i in 1:length(ID_update)){
error_table[2*i-1,] <- origin_update[i,]
error_table[2*i,] <- compare_update[i,]
error_table[2*i, 11:14] <- ""
}
}
colnames(error_table) <- c("ID", "T1", "T2", "N_Biop", "HypPlas", "R_Hyp", "AgeMen", "Age1st", "N_Rels", "Race", "RR_Star1", "RR_Star2", "AbsRisk", "PatternNum")
error_table<-data.frame(error_table, row.names=NULL)
return(error_table)
}
} |
library(decompr)
data(leather)
list2env(leather, environment())
w <- decomp(x = inter,
y = final,
k = countries,
i = industries,
o = out,
method = "wwz")
context("output format")
test_that("output size matches", {
expect_equal(length(w), 29 )
expect_equal(dim(w)[1], 27 )
})
test_that("output format matches", {
expect_match(typeof(w[,5]), "double")
})
test_that("verbose computation 1/2",
expect_message(decomp(x=inter, y=final, k=countries, i=industries,
o=out, method = "wwz", verbose = TRUE),
"Starting decomposing the trade flow"))
test_that("verbose computation 2/2",
expect_message(decomp(x=inter, y=final, k=countries, i=industries,
o=out, method = "wwz", verbose = TRUE),
"16/16, elapsed time:"))
context("custom v")
va <- out - colSums(inter)
w.2 <- decomp(x = inter,
y = final,
k = countries,
i = industries,
o = out,
v = va,
method = "wwz")
test_that("specifying v leaves output unchanged",
expect_identical(w.2, w))
va[4:9] <- 0
w.arg <- decomp(x = inter,
y = final,
k = countries,
i = industries,
o = out,
v = va,
method = "wwz")
test_that("only argentina has positive numbers",
expect_true(any(w.arg$DVA_FIN[1:9] > 0)))
test_that("turkey and germany are 0",
expect_true(all(w.arg$DVA_FIN[10:27] == 0)))
va <- out - colSums(inter)
va[1:9 %% 3 != 0] <- 0
w.transport <- decomp(x = inter,
y = final,
k = countries,
i = industries,
o = out,
v = va,
method = "wwz")
within.country <- w.transport[w.transport$Exporting_Country == w.transport$Importing_Country, "DVA_FIN"]
test_that("only within-country flows are 0",
expect_true(all(within.country == 0)))
non_within.country <- w.transport[w.transport$Exporting_Country != w.transport$Importing_Country, "DVA_FIN"]
test_that("all others should be greater than 0",
expect_true(all(non_within.country > 0))) |
Doptrcd.maeT<-function(trt.N,col.N,theta,nrep,itr.cvrgval) {
del.1<-matrix(10^20,trt.N,3)
desbest.1<-matrix(0,nrep*2,col.N)
doptbest.1<-matrix(0,nrep,2)
for(irep in 1:nrep){
des<-intcrcd.mae(trt.N,col.N)
if(trt.N==col.N&trt.N>3&irep<(trt.N-1)) {in.desns=matrix(0,(trt.N-3)*2,col.N)
in.desns0=rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1))
for(i in 1:(trt.N-3)) {in.desns01=cbind(rbind(seq(1,(trt.N-i)),c(seq(1,(trt.N-i))[2:(trt.N-i)],1)),rbind(rep(1,i),((trt.N-i+1):trt.N))); in.desns[c((i-1)*2+1,i*2),]=in.desns01}
in.desns=rbind(rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1)),in.desns)
des=in.desns[c((irep-1)*2+1,irep*2),]}
cmat<-cmatrcd.mae(trt.N,col.N,theta,des)
degv<-sort(eigen(cmat)$values)
degvp<-degv[2:length(degv)]
dopt<-prod(1/degvp)
dcold=dopt
descold=t(des)
cdel<-1000
while( abs(cdel)>=0.000000001){
ivaldcold={}
for (i in 1:col.N){
m=1;
for (m in 1:2){
j=1;
for (j in 1:trt.N){
temp=descold[i,]
if(m==1) {
if(j==descold[i,1]|j==descold[i,2]) {dopt=dcold; del.1[j,]<-c(descold[i,1],(dcold-dopt),dopt); next} else { descold[i,]=c(j,descold[i,2])}}
if(m==2) {
if(descold[i,2]==j|j==descold[i,1]) {dopt=dcold; del.1[j,]<-c(descold[i,2],(dcold-dopt),dopt); next} else { descold[i,]=c(descold[i,1],j)}}
trtin<-contrasts(as.factor(t(descold)),contrasts=FALSE)[as.factor(t(descold)),]
R.trt<-t(trtin)%*%trtin
if (rankMatrix(R.trt)[1]<trt.N) {dopt=dcold; descold[i,]=temp; if(m==1) {del.1[j,]<-c(descold[i,1],(dcold-dopt),dopt)} else {
del.1[j,]<-c(descold[i,2],(dcold-dopt),dopt)}; next}
cmato=cmatrcd.mae(trt.N,col.N, 0,t(descold))
egv<-sort(eigen(cmato)$values)
if(egv[2]<0.000001) {dopt=dcold; descold[i,]=temp; if(m==1) {del.1[j,]<-c(descold[i,1],(dcold-dopt),dopt)} else {
del.1[j,]<-c(descold[i,2],(dcold-dopt),dopt)}; next}
cmat=cmatrcd.mae(trt.N,col.N,theta,t(descold))
degv<-sort(eigen(cmat)$values)
degvp<-degv[2:length(degv)]
dopt<-prod(1/degvp)
del.n<-del.1[j,]<-c(j,(dcold-dopt),dopt)
descold[i,]=temp
}
del.1<-del.1[order(del.1[,3]),]
delbest=t(del.1[1,])
if (m==1) {
if (delbest[1]==descold[i,2]) { descold[i,]= descold[i,]} else{ descold[i,]=c(delbest[1],descold[i,2]); cdel=delbest[2]; dcold=delbest[3]}} else {
if (descold[i,1]==delbest[1]) {descold[i,]= descold[i,] } else{ descold[i,]=c(descold[i,1],delbest[1]); cdel=delbest[2]; dcold=delbest[3] }}
}
ivaldcold=rbind(ivaldcold, c(i,dcold))
if(i>itr.cvrgval) if(all(ivaldcold[c(i-(itr.cvrgval-2),i),2]==ivaldcold[i-(itr.cvrgval-1),2])) break
}
}
cdel<-1000
while( abs(cdel)>=0.000000001){
dopt=dcold
del.2<-matrix(10^20,col.N+1,3)
del.2[col.N+1,]<-c(col.N+1,0,dcold)
for(i in 1:col.N){
temp=descold[i,]
descold[i,]=rev(descold[i,])
cmato=cmatrcd.mae(trt.N,col.N, 0,t(descold))
egv<-sort(eigen(cmato)$values)
if(egv[2]<0.000001) {dopt2=10^20; del.2[i,]<-c(i,(dcold-dopt2),dopt2); next}
cmat=cmatrcd.mae(trt.N,col.N,theta,t(descold))
degv<-sort(eigen(cmat)$values)
degvp<-degv[2:length(degv)]
dopt2<-prod(1/degvp)
del.2[i,]<-c(i,(dcold-dopt2),dopt2)
descold[i,]=temp
}
del.2<-del.2[order(del.2[,3]),]
delbest=t(del.2[1,])
if(delbest[1]<=col.N) {descold[delbest[1],]=rev(descold[delbest[1],]); cdel=delbest[2]; dcold=delbest[3]} else {cdel=0}
}
if (irep==1) {desbest.1=t(descold)} else {desbest.1=rbind(desbest.1,t(descold))}
doptbest.1[irep,]=c(irep,dcold)
}
best=doptbest.1[order(doptbest.1[,2]),]
nb=best[1,1]
Dscore<-best[1,2]
Doptde<- desbest.1[c((nb-1)*2+1,nb*2),]
tkmessageBox(title="Search completed",message=paste("Search completed",sep=""))
cnames=paste0("Ary",1:col.N)
dimnames(Doptde)=list(c("Dye 1:", "Dye 2:"),cnames)
Dopt_sum2<-list("v"=trt.N,"b"=col.N,theta=theta,nrep=nrep,itr.cvrgval=itr.cvrgval, "OptdesF"=Doptde,"Optcrtsv" =Dscore)
return(Dopt_sum2)
} |
NULL
repr_plotly1.plotly <- function(obj, ...) fromJSON(plotly::plotly_json(obj, jsonedit = FALSE))
repr_plotly1.ggplot <- repr_plotly1.plotly |
setClass("Dinamic.programming",
contains = "Exhaustive.model.search.algorithm"
) |
library(factorMerger)
dfWithoutCovariates <- generateMultivariateSample(20,10)
dfWithCovariates <- dfWithoutCovariates
dfWithCovariates$covariates <- data.frame(runif(20), rnorm(20))
context("Check mergeFactors() function")
test_that("Wrong input",{
expect_error(mergeFactors())
expect_error(mergeFactors(dfWithCovariates$response))
expect_error(mergeFactors(dfWithCovariates$factor))
})
test_that("Output format",{
expect_is(mergeFactors(dfWithCovariates$response, dfWithCovariates$factor), "factorMerger")
expect_is(mergeFactors(dfWithCovariates$response, dfWithCovariates$factor, method = "fast-adaptive"), "factorMerger")
})
context("Check groupStats() function")
test_that("Wrong input",{
expect_error(groupsStats())
expect_error(groupsStats(dfWithoutCovariates))
})
test_that("Output format",{
expect_is(groupsStats(mergeFactors(dfWithCovariates$response, dfWithCovariates$factor)), "data.frame")
}) |
rXb <-
function(n, p, s0,
xtype = c("toeplitz", "exp.decay", "equi.corr"),
btype = "U[-2,2]", permuted = FALSE,
iteration = NA, do2S = TRUE,
x.par = switch(xtype,
"toeplitz" = 0.9,
"equi.corr" = 0.8,
"exp.decay" = c(0.4, 5)),
verbose = TRUE)
{
xtype <- match.arg(xtype)
stopifnot(is.character(btype), length(btype) == 1,
n == as.integer(n), length(n) == 1, n >= 1,
p == as.integer(p), length(p) == 1, p >= 1,
s0== as.integer(s0),length(s0)== 1, 0 <= s0, s0 <= p)
do.seed <- is.numeric(iteration) && !is.na(iteration)
if(do.seed) {
if(verbose) {
cat("A value for the argument iteration has been specified:\n")
cat("The seed will be set for reproducibility, the old RNGstate will be restored after the data generation.\n")
}
R.seed <- get(".Random.seed", envir = .GlobalEnv)
on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv))
seed <- iteration + 2
set.seed(seed)
}
x <- rX(n = n, p = p, xtype = xtype,
permuted = permuted, do2S = do2S, par = x.par)
if(do.seed && s0 > 0 && !grepl("^bfix", btype))
set.seed(seed)
beta <- rb(p = p, s0 = s0, btype = btype)
list(x=x, beta=beta)
}
rX <-
function(n, p, xtype, permuted, do2S = TRUE,
par = switch(xtype,
"toeplitz" = 0.9,
"equi.corr" = 0.8,
"exp.decay" = c(0.4, 5)))
{
xtype <- tolower(xtype)
stopifnot(is.numeric(par), is.finite(par))
Sigma <- switch(xtype,
"toeplitz" = {
indices <- toeplitz(0:(p-1))
stopifnot(length(par) == 1)
cov <- par ^ abs(indices)
if(do2S)
solve(solve(cov))
else cov
},
"equi.corr" = {
stopifnot(length(par) == 1)
cov <- matrix(par, p,p)
diag(cov) <- 1
if(do2S) solve(solve(cov)) else cov
},
"exp.decay" = {
stopifnot(length(par) == 2)
indices <- toeplitz(0:(p-1))
solve(par[1]^ (abs(indices)/par[2]))
},
stop("Invalid 'xtype': Must be one of 'toeplitz', 'equi.corr' or 'exp.decay'"))
x <- mvrnorm(n, rep(0,p), Sigma)
if(permuted)
x[, sample.int(ncol(x))]
else
x
}
rb <- function(p, s0, btype) {
stopifnot(s0 <= p, p >= 0, length(s0) == 1, length(p) == 1,
is.character(btype), length(btype) == 1)
invalid.btype.txt <- "Invalid btype: Please provide a btype of the form 'bfix*' for a fixed value or 'U[*,*]', where * are two numbers, the lower and upper bounds."
if(grepl("^U\\[",btype) &&
grepl("\\]$", btype) &&
sapply(regmatches(btype, gregexpr(",", btype)), length) == 1) {
split.btype <- strsplit(sub("^U\\[", '', sub("\\]$", '', btype)),
",")[[1]]
lower <- as.numeric(split.btype[1])
upper <- as.numeric(split.btype[2])
if(is.na(lower) || is.na(upper) || length(lower) != 1 || length(upper) != 1)
stop(invalid.btype.txt)
b <- runif(s0, lower, upper)
} else if(grepl("^bfix", btype)) {
b <- as.numeric(sub("^bfix", "", btype))
if(is.na(b))
stop(invalid.btype.txt)
b <- rep(b, s0)
}
else
stop(invalid.btype.txt)
c(b, rep(0, p - s0))
} |
caThreshold_at_sensitivity <- function(diseaseData,
userFormula,
control_sensitivity,
new_covariates) {
if(!is.numeric(control_sensitivity)) {
control_sensitivity <- as.numeric(control_sensitivity)
}
if(sum(control_sensitivity>1)>0 | sum(control_sensitivity<0)>0) {
stop("control_sensitivity should be between 0 and 1!")
}
rqfit <- NULL
if (length(control_sensitivity) == 1) {
expr1 <- paste0("rqfit <- rq(", userFormula, ", tau = ", 1-control_sensitivity, ", data = diseaseData)")
eval(parse(text = expr1))
new_thres <- predict.rq(rqfit, newdata = new_covariates)
} else {
new_thres <- c()
for(j in 1:length(control_sensitivity)) {
expr1 <- paste0("rqfit <- rq(", userFormula, ", tau = ", 1-control_sensitivity[j], ", data = diseaseData)")
eval(parse(text = expr1))
tmp <- predict.rq(rqfit, newdata = new_covariates)
new_thres <- cbind(new_thres, tmp)
}
colnames(new_thres) = paste0("control_sens=", control_sensitivity)
}
return(new_thres)
} |
validate_kernel_ranged_groups <- function(c, timestamp, gamma, beta) {
r_s <- 1
freq <- 3
lines_grg <- nrow(c$rgs$time)
lines_grg_closed <- nrow(c$rgs_closed$time)
to_remove <- NULL
for (i in 1:lines_grg) {
sup <- length(unique(c$rgs$occ[[i]][, 2]))
freq <- sup / (timestamp - (c$rgs$time[i, r_s]) + 1)
if (freq < gamma) {
if (sum(c$rgs$group[[i]]) >= beta) {
lines_grg_closed <- lines_grg_closed + 1
c$rgs_closed$time <- rbind(c$rgs_closed$time, c$rgs$time[i, ])
c$rgs_closed$group[[lines_grg_closed]] <- c$rgs$group[[i]]
c$rgs_closed$occ[[lines_grg_closed]] <- c$rgs$occ[[i]]
}
to_remove <- append(to_remove, i)
}
}
if (! is.null(to_remove)) {
c$rgs$time <- c$rgs$time[-to_remove, , drop = FALSE]
c$rgs$group <- c$rgs$group[-to_remove]
c$rgs$occ <- c$rgs$occ[-to_remove]
}
return(c)
} |
PeakGroup<-function (aif1,aif2,aif3)
{
if(missing(aif3)){
file1<-aif1$annotation
file2<-aif2$annotation
file1Raw1<-aif1$RawData1
file1Raw2<-aif1$RawData2
file2Raw1<-aif2$RawData1
file2Raw2<-aif2$RawData2
}else{
file1<-aif1$annotation
file2<-aif2$annotation
file3<-aif3$annotation
f123<-c()
f123<-rbind(file1,file2,file3)
f123<-f123[order(f123$Metabolite),]
for(i in 1:length(levels(f123$Metabolite))){
name<-levels(f123$Metabolite)[i]
peakG<-c()
peakG <- f123[which(f123$Metabolite == name), ]
peakG<-peakG[,-8]
ppmdif<-((as.numeric(peakG[,2])-peakG[,13])/peakG[,13])*1000000
peakGG<-cbind(peakG,ppmdif)
peakGF<-unique(peakGG)
write.csv2(peakGF,paste0("PeakGroup",name,".csv"))
}
}
} |
tadd<-function(...){
y<-Inf
z<-cbind(list(...))
n<-length(z)
if(n==1)
{
tvectorAdd(z[[1]])
}
else{
for (i in 1:length(z)) {
if(is.numeric(z[[i]])){
y<-if(y<z[[i]]) y else z[[i]]
}else
return(stop("arguments must be numeric values"))
}
return(y)
}
} |
ChinaPop =
structure(c(1.09, 1.43, 6.09, 6.02, 4.62, 0.97, 2.57, 2.67, 0.96,
2.21, 5.02, 6.2, 5.98, 7.83, 5.83, 5.25, 3.05, 5.15, 7.02, 8.16,
8.93, 3, 2.9, 7.38, 7.97, 10.79, 4.01, 6.02, 9.49, 10.98, 11.38,
1538, 1043, 6851, 3355, 2386, 4221, 2716, 3820, 1778, 7475, 4898,
6120, 3535, 4311, 9248, 9380, 5710, 6326, 9194, 4660, 828, 2798,
8212, 3730, 4450, 277, 3720, 2594, 543, 596, 2010, 0.8362, 0.7511,
0.3769, 0.4211, 0.472, 0.587, 0.5252, 0.531, 0.8909, 0.5011,
0.5602, 0.355, 0.473, 0.37, 0.45, 0.3065, 0.432, 0.37, 0.6068,
0.3362, 0.452, 0.452, 0.33, 0.2687, 0.295, 0.2665, 0.3723, 0.3002,
0.3925, 0.4228, 0.3715, 76.1, 74.91, 72.54, 71.65, 69.87, 73.34,
73.1, 72.37, 78.14, 73.91, 74.7, 71.85, 72.55, 68.95, 73.92,
71.54, 71.08, 70.66, 73.27, 71.29, 72.92, 71.73, 71.2, 65.96,
65.49, 64.37, 70.07, 67.47, 66.03, 70.17, 67.41, 48001, 18601,
40036, 23197, 23660, 44404, 22832, 30888, 40549, 63909, 33115,
29007, 21877, 19946, 50909, 48450, 36287, 34917, 66510, 22556,
5524, 16122, 35297, 14897, 18117, 293, 28734, 13637, 4682, 4895,
21340), .Dim = c(31L, 5L), .Dimnames = list(c("北京", "天津",
"河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "上海", "江苏",
"浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南",
"广东", "广西", "海南", "重庆", "四川", "贵州", "云南", "西藏",
"陕西", "甘肃", "青海", "宁夏", "新疆"), c("增长率", "总人口",
"城镇人口比重", "预期寿命", "高学历人数")), adj = structure(c(-0.5,
-0.5, 0.5, 0.5, 1.3, -0.4, -0.6, -0.5, -0.5, -0.6, -0.6, 0.6,
0.5, 0.5, 0.5, 0.5, 0.5, 1.8, 0.5, 1.7, 0.5, -0.6, -0.6, 0.5,
0.5, 0.5, 1.7, -0.7, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0, -0.5,
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.3, 2.1, -0.3, -0.5, -0.5, -1.6,
0.5, -0.7, 1.3, -0.7, 0.5, 0.5, 2.4, -0.3, -0.6, 0.5, 0.5, -0.8,
-0.7, -0.8), .Dim = c(31L, 2L), .Dimnames = list(c("北京", "天津",
"河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "上海", "江苏",
"浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南",
"广东", "广西", "海南", "重庆", "四川", "贵州", "云南", "西藏",
"陕西", "甘肃", "青海", "宁夏", "新疆"), c("horizontal", "vertical"
))))
library(KernSmooth)
x = ChinaPop
x[, 1:2] = apply(x[, 1:2], 2, function(z) 20 * (z -
min(z)) / (max(z) - min(z)) + 5)
symbols(x[, 4], x[, 5],
thermometers = x[, 1:3], fg = "gray40",
inches = 0.5, xlab = "\u4EBA\u5747\u9884\u671F\u5BFF\u547D", ylab = "\u9AD8\u5B66\u5386\u8005\u4EBA\u6570"
)
est = bkde2D(x[, 4:5], apply(x[, 4:5], 2, dpik))
contour(est$x1, est$x2, est$fhat, add = TRUE, lty = "12")
for (i in 1:nrow(x)) {
text(x[i, 4], x[i, 5], rownames(x)[i],
cex = 0.75, adj = attr(x, "adj")[i, ]
)
}
rug(x[, 4], 0.02, side = 3, col = "gray40")
rug(x[, 5], 0.02, side = 4, col = "gray40")
boxplot(x[, 4],
horizontal = TRUE, pars = list(
boxwex = 7000,
staplewex = 0.8, outwex = 0.8
), at = -6000, add = TRUE, notch = TRUE, col = "skyblue",
xaxt = "n"
)
boxplot(x[, 5],
at = 63, pars = list(
boxwex = 1.4,
staplewex = 0.8, outwex = 0.8
), add = TRUE, notch = TRUE, col = "skyblue",
yaxt = "n"
)
text(67, 60000, "2005", cex = 3.5, col = "gray") |
ResamplingSptCVCstf = R6Class("ResamplingSptCVCstf",
inherit = mlr3::Resampling,
public = list(
initialize = function(id = "sptcv_cstf") {
ps = ParamSet$new(params = list(
ParamInt$new("folds", lower = 1L, default = 10L, tags = "required"),
ParamUty$new("space_var", custom_check = function(x) check_character(x, len = 1)),
ParamUty$new("time_var", custom_check = function(x) check_character(x, len = 1)),
ParamUty$new("class", custom_check = function(x) check_character(x, len = 1))
))
ps$values = list(folds = 10L)
super$initialize(
id = id,
param_set = ps,
man = "mlr3spatiotempcv::mlr_resamplings_sptcv_cstf"
)
},
instantiate = function(task) {
pv = self$param_set$values
mlr3::assert_task(task)
checkmate::assert_multi_class(task, c("TaskClassifST", "TaskRegrST"))
checkmate::assert_subset(pv$time_var,
choices = task$feature_names,
empty.ok = TRUE)
checkmate::assert_subset(pv$space_var,
choices = task$feature_names,
empty.ok = TRUE)
groups = task$groups
if (!is.null(groups)) {
stopf("Grouping is not supported for spatial resampling methods")
}
private$.sample(task)
self$task_hash = task$hash
self$task_nrow = task$nrow
invisible(self)
}
),
active = list(
iters = function() {
self$param_set$values$folds
}
),
private = list(
.sample = function(task) {
pv = self$param_set$values
sptfolds = sample_cstf(
self = self, task, pv$space_var, pv$time_var,
pv$class, pv$folds, task$data()
)
for (i in 1:pv$folds) {
if (!is.null(pv$time_var) & !is.null(sptfolds$space_var)) {
self$instance$test[[i]] = which(sptfolds$data[[sptfolds$space_var]] %in%
sptfolds$spacefolds[[i]] &
sptfolds$data[[pv$time_var]] %in% sptfolds$timefolds[[i]])
self$instance$train[[i]] = which(!sptfolds$data[[sptfolds$space_var]] %in%
sptfolds$spacefolds[[i]] &
!sptfolds$data[[pv$time_var]] %in% sptfolds$timefolds[[i]])
} else if (is.null(pv$time_var) & !is.null(sptfolds$space_var)) {
self$instance$test[[i]] = which(sptfolds$data[[sptfolds$space_var]] %in%
sptfolds$spacefolds[[i]])
self$instance$train[[i]] = which(!sptfolds$data[[sptfolds$space_var]] %in%
sptfolds$spacefolds[[i]])
} else if (!is.null(pv$time_var) & is.null(sptfolds$space_var)) {
self$instance$test[[i]] = which(sptfolds$data[[pv$time_var]] %in%
sptfolds$timefolds[[i]])
self$instance$train[[i]] = which(!sptfolds$data[[pv$time_var]] %in%
sptfolds$timefolds[[i]])
}
}
invisible(self)
},
.get_train = function(i) {
self$instance$train[[i]]
},
.get_test = function(i) {
self$instance$test[[i]]
}
)
) |
pmml.gbm <- function(model,
model_name = "GBM_Model",
app_name = "SoftwareAG PMML Generator",
description = "Generalized Boosted Tree Model",
copyright = NULL,
model_version = NULL,
transforms = NULL,
missing_value_replacement = NULL,
...) {
if (!inherits(model, "gbm")) {
stop("Not a legitimate gbm object")
}
requireNamespace("gbm", quietly = TRUE)
dist <- model$distribution$name
field <- NULL
var.names0 <- c(model$response.name, model$var.names)
var.names0 <- gsub("as\\.factor\\(", "", var.names0)
var.names <- gsub("\\)", "", var.names0)
field$name <- var.names
number.of.fields <- length(field$name)
target <- model$response.name
field$class <- c(0, model$var.type)
field$class[field$class > 0] <- "factor"
if (model$num.classes > 1) field$class[1] <- "factor"
field$class[field$class == 0] <- "numeric"
names(field$class) <- var.names
levelvector <- which(vapply(model$var.levels, function(x) {
is.null(attr(x, "names"))
}, FUN.VALUE = 0) == 1)
j <- 1
for (i in 1:number.of.fields)
{
if (field$name[i] == model$response.name) {
field$levels[[field$name[i]]] <- model$classes
} else {
if (field$class[[field$name[i]]] == "factor") {
field$levels[[field$name[i]]] <- model$var.levels[[levelvector[j]]]
j <- j + 1
}
}
}
numtrees <- model$n.trees
numcategories <- model$num.classes
pmml <- .pmmlRootNode()
pmml <- append.XMLNode(pmml, .pmmlHeader(
description, copyright, model_version,
app_name
))
pmml <- append.XMLNode(pmml, .pmmlDataDictionary(field, transformed = transforms))
if (dist == "multinomial") {
mmodel <- xmlNode("MiningModel", attrs = c(modelName = model_name, functionName = "classification"))
} else {
mmodel <- xmlNode("MiningModel", attrs = c(modelName = model_name, functionName = "regression"))
}
mmodel <- append.XMLNode(mmodel, .pmmlMiningSchema(field, target, transforms, missing_value_replacement))
output <- .pmmlOutput(field, target)
if (dist == "bernoulli") {
responseNode <- xmlNode("OutputField", attrs = c(
name = "BernoulliResponsePrediction",
feature = "transformedValue", dataType = "double"
))
divideNode <- xmlNode("Apply", attrs = c("function" = "/"))
multiplyNode <- xmlNode("Apply", attrs = c("function" = "*"))
plusNode <- xmlNode("Apply", attrs = c("function" = "+"))
expNode <- xmlNode("Apply", attrs = c("function" = "exp"))
minusNode <- xmlNode("Apply", attrs = c("function" = "-"))
fieldNode <- xmlNode("FieldRef", attrs = c(field = paste("Predicted_", target, sep = "")))
initNode <- xmlNode("Constant", model$initF)
one1Node <- xmlNode("Constant", 1)
one2Node <- xmlNode("Constant", 1)
minus1Node <- xmlNode("Constant", -1)
multiplyNode <- append.XMLNode(multiplyNode, minus1Node)
multiplyNode <- append.XMLNode(multiplyNode, xmlNode("FieldRef", attrs = c(field = "BernoulliLinkPrediction")))
expNode <- append.XMLNode(expNode, multiplyNode)
plusNode <- append.XMLNode(plusNode, one1Node)
plusNode <- append.XMLNode(plusNode, expNode)
divideNode <- append.XMLNode(divideNode, one2Node)
divideNode <- append.XMLNode(divideNode, plusNode)
responseNode <- append.XMLNode(responseNode, divideNode)
linkNode <- xmlNode("OutputField", attrs = c(
name = "BernoulliLinkPrediction",
feature = "transformedValue", dataType = "double"
))
addNode <- xmlNode("Apply", attrs = c("function" = "+"))
addNode <- append.XMLNode(addNode, fieldNode)
addNode <- append.XMLNode(addNode, initNode)
linkNode <- append.XMLNode(linkNode, addNode)
output <- append.XMLNode(output, linkNode)
output <- append.XMLNode(output, responseNode)
}
if (dist == "multinomial") {
for (j in seq_along(field$levels[[target]]))
{
output.fields <- xmlNode("OutputField", attrs = c(
name = paste("link_",
field$levels[[target]][j],
sep = ""
),
optype = "continuous",
dataType = "double",
feature = "transformedValue",
segmentId = numtrees * j
))
fieldRefNode <- xmlNode("FieldRef", attrs = c(field = paste("UpdatedPredictedValue",
j, numtrees,
sep = ""
)))
output.fields <- append.XMLNode(output.fields, fieldRefNode)
output <- append.XMLNode(output, output.fields)
}
}
if (dist == "gaussian") {
responseNode <- xmlNode("OutputField", attrs = c(
name = "GaussianPrediction",
feature = "transformedValue", dataType = "double"
))
applyNode <- xmlNode("Apply", attrs = c("function" = "+"))
fieldNode <- xmlNode("FieldRef", attrs = c(field = paste("Predicted_", target, sep = "")))
initNode <- xmlNode("Constant", model$initF)
applyNode <- append.XMLNode(applyNode, fieldNode)
applyNode <- append.XMLNode(applyNode, initNode)
responseNode <- append.XMLNode(responseNode, applyNode)
output <- append.XMLNode(output, responseNode)
}
mmodel <- append.XMLNode(mmodel, output)
mmodel <- .makeTransforms(mmodel, field, number.of.fields, transforms, "LocalTransformations")
if (dist == "multinomial") {
segmentation <- xmlNode("Segmentation", attrs = c(multipleModelMethod = "modelChain"))
for (i in 1:numcategories)
{
segments <- lapply(1:numtrees, function(x) {
.makeSegments(x, model, model_name, field, target, missing_value_replacement, i)
})
segmentation <- append.XMLNode(segmentation, segments)
}
} else {
segmentation <- xmlNode("Segmentation", attrs = c(multipleModelMethod = "sum"))
segments <- lapply(1:numtrees, function(x) {
.makeSegments(x, model, model_name, field, target, missing_value_replacement, 1)
})
segmentation <- append.XMLNode(segmentation, segments)
}
if (dist == "multinomial") {
regModel <- .makeRegressionModel(field, target, numcategories, numtrees, model_name)
segmentation <- append.XMLNode(segmentation, regModel)
}
mmodel <- append.XMLNode(mmodel, segmentation)
pmml <- append.XMLNode(pmml, mmodel)
return(pmml)
}
.makeTransforms <- function(pmodel, field, number.of.fields, transforms, name) {
ltNode <- xmlNode(name)
interact <- FALSE
for (fld in 1:number.of.fields)
{
if (length(grep(":", field$name[fld])) == 1) {
interact <- TRUE
drvnode <- xmlNode("DerivedField", attrs = c(
name = field$name[fld], optype = "continuous",
dataType = "double"
))
applyNode <- xmlNode("Apply", attrs = c("function" = "*"))
for (fac in 1:length(strsplit(field$name[fld], ":")[[1]]))
{
fldNode <- xmlNode("FieldRef", attrs = c(field = strsplit(field$name[fld], ":")[[1]][fac]))
if (length(grep("as\\.factor\\(", fldNode)) == 1) {
fldNode <- gsub("as.factor\\((\\w*)\\)", "\\1", fldNode, perl = TRUE)
}
applyNode <- append.XMLNode(applyNode, fldNode)
}
drvnode <- append.XMLNode(drvnode, applyNode)
}
if (interact) {
ltNode <- append.XMLNode(ltNode, drvnode)
}
}
if (interact && is.null(transforms)) {
pmodel <- append.XMLNode(pmodel, ltNode)
}
if (interact && !is.null(transforms)) {
ltNode <- .pmmlLocalTransformations(field, transforms, ltNode)
pmodel <- append.XMLNode(pmodel, ltNode)
}
if (!interact && !is.null(transforms)) {
pmodel <- append.XMLNode(pmodel, .pmmlLocalTransformations(field, transforms, ltNode))
}
return(pmodel)
}
.makeRegressionModel <- function(field, target, numcat, nt, model_name) {
segment <- xmlNode("Segment", attrs = c(id = numcat * nt + 1))
tru <- xmlNode("True")
segment <- append.XMLNode(segment, tru)
regModel <- xmlNode("RegressionModel",
attrs = c(modelName = model_name, functionName = "classification", normalizationMethod = "softmax")
)
miningNode <- xmlNode("MiningSchema")
for (i in 1:numcat)
{
mfNode <- xmlNode("MiningField", attrs = c(name = paste("UpdatedPredictedValue", i, nt, sep = "")))
miningNode <- append.XMLNode(miningNode, mfNode)
}
regModel <- append.XMLNode(regModel, miningNode)
output <- .pmmlOutput(field, target)
regModel <- append.XMLNode(regModel, output)
for (i in 1:numcat)
{
tableNode <- xmlNode("RegressionTable", attrs = c(
intercept = 0.0,
targetCategory = field$levels[[target]][i]
))
predictorNode <- xmlNode("NumericPredictor", attrs = c(
name = paste("UpdatedPredictedValue", i, nt, sep = ""),
coefficient = 1.0
))
tableNode <- append.XMLNode(tableNode, predictorNode)
regModel <- append.XMLNode(regModel, tableNode)
}
segment <- append.XMLNode(segment, regModel)
return(segment)
}
.makeSegments <- function(b, model, model_name, field, target, missing_value_replacement = NULL, ncat) {
message(paste("Now converting tree ", b, " to PMML, for category
nodeList <- list()
if (model$distribution$name == "multinomial") {
ntrees <- model$n.trees
Ncat <- model$num.classes
tree <- cbind(
model$trees[[ncat + Ncat * (b - 1)]][[3]] + 1,
model$trees[[ncat + Ncat * (b - 1)]][[4]] + 1,
model$trees[[ncat + Ncat * (b - 1)]][[1]] + 2,
model$trees[[ncat + Ncat * (b - 1)]][[2]],
model$trees[[ncat + Ncat * (b - 1)]][[8]],
model$trees[[ncat + Ncat * (b - 1)]][[5]] + 1
)
rowId <- max(c(
model$trees[[ncat + Ncat * (b - 1)]][[3]] + 1, model$trees[[ncat + Ncat * (b - 1)]][[4]] + 1,
model$trees[[ncat + Ncat * (b - 1)]][[5]] + 1
))
} else {
tree <- cbind(
model$trees[[b]][[3]] + 1,
model$trees[[b]][[4]] + 1,
model$trees[[b]][[1]] + 2,
model$trees[[b]][[2]],
model$trees[[b]][[8]],
model$trees[[b]][[5]] + 1
)
rowId <- max(c(
model$trees[[b]][[3]] + 1, model$trees[[b]][[4]] + 1,
model$trees[[b]][[5]] + 1
))
}
nodeList <- lapply(1:rowId, function(x) {
.makeNodes(x, model, tree, field)
})
nodeFi <- .makeTrees(nodeList, tree, rowId)
tree.model <- xmlNode("TreeModel",
attrs = c(
modelName = model_name,
functionName = "regression",
algorithmName = "gbm",
splitCharacteristic = "multiSplit"
)
)
MSNode <- .pmmlMiningSchema(field, target, missing_value_replacement = missing_value_replacement)
outputNode <- xmlNode("Output")
if (model$distribution$name == "multinomial") {
if (b == 1) {
tree.model <- append.XMLNode(tree.model, MSNode)
outputfield1 <- xmlNode("OutputField",
attrs = c(
name = paste("UpdatedPredictedValue", ncat, b, sep = ""), optype = "continuous",
dataType = "double", feature = "predictedValue"
)
)
outputNode <- append.XMLNode(outputNode, outputfield1)
}
if (b != 1) {
miningNode <- xmlNode("MiningField", attrs = c(
name = paste("UpdatedPredictedValue", ncat, b - 1, sep = ""),
optype = "continuous"
))
MSNode <- append.XMLNode(MSNode, miningNode)
tree.model <- append.XMLNode(tree.model, MSNode)
outputfield1 <- xmlNode("OutputField",
attrs = c(
name = paste("TreePredictedValue", ncat, b, sep = ""), optype = "continuous",
dataType = "double", feature = "predictedValue"
)
)
outputNode <- append.XMLNode(outputNode, outputfield1)
outputField2 <- xmlNode("OutputField",
attrs = c(
name = paste("UpdatedPredictedValue", ncat, b, sep = ""), optype = "continuous",
dataType = "double", feature = "transformedValue"
)
)
applyNode <- xmlNode("Apply", attrs = c("function" = "+"))
previousFieldNode <- xmlNode("FieldRef", attrs = c(field = paste("UpdatedPredictedValue", ncat, b - 1, sep = "")))
newFieldNode <- xmlNode("FieldRef", attrs = c(field = paste("TreePredictedValue", ncat, b, sep = "")))
applyNode <- append.XMLNode(applyNode, previousFieldNode)
applyNode <- append.XMLNode(applyNode, newFieldNode)
outputField2 <- append.XMLNode(outputField2, applyNode)
outputNode <- append.XMLNode(outputNode, outputField2)
}
tree.model <- append.XMLNode(tree.model, outputNode)
segment <- xmlNode("Segment", attrs = c(id = (ncat - 1) * ntrees + b))
tru <- xmlNode("True")
segment <- append.XMLNode(segment, tru)
} else {
tree.model <- append.XMLNode(tree.model, MSNode)
segment <- xmlNode("Segment", attrs = c(id = b))
tru <- xmlNode("True")
segment <- append.XMLNode(segment, tru)
}
tree.model <- append.XMLNode(tree.model, nodeFi)
segment <- append.XMLNode(segment, tree.model)
return(segment)
}
.makeTrees <- function(nodeLi, tre, rId) {
while (rId != 0) {
if (tre[rId, 1] != 0) {
nodeR <- nodeLi[[tre[rId, 2]]]
nodeL <- nodeLi[[tre[rId, 1]]]
nodeM <- nodeLi[[tre[rId, 6]]]
nodeT <- nodeLi[[rId]]
nodeT <- append.XMLNode(nodeT, nodeL)
nodeT <- append.XMLNode(nodeT, nodeR)
nodeT <- append.XMLNode(nodeT, nodeM)
nodeLi[[rId]] <- nodeT
}
rId <- rId - 1
}
return(nodeLi[[1]])
}
.makeNodes <- function(n, mod, tinf, fieldInfo) {
if (n == 1) {
return(append.XMLNode(xmlNode("Node", attrs = c(id = 1)), xmlNode("True")))
} else {
side <- 6
if (n %in% tinf[, 1]) {
side <- 1
}
if (n %in% tinf[, 2]) {
side <- 2
}
score <- NULL
score <- tinf[n, 5]
if (is.null(score)) {
rfNode <- xmlNode("Node", attrs = c(id = n))
} else {
rfNode <- xmlNode("Node", attrs = c(id = n, score = score))
}
rowid <- which(tinf[, side] == n)
fname <- fieldInfo$name[tinf[rowid, 3]]
fname0 <- names(attr(mod$Terms, "dataClasses"))[tinf[rowid, 3]]
logical <- FALSE
numeric <- FALSE
fieldClass <- fieldInfo$class[[fname]]
if (fieldClass == "numeric") {
numeric <- TRUE
}
if (fieldClass == "logical") {
logical <- TRUE
}
if (numeric) {
if (side == 1) {
splitNode <- xmlNode("SimplePredicate", attrs = c(
field = fname, operator = "lessThan",
value = tinf[rowid, 4]
))
} else if (side == 2) {
splitNode <- xmlNode("SimplePredicate", attrs = c(
field = fname, operator = "greaterOrEqual",
value = tinf[rowid, 4]
))
} else {
splitNode <- xmlNode("SimplePredicate", attrs = c(field = fname, operator = "isMissing"))
}
} else if (logical) {
if (side == 6) {
splitNode <- xmlNode("SimplePredicate", attrs = c(field = fname, operator = "isMissing"))
} else {
bool <- ifelse(tinf[rowid, 4] <= 0.5, FALSE, TRUE)
splitNode <- xmlNode("SimplePredicate", attrs = c(
field = fname, operator = "equal",
value = bool
))
}
} else {
if (side == 6) {
splitNode <- xmlNode("SimplePredicate", attrs = c(field = fname, operator = "isMissing"))
} else {
splitid <- mod$c.splits[[as.integer(tinf[rowid, 4]) + 1]]
binary <- 0.5 - splitid / 2.0
ssp <- xmlNode("SimpleSetPredicate", attrs = c(field = fname, booleanOperator = "isIn"))
num1 <- 0
scat <- NULL
holder <- array(0, dim = length(fieldInfo$levels[fname][[1]]))
holder0 <- array(0, dim = c(1, mod$forest$ncat[fname][[1]]))
for (k in 1:length(binary))
{
holder[k] <- binary[k]
}
options(useFancyQuotes = FALSE)
for (k in 1:length(fieldInfo$levels[[fname]]))
{
if (side == 1) {
if (holder[k] == 1) {
num1 <- num1 + 1
catname <- fieldInfo$levels[[fname]][k]
catname0 <- mod$forest$xlevels[fname][[1]][k]
scat <- paste(scat, " ", dQuote(catname))
}
} else {
if (holder[k] == 0) {
num1 <- num1 + 1
catname <- fieldInfo$levels[[fname]][k]
scat <- paste(scat, " ", dQuote(catname))
}
}
}
scat <- gsub("^[ ]*", "", scat)
ap <- xmlNode("Array", attrs = c(n = num1, type = "string"), scat)
ssp <- append.XMLNode(ssp, ap)
splitNode <- ssp
}
}
rfNode <- append.XMLNode(rfNode, splitNode)
}
return(rfNode)
} |
exactprob1<-function(n.I,lowerbounds,p,k,K){
m=c(n.I[1],diff(n.I))
plo=rep(0,k)
phi=NULL
c.mat=matrix(0,ncol=k,nrow=n.I[k]+1)
c.mat[,1]=stats::dbinom(0:n.I[k],m[1],p)
plo[1]=sum(c.mat[(0:n.I[k])<=lowerbounds[1],1])
for(i in 2:k){
no.stop=((lowerbounds[(i-1)]+1):n.I[(i-1)])
no.stop.mat=matrix(no.stop,byrow=T,nrow=n.I[k]+1,ncol=length(no.stop))
succ.mat=matrix(0:n.I[k],byrow=F,ncol=length(no.stop),nrow=n.I[k]+1)
bin.mat=matrix(stats::dbinom(succ.mat-no.stop.mat,m[i],p),byrow=F,ncol=length(no.stop),nrow=n.I[k]+1)
c.mat[,i]=bin.mat%*%c.mat[no.stop+1,(i-1)]
plo[i]=sum(c.mat[(0:n.I[k])<=lowerbounds[i],i])
if(i==K){
plo[i]=sum(c.mat[(0:n.I[k])<lowerbounds[i],i])
phi=sum(c.mat[(0:n.I[k])>=lowerbounds[i],i])
}
}
return(list(plo=plo,phi=phi))
} |
emergencystart <- function(x){
nGroups <- nrow(x@sample@groups)
if (x@model == 'varcov' && x@types[['y']] == 'ggm' && !is.null(x@baseline_saturated$saturated) && nGroups == 1){
mats <- formModelMatrices(x)
nGroups <- nrow(x@sample@groups)
g <- 1
satCovs <- spectralshift(x@baseline_saturated$saturated@modelmatrices[[g]]$sigma)
net <- mats[[g]]$omega != 0
zeroes <- which(net & diag(ncol(net)) != 1, arr.ind = TRUE)
if (nrow(zeroes) > 0){
suppressWarnings(glas <- glasso::glasso(as.matrix(satCovs), 0, zero = zeroes))
omega <- -1*cov2cor(glas$wi)
diag(omega) <- 0
} else {
omega <- qgraph::wi2net(solve(as.matrix(satCovs)))
}
for (i in which(x@parameters$matrix == "omega" & x@parameters$group_id == g & !x@parameters$fixed)){
x@parameters$est[i] <- omega[x@parameters$row[i], x@parameters$col[i]]
}
if (!x@sample@corinput){
toR <- diag(1/sqrt(diag(solve_symmetric(diag(nrow(omega)) - omega))))
toCov <- diag(sqrt(diag(satCovs)))
delta <- toCov %*% toR
for (i in which(x@parameters$matrix == "delta" & x@parameters$group_id == g & !x@parameters$fixed)){
x@parameters$est[i] <- delta[x@parameters$row[i], x@parameters$col[i]]
}
}
} else {
allMats <- x@matrices[!grepl("(mu)|(nu)",x@matrices$name),]
for (mat in seq_len(nrow(allMats))){
if (allMats$posdef[mat]){
x@parameters$est[x@parameters$matrix == allMats$name[mat] & !x@parameters$fixed] <-
ifelse(x@parameters$row[x@parameters$matrix == allMats$name[mat] & !x@parameters$fixed] ==
x@parameters$col[x@parameters$matrix == allMats$name[mat] & !x@parameters$fixed], 1, 0)
} else {
x@parameters$est[x@parameters$matrix == allMats$name[mat]& !x@parameters$fixed] <-
(x@parameters$est[x@parameters$matrix == allMats$name[mat]& !x@parameters$fixed] != 0) * 1e-7 * sign(x@parameters$est[x@parameters$matrix == allMats$name[mat]& !x@parameters$fixed])
}
}
}
return(x)
} |
"df2latex" <-
function(x,digits=2,rowlabels=TRUE,apa=TRUE,short.names=TRUE,
font.size ="scriptsize",big.mark=NULL, drop.na=TRUE, heading="A table from the psych package in R",
caption="df2latex",label="default",char=FALSE,stars=FALSE,silent=FALSE,file=NULL,append=FALSE,cut=0,big=.0,abbrev=NULL,long=FALSE) {
if(is.null(abbrev)) abbrev<- digits + 3
nvar <- dim(x)[2]
rname<- rownames(x)
tempx <- x
comment <- paste("%", match.call())
if(long) {
header <- paste0("\\begin{center}
\\begin{",font.size,"}
\\begin{longtable}")
header <- c(header,"{l",rep("r",(nvar)),"}\n")
header <- c(header,paste0("
\\caption{",caption,"}
\\endfirsthead
\\multicolumn{",nvar+1,"}{c}
{{\\bfseries \\tablename\\ \\thetable{} -- continued from previous page}} \\\\
\\endhead
\\hline \\multicolumn{",nvar+1,"}{|c|}{{Continued on next page}} \\\\
\\hline
\\endfoot
\\hline \\hline
\\endlastfoot
"))
footer <- paste0("\\end{longtable}
\\end{",font.size,"}
\\end{center}")
} else {
header <- paste("\\begin{table}[htpb]",
"\\caption{",caption,"}
\\begin{center}
\\begin{",font.size,"}
\\begin{tabular}",sep="")
if(stars) {if(rowlabels) {
header <- c(header,"{l",rep("S",(nvar)),"}\n")} else {header <- c(header,"{",rep("S",(nvar+1)),"}\n")} } else {
if(rowlabels) { header <- c(header,"{l",rep("r",(nvar)),"}\n")} else {header <- c(header,"{",rep("r",(nvar+1)),"}\n")}
}
if(apa) {header <- c(header,
"\\multicolumn{",nvar,"}{l}{",heading,"}",
'\\cr \n \\hline ')
footer <- paste(" \\hline ")} else {footer <- NULL}
if (stars){
footer <- paste(" \\hline
\n \\multicolumn{7}{l}{\\scriptsize{\\emph{Note: }\\textsuperscript{***}$p<.001$;
\\textsuperscript{**}$p<.01$;
\\textsuperscript{*}$p<.05$",".}}" ,sep = "")
}else{
footer <- paste(" \\hline ")}
footer <- paste(footer,"
\\end{tabular}
\\end{",font.size,"}
\\end{center}
\\label{",label,"}
\\end{table}
",sep=""
)
}
if(big) all.x <- x
if(!char) {if(!is.null(digits)) {if(is.numeric(x) ) {x <- round(x,digits=digits)} else {for(i in 1:ncol(x)) {if (is.numeric(x[,i])) x[,i] <- round(x[,i],2)} }
if(cut > 0) x[abs(x) < cut] <- NA }
}
cname <- colnames(x)
if (short.names) cname <- abbreviate(cname,minlength=abbrev)
names1 <- paste0("{",cname[1:(nvar-1)], "} & ")
lastname <- paste0("{",cname[nvar],"}\\cr \n")
if(apa) {allnames <- c("Variable & ",names1,lastname," \\hline \n")} else {if(rowlabels) {allnames <- c(" & ",names1,lastname,"\\cr \n")} else {
allnames <- c(names1,lastname,"\\cr \n")}}
if(!char) {if(is.null(big.mark)) { x <- format(x,drop0trailing=FALSE)
if(big > 0) {
for(i in 1:ncol(x)) {if (is.numeric(all.x[,i])) x[abs(all.x[,i] ) > big,i] <- paste0("\\bf{",x[abs(all.x[,i]) > big,i],"}") }}
} else
{x <- prettyNum(x,big.mark=",",drop0trailing=FALSE)}
} else {if(big > 0) { x[!is.na(abs(as.numeric(all.x))>big) & abs(as.numeric(all.x))>big ] <- paste0("\\bf{", x[!is.na(abs(as.numeric(all.x))>big) & abs(as.numeric(all.x))>big ],"}") } }
value <- apply(x,1,paste,collapse=" & ")
if(rowlabels) {value <- paste(sanitize.latex(rname)," & ",value)} else {value <- paste(" & ",value)}
values <- paste(value, "\\cr", "\n")
if(drop.na) values <- gsub("NA"," ",values,fixed=TRUE)
if(!silent) {cat(comment,"\n")
cat(header)
cat(allnames)
cat(values)
cat(footer)
}
result <- c(header,allnames,values,footer)
if(!is.null(file)) write.table(result,file=file,row.names=FALSE,col.names=FALSE,quote=FALSE,append=append)
invisible(result)
}
cor2latex <- function (x, use = "pairwise", method="pearson", adjust="holm", stars = FALSE, digits=2, rowlabels = TRUE, lower = TRUE, apa = TRUE,
short.names = TRUE, font.size = "scriptsize", heading = "A correlation table from the psych package in R.",
caption = "cor2latex", label = "default",silent=FALSE,file=NULL,append=FALSE,cut=0,big=.0)
{
if(stars) heading <- paste(heading, "Adjust for multiple tests = ",adjust )
if (!is.na(class(x)[2]) & class(x)[2]=="corr.test") {
r <- x$r
p <- x$p} else {
if (nrow(x) > ncol(x)) {
x <- psych::corr.test(x, use=use,method=method,adjust=adjust)
r <- x$r
p <- x$p } else {
r <- x
p <- NULL
}
}
r <- round(r, digits)
r <- format(r, nsmall = digits,drop0trailing=FALSE)
if (lower) {
r[upper.tri(r)] <- "~"
} else {
r[lower.tri(r)] <- "~"
}
if(isTRUE(stars && is.null(p))) stop("To print significance levels, x must be be either a data frame of observations or a correlation matrix created with the corr.test function of the package psych. If you are not interested in displaying signicance level set stars = FALSE")
mystars <- ifelse(p < .001, "{***}", ifelse(p < .01, "{**}", ifelse(p < .05, "{*}", "")))
mystars <- t(mystars)
if(stars) { R <- matrix(paste(r,mystars,sep=""),ncol=ncol(r))} else {R <- r}
diag(R) <- paste(diag(r), " ", sep="")
rownames(R) <- colnames(r)
colnames(R) <- colnames(r)
if (lower) {
R[upper.tri(R, diag = FALSE)] <- ""
} else {
R[lower.tri(R, diag = FALSE)] <- ""
}
if(stars) {char<- TRUE} else {char <- FALSE}
return(df2latex(R, digits = digits, rowlabels = rowlabels,
apa = apa, short.names = short.names, font.size = font.size,
heading = heading, caption = caption, label = label, char=TRUE,stars = stars,silent=silent,file=file,append=append,cut=cut,big=big))
}
"fa2latex" <-
function(f,digits=2,rowlabels=TRUE,apa=TRUE,short.names=FALSE,cumvar=FALSE,cut=0,big=.3,alpha=.05,font.size ="scriptsize", heading="A factor analysis table from the psych package in R",caption="fa2latex",label="default",silent=FALSE,file=NULL,append=FALSE) {
if(class(f)[2] == "fa.ci") {
if(is.null(f$cip)) {px <- f$cis$p} else {px <- f$cip}} else {px <- NULL}
x <- unclass(f$loadings)
if(!is.null(f$Phi)) {Phi <- f$Phi} else {Phi <- NULL}
nfactors <- ncol(x)
if(nfactors > 1) {if(is.null(Phi)) {h2 <- rowSums(x^2)} else {h2 <- diag(x %*% Phi %*% t(x)) }} else {h2 <-x^2}
u2 <- 1- h2
vtotal <- sum(h2 + u2)
if(cut > 0) x[abs(x) < cut] <- NA
if(!is.null(f$complexity)) {x <- data.frame(x,h2=h2,u2=u2,com=f$complexity) } else {x <- data.frame(x,h2=h2,u2=u2)}
colnames(x)[which(colnames(x)=='h2')] <- '$h^2$'
colnames(x)[which(colnames(x)=='u2')] <- '$u^2$'
nvar <- dim(x)[2]
comment <- paste("% Called in the psych package ", match.call())
header <- paste("\\begin{table}[htpb]",
"\\caption{",caption,"}
\\begin{center}
\\begin{",font.size,"}
\\begin{tabular}",sep="")
header <- c(header,"{l",rep("r",nvar),"}\n")
if(apa) header <- c(header,
"\\multicolumn{",nvar,"}{l}{",heading,"}",
'\\cr \n \\hline ')
if(apa) {footer <- paste(" \\hline ")}
footer <- paste(footer,"
\\end{tabular}
\\end{",font.size,"}
\\end{center}
\\label{",label,"}
\\end{table}
",sep=""
)
x <- round(x,digits=digits)
cname <- colnames(x)
if (short.names) cname <- 1:nvar
names1 <- paste(cname[1:(nvar-1)], " & ")
lastname <- paste(cname[nvar],"\\cr \n")
if(apa) {allnames <- c("Variable & ",names1,lastname," \\hline \n")} else {allnames <- c(" & ",names1,lastname,"\\cr \n")}
fx <- format(x,drop0trailing=FALSE)
{if(!is.null(px) && (cut == 0)) { temp <- fx[1:nfactors]
temp[px < alpha] <- paste("\\bf{",temp[px < alpha],"}",sep="")
fx[1:nfactors] <- temp
}
if(big > 0) {temp <- fx[1:nfactors]
x <- x[1:nfactors]
temp[!is.na(x) & (abs(x) > big)] <- paste("\\bf{",temp[!is.na(x) & (abs(x) > big)],"}",sep="")
fx[1:nfactors] <- temp
}
value <- apply(fx,1,paste,collapse=" & ")
value <- gsub("NA", " ", value, fixed = TRUE)
if(rowlabels) value <- {paste(sanitize.latex(names(value))," & ",value)} else {paste(" & ",value)}
values <- paste(value, "\\cr", "\n")
if(!silent) {
cat(comment,"\n")
cat(header)
cat(allnames)
cat(values)
}
x <- f$loadings
nvar <- nrow(x)
if(is.null(Phi)) {if(nfactors > 1) {vx <- colSums(x^2) } else {
vx <- diag(t(x) %*% x)
vx <- vx*nvar/vtotal
}} else {vx <- diag(Phi %*% t(x) %*% x)
vx <- vx*nvar/vtotal }
vx <- round(vx,digits)
loads <- c("\\hline \\cr SS loadings &",paste(vx," & ",sep=""),"\\cr \n")
if(!silent) { cat(loads)}
summ <- NULL
if(cumvar) {
provar <- round(vx/nvar,digits)
summ <- c("Proportion Var &" ,paste( provar, " & ",sep=""),"\\cr \n")
if (nfactors > 1) {cumvar <- round(cumsum(vx/nvar),digits)
cumfavar <- round(cumsum(vx/sum(vx)),digits=digits)
summ <- c(summ, "Cumulative Var & ",paste( cumvar," & ", sep=""),"\\cr \n",
"Cum. factor Var & ",paste(round(cumsum(vx/sum(vx)),digits=digits)," & ",sep=""),"\\cr \n")
}
if(!silent) {cat(summ) }
}
loads <- c(loads,summ)
if(!is.null(Phi)) {
summ <- c("\\cr
\\hline \\cr \n")
if(!silent) {cat(summ) }
Phi <- round(Phi,digits)
phi <- format(Phi,nsmall=digits)
phi <-apply(phi,1,paste,collapse=" & ")
phi <-paste(colnames(x)," &",phi)
phi <- paste(phi, "\\cr", "\n")
loads <- c(loads,summ,phi)
if(!silent) { cat(phi)}
}
if(!silent) { cat(footer)}
}
values <- c(values,loads)
result <- c(header,allnames,values,footer)
if(!is.null(file)) write.table(result,file=file,row.names=FALSE,col.names=FALSE,quote=FALSE,append=append)
invisible(result)
}
"irt2latex" <-
function(f,digits=2,rowlabels=TRUE,apa=TRUE,short.names=FALSE,font.size ="scriptsize", heading="An IRT factor analysis table from R",caption="fa2latex" ,label="default",silent=FALSE,file=NULL,append=FALSE) {
if(class(f)[2] != "polyinfo" ) {nf <- length(f$plot$sumInfo) } else {nf <- length(f$sumInfo) }
for(i in (1:nf)) {
if(class(f)[2] != "polyinfo" ) {x <- f$plot$sumInfo[[i]]} else {x <- f$sumInfo[[i]] }
if(nf>1) {
rowmax <- apply(x,1,max, na.rm=TRUE)
rowmax <- which(rowmax <.001,arr.ind=TRUE)
if(!is.null(rowmax)) x <- x[-rowmax,]}
nvar <- ncol(x)
comment <- paste("%", match.call())
header <- paste("\\begin{",font.size,"} \\begin{table}[htpb]",
"\\caption{",caption,"}
\\begin{center}
\\begin{tabular}",sep="")
header <- c(header,"{l",rep("r",nvar),"}\n")
if(apa) header <- c(header,
"\\multicolumn{",nvar,"}{l}{",heading," for factor " , i, " }",
"\\cr \\hline \\cr",
"\n & \\multicolumn{7}{c}{Item information at $\\theta$} \\cr \\cline{2-8} ")
if(apa) {footer <- paste(" \\hline ")}
footer <- paste(footer,"
\\end{tabular}
\\end{center}
\\label{",label,"}
\\end{table}
\\end{",font.size,"}
",sep=""
)
x <- round(x,digits=digits)
cname <- colnames(x)
if (short.names) cname <- 1:nvar
names1 <- paste(cname[1:(nvar-1)], " & ")
lastname <- paste(cname[nvar],"\\cr \n")
if(apa) {allnames <- c("Item & ",names1,lastname," \\hline \n")} else {allnames <- c(" & ",names1,lastname,"\\cr \n")}
x <- format(x,drop0trailing=FALSE)
value <- apply(x,1,paste,collapse=" & ")
if(rowlabels) value <- paste(sanitize.latex(names(value))," & ",value)
values <- paste(value, "\\cr", "\n")
if(class(f)[2] != "polyinfo" ) {test.info <- colSums(f$plot$sumInfo[[i]])} else {test.info <- colSums(f$sumInfo[[i]])}
sem <- sqrt(1/test.info)
reliab <- 1 - 1/test.info
summary <- rbind(test.info,sem,reliab)
summary <- round(summary,digits)
summary <- format(summary,nsmall=digits)
summary <- cbind(c("Test.info","SEM","Reliability"),summary)
summary <- apply(summary,1,paste,collapse=" & ")
summary <- paste(summary,"\\cr \n")
if(!silent) { cat(comment,"\n")
cat(header)
cat(allnames)
cat(values)
cat("\\hline \n & \\multicolumn{7}{c}{Summary statistics at $\\theta$} \\cr \\cline{2-8}")
cat(summary)
cat(footer)
}
}
result <- c(header,allnames,values,summary,footer)
if(!is.null(file)) write.table(result,file=file,row.names=FALSE,col.names=FALSE,quote=FALSE,append=append)
invisible(result)
}
"sanitize.latex" <-
function(astring) {
result <- astring
result <- gsub("&", "\\&", result, fixed = TRUE)
result <- gsub("_", "\\_", result, fixed = TRUE)
result <- gsub("%", "\\%", result, fixed = TRUE)
return(result)
}
"omega2latex" <-
function(f,digits=2,rowlabels=TRUE,apa=TRUE,short.names=FALSE,cumvar=FALSE,cut=.2,font.size ="scriptsize", heading="An omega analysis table from the psych package in R",caption="omega2latex",label="default",silent=FALSE,file=NULL,append=FALSE) {
if(class(f)[2] == "omega" ) f$loadings <- f$schmid$sl
x <- unclass(f$loadings)
nfactors <- ncol(x)
h2 <- rowSums(x^2)
u2 <- 1- h2
vtotal <- sum(h2 + u2)
nvar <- dim(x)[2]
comment <- paste("% Called in the psych package ", match.call())
header <- paste("\\begin{",font.size,"} \\begin{table}[htpb]",
"\\caption{",caption," with cut = ",cut,"\n $\\omega_h = ",round(f$omega_h,digits), "\\;\\;\\;\\alpha (\\lambda_3) = ",round(f$alpha,digits), "\\;\\;\\;\\lambda_6^* = ",round(f$G6,digits),"\\;\\;\\; \\omega_t = ",round(f$omega.tot,digits),"$ }
\\begin{center}
\\begin{tabular}",sep="")
header <- c(header,"{l",rep("r",nvar),"}\n")
if(apa) header <- c(header,
"\\multicolumn{",nvar,"}{l}{",heading,"}",
'\\cr \n \\hline ')
if(apa) {footer <- paste(" \\hline ")}
footer <- paste(footer,"
\\end{tabular}
\\end{center}
\\label{",label,"}
\\end{table}
\\end{",font.size,"}
",sep=""
)
x[abs(x) < cut] <- NA
x <- round(x,digits=digits)
cname <- colnames(x)
if (short.names) cname <- 1:nvar
names1 <- paste(cname[1:(nvar-1)], " & ")
lastname <- paste(cname[nvar],"\\cr \n")
if(apa) {allnames <- c("Variable & ",names1,lastname," \\hline \n")} else {allnames <- c(" & ",names1,lastname,"\\cr \n")}
x <- format(x,drop0trailing=FALSE)
value <- apply(x,1,paste,collapse=" & ")
value <- gsub("NA", " ", value, fixed = TRUE)
if(rowlabels) value <- {paste(sanitize.latex(names(value))," & ",value)} else {paste(" & ",value)}
values <- paste(value, "\\cr", "\n")
x <- f$loadings
nvar <- nrow(x)
vx <- colSums(x^2)[1:(ncol(x)-3)]
vx <- round(vx,digits)
loads <- c("\\hline \\cr SS loadings &",paste(vx," & ",sep=""),"\\cr \n")
if(!silent) { cat(comment,"\n")
cat(header)
cat(allnames)
cat(values)
cat(loads)
cat(footer)
}
result <- c(header,allnames,values,loads,footer)
if(!is.null(file)) write.table(result,file=file,row.names=FALSE,col.names=FALSE,quote=FALSE,append=append)
invisible(result)
}
"ICC2latex" <-
function(icc,digits=2,rowlabels=TRUE,apa=TRUE,ci=TRUE,
font.size ="scriptsize",big.mark=NULL, drop.na=TRUE, heading="A table from the psych package in R",
caption="ICC2latex",label="default",char=FALSE,silent=FALSE,file=NULL,append=FALSE) {
if((length(class(icc)) < 2 ) | (class(icc)[2] !="ICC")) icc <- psych::ICC(icc)
x <- icc$results
nvar <- dim(x)[2]
rname<- rownames(x)
comment <- paste("%", match.call())
header <- paste("\\begin{",font.size,"} \\begin{table}[[htpb]",
"\\caption{",caption,"}
\\begin{tabular}",sep="")
if(rowlabels) { header <- c(header,"{l",rep("r",(nvar)),"}\n")} else {header <- c(header,"{",rep("r",(nvar+1)),"}\n")
}
if(apa) {header <- c(header,
"\\multicolumn{",5,"}{l}{",heading,"}", '\\cr \n \\hline ')
footer <- paste(" \\hline \\cr \\multicolumn{ 5 }{c}{ Number of subjects = ", icc$n.obs, "Number of raters = ",icc$n.judge,"}")} else {footer <- NULL}
footer <- paste(footer,"
\\end{tabular}
\\label{",label,"}
\\end{table}
\\end{",font.size,"}
",sep=""
)
x[2:nvar] <- try(round(x[2:nvar],digits=digits))
cname <- colnames(x)
if(!ci) nvar <- nvar-2
names1 <- paste(cname[1:(nvar-1)], " & ")
lastname <- paste(cname[nvar],"\\cr \n")
if(apa) {allnames <- c("Variable & ",names1,lastname," \\hline \n")} else {if(rowlabels) {allnames <- c(" & ",names1,lastname,"\\cr \n")} else {
allnames <- c(names1,lastname,"\\cr \n")}}
if(!char) {if(is.null(big.mark)) { x <- format(x[1:nvar],drop0trailing=FALSE)} else
{x <- prettyNum(x,big.mark=",",drop0trailing=FALSE)}
}
value <- apply(x,1,paste,collapse=" & ")
if(rowlabels) {value <- paste(sanitize.latex(rname)," & ",value)} else {value <- paste(" & ",value)}
values <- paste(value, "\\cr", "\n")
if(drop.na) values <- gsub("NA"," ",values,fixed=TRUE)
if(!silent) { cat(comment,"\n")
cat(header)
cat(allnames)
cat(values)
cat(footer)
}
result <- c(header,allnames,values,footer)
if(!is.null(file)) write.table(result,file=file,row.names=FALSE,col.names=FALSE,quote=FALSE,append=append)
invisible(result)
}
|
morphomapCore<-function (out.sur = out.sur, inn.sur = inn.sur, num.sect = 61,
mech.len, clean_int_out = TRUE, param1 = 0.5, radius.fact = 2.5,
npovs = 100, num.points = 500, start = 0.2, end = 0.8, print.progress = TRUE)
{
ext_raw_sects_2D <- array(NA, dim = c(num.points, 2, num.sect))
inn_raw_sects_2D <- array(NA, dim = c(num.points, 2, num.sect))
ext_raw_sects_3D <- array(NA, dim = c(num.points, 3, num.sect))
inn_raw_sects_3D <- array(NA, dim = c(num.points, 3, num.sect))
sect_poi <- seq(mech.len * start, mech.len * end, length = num.sect)
if(print.progress==TRUE){
pb <- txtProgressBar(min=0,max=num.sect-1,initial=0,style=3)
step<-0
}
for (m in 1:num.sect) {
p1 <- c(0, 0, sect_poi[m])
p2 <- c(100, 0, sect_poi[m])
p3 <- c(0, 100, sect_poi[m])
inter_out <- NULL
inter_inn <- NULL
inter_out <- meshPlaneIntersect(out.sur, p1, p2, p3)[,
c(1, 2)]
inter_inn <- meshPlaneIntersect(inn.sur, p1, p2, p3)[,
c(1, 2)]
inters <- inter_inn
ordered_out_temp <- morphomapSort(inter_out)
ordered_out_temp <- rbind(ordered_out_temp, ordered_out_temp[1,
])
ordered_out <- ordered_out_temp
if (clean_int_out == TRUE) {
inter_inn <- morphomapFlip(inter_inn, param1 = param1,
radius.fact = radius.fact, npovs = npovs)
}
ordered_inn_temp <- morphomapSort(inter_inn)
ordered_inn_temp <- rbind(ordered_inn_temp, ordered_inn_temp[1,
])
ordered_inn <- ordered_inn_temp
ev_out <- equidistantCurve(ordered_out, n = num.points,
iterations = 1, increment = 0)
ev_inn <- equidistantCurve(ordered_inn, n = num.points,
iterations = 1, increment = 0)
ext_raw_sects_2D[, , m] <- ev_out
inn_raw_sects_2D[, , m] <- ev_inn
ext_raw_sects_3D[, , m] <- cbind(ev_out, sect_poi[m])
inn_raw_sects_3D[, , m] <- cbind(ev_inn, sect_poi[m])
if(print.progress==TRUE){
setTxtProgressBar(pb,step)
step <- step+1
}
}
if(print.progress==TRUE){
close(pb)
}
out <- list(`3D_out` = ext_raw_sects_3D, `3D_inn` = inn_raw_sects_3D,
`2D_out` = ext_raw_sects_2D, `2D_inn` = inn_raw_sects_2D,
mech_length = mech.len, start = start, end = end)
return(out)
} |
smirt <- function( dat, Qmatrix, irtmodel="noncomp",
est.b=NULL, est.a=NULL,
est.c=NULL, est.d=NULL, est.mu.i=NULL, b.init=NULL, a.init=NULL,
c.init=NULL, d.init=NULL, mu.i.init=NULL, Sigma.init=NULL,
b.lower=-Inf, b.upper=Inf, a.lower=-Inf, a.upper=Inf,
c.lower=-Inf, c.upper=Inf, d.lower=-Inf, d.upper=Inf,
theta.k=seq(-6,6,len=20), theta.kDES=NULL, qmcnodes=0,
mu.fixed=NULL, variance.fixed=NULL,
est.corr=FALSE, max.increment=1, increment.factor=1,
numdiff.parm=.0001, maxdevchange=.10,
globconv=.001, maxiter=1000, msteps=4, mstepconv=.001)
{
s1 <- Sys.time()
if (is.null(colnames(dat))){
colnames(dat) <- paste0("I", 1:ncol(dat))
}
dat0 <- dat <- as.matrix(dat)
N <- nrow(dat)
res1 <- .smirt.check.inits( a.init, b.init, irtmodel, Qmatrix )
a.init <- res1$a.init
b.init <- res1$b.init
Q <- Qmatrix
if ( is.null( theta.kDES) ){
D <- ncol(Qmatrix)
TD <- D
} else {
D <- ncol(theta.k)
TD <- ncol(theta.kDES )
}
if ( is.null(colnames(Qmatrix) ) ){
colnames(Qmatrix) <- paste0( "Dim", 1:D )
}
if ( is.null(theta.kDES) ){
nodes <- theta.k
theta.k <- as.matrix( expand.grid( as.data.frame( matrix( rep(nodes, D),
ncol=D ) ) ) )
}
theta.k <- as.matrix( theta.k )
Q <- as.matrix(Q)
Qmatrix <- as.matrix(Qmatrix)
QMC <- FALSE
if (qmcnodes>0){
QMC <- TRUE
theta.k <- qmc.nodes( snodes=qmcnodes, ndim=D )
colnames(theta.k) <- paste0("Dim",1:D)
theta.k0 <- theta.k
}
TP <- nrow(theta.k)
if ( is.null(theta.kDES) ){ theta.kDES <- theta.k }
theta.kDES <- as.matrix( theta.kDES )
K <- 1
dat2 <- dat
I <- ncol(dat)
dat2.resp <- 1 - is.na(dat)
dat2[ dat2.resp==0 ] <- 0
dat2.ind0 <- dat2.resp * 1*(dat2==0)
dat2.ind1 <- dat2.resp * 1*(dat2==1)
dat2.ind <- as.matrix( cbind( dat2.ind0, dat2.ind1 ) )
if ( is.null(b.init)){
if (irtmodel!="comp"){
b <- Qmatrix * matrix( - stats::qlogis( colMeans(dat, na.rm=TRUE ) ),I, D )
} else {
b <- - stats::qlogis( colMeans(dat, na.rm=TRUE ) )
}
} else {
b <- b.init
}
if ( ! is.null(est.b) & is.null(b.init) ){ b <- 0*b }
e1 <- matrix( 1:I, I, ncol(Qmatrix) )
if ( is.null(est.b)){
if (irtmodel!="comp"){ est.b <- Qmatrix*e1 }
if (irtmodel=="comp"){ est.b <- 1:I }
}
if ( is.null(a.init) ){
a <- matrix( 1, I, ncol(Qmatrix) )
a[ Qmatrix==0 ] <- 0
} else { a <- a.init }
max.a.increment <- matrix( .4, nrow=1, ncol=ncol(a) )
if ( ! is.null( est.a)){
if ( est.a=="2PL"){
est.a <- matrix(1:I, I, ncol(Qmatrix) ) * ( Qmatrix !=0 )
est.corr <- TRUE
}
}
if ( is.null(est.a)){
est.a <- 0 * Qmatrix*e1
}
if ( ! is.null(est.a) & is.null(a.init) ){ a <- 1*a }
if ( is.null(c.init)){ c <- rep(0,I) } else { c <- c.init }
if ( is.null(d.init)){ d <- rep(1,I) } else { d <- d.init }
if ( is.null(mu.i.init)){
mu.i <- rep(.5,I)
mu.i[ ( rowSums(Qmatrix>0)==1 ) ] <- 0
} else {
mu.i <- mu.i.init
}
if ( irtmodel=="partcomp"){
if ( is.null(est.mu.i) ){
est.mu.i <- ( 1:I ) * ( rowSums(Qmatrix>0) > 1 )
}
}
mu <- rep(0,D)
if ( is.null(mu.fixed) ){ mu.fixed <- cbind( 1:D, 0 ) }
if ( is.null(Sigma.init) ){
Sigma <- .4+.6*diag(1,D) } else { Sigma <- Sigma.init }
if ( ! is.null(variance.fixed ) ){
Sigma[ variance.fixed[,1:2,drop=FALSE] ] <- variance.fixed[,3]
Sigma[ variance.fixed[,c(2,1),drop=FALSE] ] <- variance.fixed[,3]
}
pi.k <- sirt_dmvnorm_discrete( theta.k, mean=mu, sigma=Sigma )
n.ik <- array( 0, dim=c(TP,I, K+1) )
probs <- array(0, dim=c(I,K+1,TP))
se.mu.i <- se.d <- se.c <- se.b <- se.a <- NULL
iter <- 0
dev0 <- dev <- 0
conv <- devchange <- 1000
disp <- "...........................................................\n"
while( ( ( maxdevchange < devchange ) | (globconv < conv) ) &
( iter < maxiter )
){
cat(disp)
cat("Iteration", iter+1, " ", paste( Sys.time() ), "\n" )
dev0 <- dev
b0 <- b
a0 <- a
c0 <- c
d0 <- d
mu0 <- mu
mu.i0 <- mu.i
Sigma0 <- Sigma
probres <- .smirt.calcprob( a, b, Q=Qmatrix, thetak=theta.kDES, c, d,
mu.i, irtmodel )
probs <- problong2probarray( probres, I, TP )
if (QMC){ pi.k <- 1+0*pi.k }
probsM <- matrix( aperm( probs, c(2,1,3) ), nrow=I*2, ncol=TP )
res1 <- calcpost( dat2, dat2.resp, probsM, dat2.ind, pi.k, K )
f.yi.qk <- res1$fyiqk
f.qk.yi <- res1$f.qk.yi
pi.k <- res1$pi.k
n.ik <- array( res1$n.ik, dim=dim(n.ik) )
N.ik <- res1$N.ik
res2 <- .smirt.est.b( b, a, c, d, mu.i, Qmatrix, est.b,
theta.k=theta.kDES,
n.ik, I, K, TP, D, numdiff.parm=numdiff.parm,
max.increment=max.increment,
msteps, mstepconv, irtmodel, increment.factor )
b <- res2$b
se.b <- res2$se.b
b <- smirt_squeeze( b, b.lower, b.upper, est.b )
if ( sum (est.a) > 0 ){
res2 <- .smirt.est.a( b, a, c, d, mu.i, Qmatrix, est.a,
theta.k=theta.kDES,
n.ik, I, K, TP, D=TD, numdiff.parm=numdiff.parm,
max.a.increment=max.a.increment,
msteps, mstepconv, irtmodel, increment.factor )
a <- res2$a
se.a <- res2$se.a
a <- smirt_squeeze( a, a.lower, a.upper, est.a )
}
if ( sum (est.c) > 0 ){
res2 <- .smirt.est.c( b, a, c, d, mu.i, Qmatrix, est.c,
theta.k=theta.kDES,
n.ik, I, K, TP, D, numdiff.parm=numdiff.parm,
max.increment=max.increment,
msteps, mstepconv, irtmodel, increment.factor)
c <- res2$c
se.c <- res2$se.c
c <- smirt_squeeze( c, c.lower, c.upper, est.c )
}
if ( sum (est.d) > 0 ){
res2 <- .smirt.est.d( b, a, c, d, mu.i, Qmatrix, est.d,
theta.k=theta.kDES,
n.ik, I, K, TP, D, numdiff.parm=numdiff.parm,
max.increment=max.increment,
msteps, mstepconv, irtmodel, increment.factor )
d <- res2$d
se.d <- res2$se.d
d <- smirt_squeeze( d, d.lower, d.upper, est.d )
}
if ( sum(est.mu.i) > 0 ){
res2 <- .smirt.est.mu.i.partcomp( b, a, c, d, mu.i, Qmatrix, est.mu.i, theta.k,
n.ik, I, K, TP, D, numdiff.parm, max.increment=max.increment,
msteps, mstepconv, increment.factor)
mu.i <- res2$mu.i
se.mu.i <- res2$se.mu.i
}
flush.console()
if( increment.factor > 1){
max.increment <- max.increment / increment.factor
max.a.increment <- max.a.increment / increment.factor
}
m1 <- .smirt.est.covariance( f.qk.yi, Sigma, theta.k, N,
mu.fixed, variance.fixed, D, est.corr, irtmodel )
mu <- m1$mu
Sigma <- m1$Sigma
pi.k <- m1$pi.k
pi.k <- matrix( pi.k, ncol=1 )
ll <- sum( log( rowSums( f.yi.qk * outer( rep(1,nrow(f.yi.qk)), pi.k[,1] ) ) ) )
if (QMC){
ll <- sum( log( rowMeans( f.yi.qk ) ) )
theta.k <- matrix( mu, nrow=TP, ncol=D, byrow=T ) + t ( t(chol(Sigma)) %*% t(theta.k0) )
theta.kDES <- theta.k
}
dev <- -2*ll
conv <- max( abs(a-a0), abs(b-b0), abs(c-c0), abs(d-d0), abs(mu.i - mu.i0) )
iter <- iter+1
devchange <- abs( ( dev - dev0 ) / dev0 )
cat( paste( " Deviance=", round( dev, 4 ),
if (iter > 1 ){ " | Deviance change=" } else {""},
if( iter>1){round( - dev + dev0, 6 )} else { ""} ,"\n",sep="") )
cat( paste( " Maximum b parameter change=",
paste( round(max(abs(b-b0)),6), collapse=" " ), "\n", sep=""))
cat( paste( " Maximum a parameter change=",
paste( round(max(abs(a-a0)),6), collapse=" " ), "\n", sep=""))
cat( paste( " Maximum c parameter change=",
paste( round(max(abs(c-c0)),6), collapse=" " ), "\n", sep=""))
cat( paste( " Maximum d parameter change=",
paste( round(max(abs(d-d0)),6), collapse=" " ), "\n", sep=""))
if (irtmodel=="partcomp"){
cat( paste( " Maximum mu.i parameter change=",
paste( round(max(abs(mu.i-mu.i0)),6), collapse=" " ), "\n", sep=""))
}
cat( " Means: ", round( mu, 3 ), "\n")
cat( " Standard deviations: ", round( sqrt(diag(Sigma)), 3 ), "\n")
c1 <- stats::cov2cor(Sigma)
cat( " Correlations ", round( c1[lower.tri(c1)], 3 ), "\n")
}
ic <- list( "deviance"=dev, "n"=nrow(dat2) )
ic$np.item <- 0
ic$np.item.b <- ic$np.item.a <- ic$np.item.c <- ic$np.item.d <- 0
if (irtmodel=="noncomp"){
for (dd in 1:D){
ic$np.item.b <- ic$np.item.b + length( setdiff( unique( est.b[,dd] ), 0 ) )
}
} else {
ic$np.item.b <- ic$np.item.b + length( setdiff( unique( est.b ), 0 ) )
}
for (dd in 1:TD){
ic$np.item.a <- ic$np.item.a + length( setdiff( unique( est.a[,dd] ), 0 ) )
}
ic$np.item.c <- length( setdiff( unique( est.c ), 0 ) )
ic$np.item.d <- length( setdiff( unique( est.d ), 0 ) )
ic$np.item.mu.i <- length( setdiff( unique( est.mu.i ), 0 ) )
ic$np.item <- ic$np.item.b + ic$np.item.a + ic$np.item.c + ic$np.item.d + ic$np.item.mu.i
ic$np.cov <- 0
ic$np.cov.covM <- D*(D+1)/2
if ( est.corr ){
ic$np.cov.covM <- ic$np.cov.covM - D
}
if ( ! is.null(variance.fixed) ){
ic$np.cov.covM <- ic$np.cov.covM - nrow(variance.fixed)
}
ic$np.cov.mu <- D
if ( ! is.null(mu.fixed) ){
ic$np.cov.mu <- ic$np.cov.mu - nrow(mu.fixed)
}
ic$np.cov <- ic$np.cov.covM + ic$np.cov.mu
ic$np <- ic$np.item + ic$np.cov
ic$AIC <- dev + 2*ic$np
ic$BIC <- dev + ( log(ic$n) )*ic$np
ic$CAIC <- dev + ( log(ic$n) + 1 )*ic$np
ic$AICc <- ic$AIC + 2*ic$np * ( ic$np + 1 ) / ( ic$n - ic$np - 1 )
pers <- .smirt.person.parameters( data=dat2, D=D, theta.k=theta.k,
p.xi.aj=f.yi.qk, p.aj.xi=f.qk.yi, weights=rep(1,N) )
person <- pers$person
EAP.rel <- pers$EAP.rel
item <- data.frame("item"=colnames(dat))
item$N <- colSums( dat2.resp )
item$p <- colSums( dat2, na.rm=TRUE) / item$N
if ( irtmodel !="comp"){
for (dd in 1:( ncol(Qmatrix)) ){
b[ Qmatrix[,dd]==0, dd ] <- NA
se.b[ est.b[,dd]==0, dd ] <- NA
item[, paste0("b.",colnames(Qmatrix)[dd]) ] <- b[,dd]
}
} else {
item$b <- b
se.b[ est.b==0 ] <- NA
}
for (dd in 1:( ncol(Qmatrix)) ){
a[ Qmatrix[,dd]==0, dd ] <- NA
if ( sum( est.a) !=0 ){
se.a[ est.a[,dd]==0, dd ] <- NA
}
item[, paste0("a.",colnames(Qmatrix)[dd]) ] <- a[,dd]
}
item$c <- c
item$d <- d
if ( irtmodel=="partcomp" ){
mu.i[ rowSums( Qmatrix > 0 )==1 ] <- NA
item$mu.i <- mu.i
}
obji <- item
for (vv in seq(2,ncol(obji) )){
obji[,vv] <- round( obji[,vv],3 )
}
cat("*********************************\n")
cat("Item Parameters\n")
print( obji )
cat("*********************************\n")
cat("EAP Reliability=", round(EAP.rel,3), "\n")
s2 <- Sys.time()
res <- list(deviance=dev, ic=ic, item=item,
person=person, EAP.rel=EAP.rel,
mean.trait=mu, sd.trait=sqrt(diag(Sigma)),
Sigma=Sigma, cor.trait=stats::cov2cor(Sigma),
b=b, se.b=se.b, a=a, se.a=se.a,
c=c, se.c=se.c, d=d, se.d=se.d,
mu.i=mu.i, se.mu.i=se.mu.i,
f.yi.qk=f.yi.qk, f.qk.yi=f.qk.yi, probs=probs,
n.ik=n.ik, iter=iter, dat2=dat2, dat2.resp=dat2.resp,
dat=dat0, I=I, D=D, K=K, G=1, theta.k=theta.k, pi.k=pi.k,
irtmodel=irtmodel, Qmatrix=Qmatrix, s1=s1, s2=s2 )
class(res) <- "smirt"
return(res)
} |
as.Biclust <- function(object) {
RowxNumber <- gather(object) %>%
mutate(in_bicluster = !is.na(value)) %>%
select(row_name, bicluster_no, in_bicluster) %>%
group_by(row_name, bicluster_no) %>%
summarise(in_bicluster = any(in_bicluster)) %>%
ungroup() %>%
arrange(bicluster_no) %>%
mutate(bicluster_no = paste0("BC", bicluster_no)) %>%
spread(bicluster_no, in_bicluster) %>%
arrange(row_name)
RowxNumber <- as.matrix(RowxNumber[, -1])
colnames(RowxNumber) <- NULL
RowxNumber[is.na(RowxNumber)] <- FALSE
NumberxCol <- gather(object) %>%
mutate(in_bicluster = !is.na(value)) %>%
select(col_name, bicluster_no, in_bicluster) %>%
group_by(col_name, bicluster_no) %>%
summarise(in_bicluster = any(in_bicluster)) %>%
ungroup() %>%
arrange(bicluster_no) %>%
mutate(bicluster_no = paste0("BC", bicluster_no)) %>%
spread(bicluster_no, in_bicluster) %>%
arrange(col_name)
NumberxCol
NumberxCol <- as.matrix(NumberxCol[, -1])
colnames(NumberxCol) <- NULL
NumberxCol[is.na(NumberxCol)] <- FALSE
NumberxCol <- t(NumberxCol)
Number <- ncol(object$P) * ncol(object$Q)
BiclustResult(
object$params,
RowxNumber,
NumberxCol,
Number,
list(NA)
)
} |
calculate_first_minimum_density = function(mat, log.transform=TRUE, adjust=2, makeplots=FALSE){
something.is.wrong <- FALSE
if(base::is.vector(mat)){mat <- base::as.matrix(mat, ncol=1)}
firstmin.vector <- base::vector(length=base::ncol(mat))
for(j in base::seq_len(base::ncol(mat))){
vec <- mat[,j]
if(log.transform){vec = base::log2(vec+1)}
dens <- stats::density(base::sort(vec), adjust=2)
i <- 2
while(dens$y[i]==base::max(dens$y[1:i])){
i = i + 1
if(i > base::length(dens$y)){
something.is.wrong <- TRUE
break
}
}
i = i - 1
firstmax <- dens$x[i]
idmax <- base::match(firstmax, dens$x)
i <- idmax
while(dens$y[i]==base::min(dens$y[idmax:i])){
i = i + 1
if(i > base::length(dens$y)){
something.is.wrong <- TRUE
break
}
}
i = i - 1
if(!something.is.wrong){
xmain <- dens$x[i:length(dens$x)]
ymain <- dens$y[i:length(dens$x)]
secondmax <- xmain[ymain==base::max(ymain)]
firstmin <- xmain[ymain==base::min(ymain[xmain<secondmax])]
if(makeplots){
x=NULL; y=NULL
print(ggplot2::ggplot(data=base::data.frame("x"=dens$x, "y"=dens$y)) +
ggplot2::theme_minimal() +
ggplot2::geom_line(mapping=ggplot2::aes(x=x, y=y)) +
ggplot2::geom_vline(xintercept=firstmin, color="blue"))
}
if(log.transform){
firstmax = 2^firstmax
secondmax = 2^secondmax
firstmin = 2^firstmin
}
firstmin.vector[j] <- firstmin
}
}
if(base::sum(firstmin.vector == 0) > base::length(firstmin.vector) / 2){
base::message("Distribution does not appear to have two peaks, returning zero")
firstmin.vector.median <- 0
}else{
firstmin.vector <- firstmin.vector[firstmin.vector > 0]
firstmin.vector.median <- base::floor(stats::median(firstmin.vector))
}
return(firstmin.vector.median)
} |
size_n.regII.ci_exp <- function(mx, my, sx2=((xmax-xmin)/6)^2, sy2, xmin, xmax, alpha=0.05){
if(xmin>xmax)
stop("xmax < xmin !")
if(sx2<0)
stop("sx2<0 !")
if(sy2<0)
stop("sy2<0 !")
n.3 <- 1003
n.2 <- 1002
n.1 <- Inf
while(n.2!=n.1 & n.1!=n.3){
n <- ceiling(qt(1-alpha/2, n.1-2)^2*(1+max(c((xmin-mx)^2, (xmax-mx)^2))/sx2))
n.3 <- n.2
n.2 <- n.1
n.1 <- n
}
n
} |
predict.rocTree <- function(object, newdata, type = c("survival", "hazard"),
control = list(), ...) {
type <- match.arg(type)
if (!is.rocTree(object)) stop("Response must be a 'rocTree' object")
if (missing(newdata)) stop("Argument 'newdata' is missing")
if (!(object$rName %in% colnames(newdata)))
stop(paste("Object '", object$rName, "' not found.", sep = ""))
if (!all(object$vName %in% colnames(newdata))) {
missingName <- which(!(object$vName %in% colnames(newdata)))
if (length(missingName) == 1)
stop(paste("Object '", object$vName[missingName], "' not found.", sep = ""))
if (length(missingName) > 1)
stop(paste("Objects '", paste(object$vName[missingName], collapse = ", "),
"' not found.", sep = ""))
}
type <- match.arg(type)
control0 <- object$control
control0[names(control0) %in% names(control)] <- control[names(control) %in% names(control0)]
control <- control0
raw <- newdata[findInt(object$data$.Y0, unlist(newdata[object$rName])), object$vNames]
rownames(raw) <- NULL
cutoff <- (1:control$nc) / (control$nc + 1)
if (type %in% "survival") {
if (object$ensemble)
pred <- predict_rocForest_C(t(raw), object$data$.Y0, object$data$.D0, object,
object$data$.X, object$disc, cutoff)
else
pred <- predict_rocTree_C(t(raw), object$data$.Y0, object$data$.D0, object,
object$data$.X, object$disc, cutoff)
object$survFun <- stepfun(object$data$.Y0, c(1, pred))
object$pred <- data.frame(Time = unlist(newdata[,object$rName]),
Survival = object$survFun(unlist(newdata[,object$rName])))
}
if (type %in% "hazard") {
t0 <- unlist(newdata[,object$rName])
t0 <- seq(quantile(t0, .05), quantile(t0, .95), length.out = control$K)
knots <- findInt(t0, object$data$.Y0)
.mat1f2 <- sapply(t0, K2, vec = object$data$.Y0, h = control$h) / control$h
.mat1f2 <- .mat1f2[object$data$.D0 == 1,]
if (object$ensemble)
pred <- predict_rocForestHZ_C(t(raw[knots,]), t0,
object$data$.Y0, object$data$.D0, .mat1f2,
control$h, object, object$data$.X,
object$disc, cutoff)
else
pred <- predict_rocTreeHZ_C(t(raw[knots,]), t0,
object$data$.Y0, object$data$.D0, .mat1f2,
control$h, object, object$data$.X,
object$disc, cutoff)
object$hazFun <- stepfun(t0, c(1, pred))
object$pred <- data.frame(Time = t0, hazard = object$hazFun(t0))
}
rownames(object$pred) <- NULL
class(object) <- "predict.rocTree"
return(object)
}
is.predict.rocTree <- function(x) inherits(x, "predict.rocTree")
findInt <- function(x, y) {
pmax(1, findInterval(x, sort(y)))
}
findInt.X <- function(x, y) {
order(c(0, y))[pmax(1, findInterval(x, sort(c(0, y))))]
} |
sfaGetIntRange <- function (range){
if(length(range)==1){
int=1:range;
}else{
int=range[1]:range[2]
}
return(int)
}
customRep<-function(a,n){
res<-kronecker(array(1, c(n,1)), a)
return(res)
}
customRepmat <- function(a,n,m) {
res<-kronecker(matrix(1,n,m),a)
return(res)
}
customSize<-function(x,i=NULL){
if((class(x)=="numeric")||(class(x)=="vector")||(class(x)=="integer")){
res=c(1,length(x))
}
else{
res=dim(x)
}
if(is.null(i))return(res)
if(i==1)return(res[1])
if(i==2)return(res[2])
}
sfaCheckCondition <- function(matr, datatype){
ev=eigen(matr)
ev=sort(ev$values)
cn = abs(ev[length(ev)]/ev[1]);
if (cn > 1e10){
if (datatype=="input"){
warning("It is recommended to use sfaList$ppType = PCA2.
Covariance matrix of ", datatype," data is ill-conditioned.
CN=",paste(cn," "))
}
if (datatype=="expanded"){
warning("It is recommended to use method=SVDSFA in SFA-step.
Covariance matrix of ", datatype," data is ill-conditioned.
CN=",paste(cn," "))
}
}
}
sfaBSh<-function(X,Y){
X<-qr(X)
qr.coef(X,Y)
} |
input_multipliers_create <- function ( input_requirements,
inverse,
digits = NULL) {
names_direct <- names (input_requirements)
new_key_column <- input_requirements %>%
select (1:2) %>%
mutate(across(1, ~gsub(pattern ="_indicator",
replacement = "",
x =.data )) ) %>%
mutate(across(1, ~paste0(.data, "_multiplier")))
col_n <- ncol(input_requirements)
key_column <- subset ( input_requirements, select = 1)
input_requirements_matrix <- input_requirements[,-1]
inverse <- inverse[, -1]
inverse <- as.matrix ( inverse )
input_requirements_matrix <- as.matrix ( input_requirements_matrix )
effects <- input_requirements_matrix %*% inverse
multipliers <- effects
for ( i in seq_len(nrow(effects))) {
multipliers[i, ] <- effects[i, ] / input_requirements_matrix[i,]
}
if ( !is.null(digits) ) {
if ( digits>=0 )
multipliers <- round ( multipliers, digits )
}
cbind (new_key_column[,1], multipliers)
} |
library(ggsolvencyii)
context("fn_cornerpoints for a surfaceplot")
testdata <- sii_z_ex1_data
testdata_ggplotformat <- dplyr::rename(testdata, x = time, y = ratio, id = id, description = description , value = value )
testdata_ggplotformat <- dplyr::mutate(testdata_ggplotformat, group = id)
testparams <- NULL
testparams$structure = sii_structure_sf16_eng
testparams$levelmax <- sii_levelmax_sf16_993
testparams$aggregatesuffix <- "_other"
intresultA <- ggsolvencyii:::fn_structure_expansion(testparams)
intresultB <- ggsolvencyii:::fn_structure_data_integration(expandedstructure = intresultA, data = testdata_ggplotformat)
intresultB_group2 <- intresultB[intresultB$group == 2, ]
testparams$maxscrvalue <- ggsolvencyii:::fn_maxscrvalue(data = testdata_ggplotformat, params = testparams)
testparams$tocenter <- FALSE
testparams$plotdetails <- ggsolvencyii:::fn_constructionplotdetails(structure = testparams$structure)
testresultA <- ggsolvencyii:::fn_cornerpoints(df = intresultB_group2, siiparams = testparams)
testresultAa <- c("ri", "ro", "db" , "de") %in% colnames(testresultA)
testresultAa <- Reduce("==", testresultAa )
test_that("fn_cornerpoints" ,{
expect_equal( testresultAa, TRUE)
})
rm(testdata)
rm(testdata_ggplotformat)
rm(testparams)
rm(intresultA)
rm(intresultB)
rm(testresultA) |
print.grnnForecast <- function (x, ...) {
cat("\nCall: ",
paste(deparse(x$call),
sep = "\n",
collapse = "\n"
),
"\n\n",
sep = ""
)
cat("Multiple-Step Ahead Strategy:", x$msas, "\n")
cat("Sigma (smoothing parameter):", x$model$sigma, "\n")
cat("Autoregressive lags:", rev(x$model$lags), "\n")
cat("Number of examples:", nrow(x$model$examples$patterns), "\n")
invisible(x)
}
summary.grnnForecast <- function (object, ...) {
structure(
list(
call = object$call,
sigma = object$model$sigma,
msas = object$msas,
lags = rev(object$model$lags),
prediction = object$prediction,
transformation = object$transformation
),
class = "summary.grnnForecast"
)
}
print.summary.grnnForecast <- function (x, ...) {
stopifnot(inherits(x, "summary.grnnForecast"))
cat("\nCall: ",
paste(deparse(x$call),
sep = "\n",
collapse = "\n"
),
"\n\n",
sep = ""
)
cat("Multiple-Step Ahead Strategy:", x$msas, "\n")
cat("Sigma (smoothing parameter):", x$sigma, "\n")
cat("Autoregressive lags:", x$lags, "\n")
cat("Type of training samples transformation:", x$transformation, "\n")
cat("Forecasting horizon:", length(x$prediction), "\n")
cat("Forecast:\n")
print(x$prediction)
invisible(x)
} |
rSab_fc<-function(a,b,Sab0=NULL,eta0=NULL)
{
if(is.null(Sab0)){ Sab0<-diag(2) }
if(is.null(eta0)){ eta0<-4 }
solve(rwish(solve(eta0*Sab0+crossprod(cbind(a, b))), eta0+length(a)))
} |
context("user/properties")
test_that("we can get the properties of a user", {
testthat::skip_on_cran()
skip_unless_integration()
props <- rt_user_properties(1)
testthat::expect_is(props, "list")
testthat::expect_length(props, 6)
testthat::expect_true(props$Name == "RT_System")
})
test_that("we throw an error on user not found", {
testthat::skip_on_cran()
skip_unless_integration()
testthat::expect_error(
rt_user_properties(2), "does not exist")
}) |
library(fs)
test_that("test parameteriesed report output", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "parameterised.Rmd"),
path(f, "report_sources")
)
compile_reports(
"parameterised",
f,
params = list(test1 = "three", test2 = "four")
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "param_report_check.md", compare = compare_file_text)
})
test_that("test ignore_case works report output", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "parameterised.Rmd"),
path(f, "report_sources")
)
compile_reports(
"parameterised.rmd",
f,
ignore.case = TRUE,
params = list(test1 = "three", test2 = "four")
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "param_report_check.md", compare = compare_file_text)
expect_error(
compile_reports(
"parameterised.rmd",
f,
ignore.case = FALSE,
params = list(test1 = "three", test2 = "four")
)
)
})
test_that("test output folder gets recreated if not there", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
skip_on_os("mac")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "parameterised.Rmd"),
path(f, "report_sources")
)
file.remove(file.path(f, "outputs"))
compile_reports(
"parameterised",
f,
params = list(test1 = "three", test2 = "four")
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "outputs_deleted_param_report_check.md", compare = compare_file_text)
})
test_that("parameteriesed report with missing param output but input", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "parameterised_with_missing.Rmd"),
path(f, "report_sources")
)
compile_reports(
"parameterised",
f,
params = list(test2 = "four", test3 = "five")
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "missing_param_report_check.md", compare = compare_file_text)
})
test_that("non parameteriesed report with param input", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "simple2.Rmd"),
path(f, "report_sources")
)
compile_reports(
"simple",
f,
params = list(test2 = "four", test3 = "five")
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "nonparameterised_with_params.md", compare = compare_file_text)
})
test_that("parameteriesed report with missing param (but in environment)", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path("test_reports", "parameterised_with_missing.Rmd"),
path(f, "report_sources")
)
params = list(test2 = "four", test3 = "five")
compile_reports(
"parameterised",
f
)
md_file <- grep("\\.md", list_outputs(f), value = TRUE)
md_file <- path(f, "outputs", md_file)
expect_snapshot_file(md_file, "missing_param_but_envir.md", compare = compare_file_text)
})
test_that("integer index for reports", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path = c(
path("test_reports", "simple.Rmd"),
path("test_reports", "parameterised.Rmd")
),
path(f, "report_sources")
)
file_copy(
path("test_reports", "simple.Rmd"),
path(f, "report_sources", "dimple.Rmd")
)
file_delete(path(f, "report_sources", "example_report.Rmd"))
idx <- c(1, 3)
compile_reports(idx, f, timestamp = "test")
nms <- path_ext_remove(list_reports(f))[idx]
nms <- paste(nms, collapse = "|")
expected_files <- c(
file.path("simple", "test", "simple.Rmd"),
file.path("simple", "test", "simple.html"),
file.path("simple", "test", "simple.md"),
file.path("simple", "test", "simple_files", "figure-gfm", "pressure-1.png"),
file.path("dimple", "test", "dimple.Rmd"),
file.path("dimple", "test", "dimple.html"),
file.path("dimple", "test", "dimple.md"),
file.path("dimple", "test", "dimple_files", "figure-gfm", "pressure-1.png"),
file.path("parameterised", "test", "parameterised.Rmd"),
file.path("parameterised", "test", "parameterised.md")
)
expected_files <- expected_files[grepl(nms, expected_files)]
output_files <- list_outputs(f)
expect_true(all(
mapply(
grepl,
pattern = sort(expected_files),
x = sort(output_files),
MoreArgs = list(fixed = TRUE)
)
))
})
test_that("logical index for reports", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path = c(
path("test_reports", "simple.Rmd"),
path("test_reports", "parameterised.Rmd")
),
path(f, "report_sources")
)
file_copy(
path("test_reports", "simple.Rmd"),
path(f, "report_sources", "dimple.Rmd")
)
file_delete(path(f, "report_sources", "example_report.Rmd"))
idx <- c(TRUE, FALSE)
compile_reports(idx, f, timestamp = "test")
nms <- path_ext_remove(list_reports(f))[idx]
nms <- paste(nms, collapse = "|")
expected_files <- c(
file.path("simple", "test", "simple.Rmd"),
file.path("simple", "test", "simple.html"),
file.path("simple", "test", "simple.md"),
file.path("simple", "test", "simple_files", "figure-gfm", "pressure-1.png"),
file.path("dimple", "test", "dimple.Rmd"),
file.path("dimple", "test", "dimple.html"),
file.path("dimple", "test", "dimple.md"),
file.path("dimple", "test", "dimple_files", "figure-gfm", "pressure-1.png"),
file.path("parameterised", "test", "parameterised.Rmd"),
file.path("parameterised", "test", "parameterised.md")
)
expected_files <- expected_files[grepl(nms, expected_files)]
output_files <- list_outputs(f)
expect_true(all(
mapply(
grepl,
pattern = sort(expected_files),
x = sort(output_files),
MoreArgs = list(fixed = TRUE)
)
))
})
test_that("figures folders copied correctly reports", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_copy(
path = path("test_reports", "simple_with_figures_folder.Rmd"),
path(f, "report_sources")
)
file_delete(path(f, "report_sources", "example_report.Rmd"))
compile_reports(factory = f, timestamp = "test")
nms <- path_ext_remove(list_reports(f))
nms <- paste(nms, collapse = "|")
expected_files <- c(
file.path("simple_with_figures_folder", "test", "simple_with_figures_folder.Rmd"),
file.path("simple_with_figures_folder", "test", "simple_with_figures_folder.html"),
file.path("simple_with_figures_folder", "test", "figures", "pressure-1.png")
)
expected_files <- expected_files[grepl(nms, expected_files)]
output_files <- list_outputs(f)
expect_true(all(
mapply(
grepl,
pattern = sort(expected_files),
x = sort(output_files),
MoreArgs = list(fixed = TRUE)
)
))
})
test_that("compiling with no reports errors correctly", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
file_delete(path(f, "report_sources", "example_report.Rmd"))
expect_error(
compile_reports(factory = f),
"No reports found in",
fixed = TRUE
)
})
test_that("compiling with invalid index errors correctly", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
expect_error(
compile_reports(2, factory = f),
"Unable to match reports with the given index",
fixed = TRUE
)
})
test_that("compiling with incorrect report name errors correctly", {
skip_if_pandoc_not_installed()
skip_on_os("windows")
f <- new_factory(path = path_temp(), move_in = FALSE)
on.exit(dir_delete(f))
expect_error(
compile_reports("test", factory = f),
"Unable to find matching reports to compile",
fixed = TRUE
)
}) |
context("Test: download.database()")
test_that("The download.database() throws error when wrong input
database is specified..",{
skip_on_cran()
skip_on_travis()
expect_error(download.database(db = "nr"))
}) |
rmpg <- function(dataset,
ipuc = "ipuc",
hhcsw = "DB090",
hhsize = "HX040",
arpt.value = NULL, ci = NULL, rep = 1000, verbose = FALSE){
if(is.null(arpt.value)) arpt.value <- arpt(dataset, ipuc, hhcsw, hhsize)
dataset <- dataset[order(dataset[,ipuc]),]
if(is.null(ci)){
rmpg.data <- dataset[which(dataset[,ipuc] < arpt.value),]
rmpg.data$weights.rmpg <- rmpg.data[,hhcsw]*rmpg.data[,hhsize]
rmpg.data$acum.weights.rmpg <- cumsum(rmpg.data$weights.rmpg)
rmpg.data$abscisa.rmpg <-
rmpg.data$acum.weights.rmpg/rmpg.data$acum.weights.rmpg[length(rmpg.data$acum.weights.rmpg)]
rmpg.median <- rmpg.data[which(rmpg.data$abscisa.rmpg > 0.5)[1],ipuc]
rmpg <- 100*(arpt.value-rmpg.median)/arpt.value
return(rmpg)
}else{
rmpg3 <- function(dataset, i, arpt.value){
dataset.boot <- dataset[i,]
dataset.boot <- dataset.boot[order(dataset.boot[,ipuc]), ]
rmpg.data <- dataset.boot[which(dataset.boot[,ipuc] < arpt.value),]
rmpg.data$weights.rmpg <- rmpg.data[,hhcsw]*rmpg.data[,hhsize]
rmpg.data$acum.weights.rmpg <- cumsum(rmpg.data$weights.rmpg)
rmpg.data$abscisa.rmpg <-
rmpg.data$acum.weights.rmpg/rmpg.data$acum.weights.rmpg[length(rmpg.data$acum.weights.rmpg)]
rmpg.median <- rmpg.data[which(rmpg.data$abscisa.rmpg > 0.5)[1],ipuc]
100*(arpt.value-rmpg.median)/arpt.value
}
boot.rmpg <- boot::boot(dataset, statistic = rmpg3, R = rep,
sim = "ordinary", stype = "i", arpt.value = arpt.value)
rmpg.ci <- boot::boot.ci(boot.rmpg, conf = ci, type = "basic")
if(verbose == FALSE){
return(rmpg.ci)
}else{
plot(boot.rmpg)
summary(rmpg.ci)
return(rmpg.ci)
}
}
} |
gof <- function(obs, fit, methods=c("FT"), p.out=FALSE){
retvals <- list()
if("FT" %in% methods){
ftres <- ft.res(obs, fit, p.out=p.out)
retvals <- c(retvals, list(ft.res=ftres))
}
if("KL" %in% methods){
kl <- kl.divergence(obs, fit) + kl.divergence(fit, obs)
retvals <- c(retvals, list(kl.div=kl))
}
if("Chisq" %in% methods){
chisq <- chisq.test(obs, fit)
chisq <- list(statistic=chisq$stat, df=chisq$parameter, p.value=chisq$p.value)
retvals <- c(retvals, list(chisq=chisq))
}
retvals$methods <- methods
class(retvals) <- "snse.gof"
retvals
}
print.snse.gof <- function(x, ...){
if("FT" %in% x$methods){
cat("Freeman-Tukey Residuals:\n")
cat("------------------------\n")
print(x$ft.res)
cat("\n")
}
if("KL" %in% x$methods){
cat("Symmetrised Kullback-Leibler divergence:\n")
cat("----------------------------------------\n")
print(x$kl.div)
cat("\n")
}
if("Chisq" %in% x$methods){
cat("Pearson's Chi-squared Test:\n")
cat("---------------------------\n")
cat("H0: The data is consistent with the specified distribution\n\n")
cat(paste0("X-squared = ",x$chisq$stat, ", df = ",x$chisq$df, ", p-value = ",round(x$chisq$p.value, 3)))
cat("\n")
}
}
ft.res <- function(obs, fit, p.out=TRUE){
FT <- as.numeric(sqrt(obs) + sqrt(obs+1) - sqrt(4*fit+1))
if(p.out){
par(mfrow=c(1,1))
qqnorm(FT, main="Freeman-Tukey Residuals QQPlot")
qqline(FT, col=2)
}
return(FT)
}
kl.divergence <- function(p, q){
pn <- p / sum(p)
qn <- q / sum(q)
return( sum(pn*(log(pn) - log(qn))) )
} |
require(chillR)
daylength(latitude=50.4,JDay=15)
all_daylengths<-cbind(JDay=1:365,sapply(daylength(latitude=50.5,JDay=1:365),cbind))
knitr::kable(head(all_daylengths))
weather<-make_all_day_table(KA_weather)
hourtemps<-stack_hourly_temps(weather, latitude=50.4)$hourtemps
hourtemps$DATE<-ISOdate(hourtemps$Year,hourtemps$Month,hourtemps$Day,hourtemps$Hour)
knitr::kable(hourtemps[20:30,],row.names = FALSE)
par(mar=c(5,5,1,1))
plot(hourtemps$Temp[10:250]~hourtemps$DATE[10:250],type="l",col="red",lwd=3,
xlab="Date",ylab="Temperature (°C)",xaxs="i")
KA_weather_gaps<-KA_weather[1:100,]
KA_weather_gaps[,"Tmin_original"]<-KA_weather_gaps[,"Tmin"]
KA_weather_gaps[,"Tmax_original"]<-KA_weather_gaps[,"Tmax"]
KA_weather_gaps$Tmin[c(4:15,20:30,35:40,44:45,48,50:60)]<-NA
KA_weather_gaps$Tmax[c(3:10,12:15,17:20,30:35,42:60,65:70)]<-NA
fixed<-fix_weather(KA_weather_gaps)
par(mar=c(5,5,1,1))
plot(fixed$weather$Tmin_original~fixed$weather$DATE,type="l",lwd=4,col="blue",
ylim=c(min(fixed$weather[,c("Tmin","Tmin_original")],na.rm=TRUE),
max(fixed$weather[,c("Tmax","Tmax_original")],na.rm=TRUE)),xaxs="i",
xlab="Date",ylab="Temperature (°C)")
lines(fixed$weather$Tmax_original~fixed$weather$DATE,type="l",lwd=4,col="red")
lines(fixed$weather$Tmin~fixed$weather$DATE,type="l",lwd=2)
lines(fixed$weather$Tmax~fixed$weather$DATE,type="l",lwd=2)
stations<-read.csv("KA_stations.csv")
knitr::kable(stations[1:10,c(1:2,4:5,8)])
patch_weather<-read.csv("KA_patch.csv")
knitr::kable(patch_weather[1:5,])
patched_weather<-patch_daily_temperatures(KA_weather_gaps,patch_weather)
knitr::kable(patched_weather$statistics)
par(mar=c(5,5,0,0))
plot(fixed$weather$Tmin_original~fixed$weather$DATE,type="l",lwd=4,col="blue",
ylim=c(min(fixed$weather[,c("Tmin","Tmin_original")],na.rm=TRUE),
max(fixed$weather[,c("Tmax","Tmax_original")],na.rm=TRUE)),xaxs="i",
xlab="Date",ylab="Temperature (°C)")
lines(fixed$weather$Tmax_original~fixed$weather$DATE,type="l",lwd=4,col="red")
lines(patched_weather$weather$Tmin~fixed$weather$DATE,type="l",lwd=2)
lines(patched_weather$weather$Tmax~fixed$weather$DATE,type="l",lwd=2)
Winters_hours_gaps[,"DATE"]<-ISOdate(Winters_hours_gaps$Year,Winters_hours_gaps$Month,Winters_hours_gaps$Day,Winters_hours_gaps$Hour)
par(mar=c(5,5,1,1))
plot(Winters_hours_gaps$Temp[50:300]~Winters_hours_gaps$DATE[50:300],type="l",
lwd=2,col="dark grey",xaxs="i",xlab="Date",ylab="Temperature (°C)")
lines(interpolate_gaps(Winters_hours_gaps$Temp_gaps)$interp[50:300]~Winters_hours_gaps$DATE[50:300],col="red",lwd=2)
lines(Winters_hours_gaps$Temp_gaps[50:300]~Winters_hours_gaps$DATE[50:300],type="l",lwd=2)
winters_daily<-read.csv("winters_daily.csv")
knitr::kable(winters_daily[1:5,])
to_interp<-Winters_hours_gaps
to_interp[,"Temp_recorded"]<-to_interp[,"Temp"]
to_interp[,"Temp"]<-to_interp[,"Temp_gaps"]
interp<-interpolate_gaps_hourly(hourtemps=to_interp,latitude=38.5,
daily_temps=list(Winters=winters_daily))
knitr::kable(interp$daily_patch_report,row.names = FALSE,align="r")
knitr::kable(interp$weather[30:45,c(1:5,10)],row.names = FALSE,
align=c("r","r","r","r","r","r"))
inter<-interp$weather
inter[,"DATE"]<-ISOdate(inter$Year,inter$Month,inter$Day,inter$Hour)
par(mar=c(5,5,1,1))
plot(inter$Temp_recorded[50:300]~inter$DATE[50:300],type="l",
lwd=2,col="dark grey",xaxs="i",xlab="Date",ylab="Temperature (°C)")
lines(inter$Temp[50:300]~inter$DATE[50:300],col="red",lwd=2)
lines(inter$Temp_gaps[50:300]~inter$DATE[50:300],type="l",lwd=2)
require(stats)
y<-rnorm(100)
IQ<-quantile(y)[4]-quantile(2)[2]
orchard_extremes<-make_all_day_table(inter,timestep="day",
input_timestep = "hour")
winters_hours<-stack_hourly_temps(fix_weather(winters_daily),latitude=38)$hourtemps
start_hour_winters<-which(winters_hours$Year==inter$Year[1]&
winters_hours$Month==inter$Month[1]&
winters_hours$Day==inter$Day[1]&
winters_hours$Hour==inter$Hour[1])
end_hour_winters<-which(winters_hours$Year==inter$Year[nrow(inter)]&
winters_hours$Month==inter$Month[nrow(inter)]&
winters_hours$Day==inter$Day[nrow(inter)]&
winters_hours$Hour==inter$Hour[nrow(inter)])
orchard_hours<-stack_hourly_temps(orchard_extremes,latitude=38)$hourtemps
start_hour_orchard<-which(orchard_hours$Year==inter$Year[1]&
orchard_hours$Month==inter$Month[1]&
orchard_hours$Day==inter$Day[1]&
orchard_hours$Hour==inter$Hour[1])
end_hour_orchard<-which(orchard_hours$Year==inter$Year[nrow(inter)]&
orchard_hours$Month==inter$Month[nrow(inter)]&
orchard_hours$Day==inter$Day[nrow(inter)]&
orchard_hours$Hour==inter$Hour[nrow(inter)])
observed<-inter$Temp_recorded
option1<-winters_hours$Temp[start_hour_winters:end_hour_winters]
option2<-orchard_hours$Temp[start_hour_orchard:end_hour_orchard]
option3<-interpolate_gaps(inter$Temp_gaps)$interp
option4<-inter$Temp
eval_table<-eval_table_gaps<-data.frame(Option=1:4,
Input_data=c("daily","daily","hourly","hourly"),
Interpolation_method=c("from proxy","local extremes",
"linear","hourly interpolation"),
RMSEP=NA,RPIQ=NA)
observed_gaps<-observed[which(is.na(inter$Temp_gaps))]
option1_gaps<-option1[which(is.na(inter$Temp_gaps))]
option2_gaps<-option2[which(is.na(inter$Temp_gaps))]
option3_gaps<-option3[which(is.na(inter$Temp_gaps))]
option4_gaps<-option4[which(is.na(inter$Temp_gaps))]
eval_table_gaps[,"RMSEP"]<-round(c(RMSEP(option1_gaps,observed_gaps),
RMSEP(option2_gaps,observed_gaps),
RMSEP(option3_gaps,observed_gaps),
RMSEP(option4_gaps,observed_gaps)),1)
eval_table_gaps[,"RPIQ"]<-round(c(RPIQ(option1_gaps,observed_gaps),
RPIQ(option2_gaps,observed_gaps),
RPIQ(option3_gaps,observed_gaps),
RPIQ(option4_gaps,observed_gaps)),1)
knitr::kable(eval_table_gaps,row.names = FALSE)
eval_table<-data.frame(Option=1:4,
Input_data=c("daily","daily","hourly","hourly"),
Interpolation_method=c("from proxy","local extremes",
"linear","hourly interpolation"),
RMSEP=NA,RPIQ=NA)
eval_table[,"RMSEP"]<-round(c(RMSEP(option1,observed),RMSEP(option2,observed),
RMSEP(option3,observed),RMSEP(option4,observed)),1)
eval_table[,"RPIQ"]<-round(c(RPIQ(option1,observed),RPIQ(option2,observed),
RPIQ(option3,observed),RPIQ(option4,observed)),1)
knitr::kable(eval_table,row.names = FALSE)
option1_chill<-Dynamic_Model(option1)
option2_chill<-Dynamic_Model(option2)
option3_chill<-Dynamic_Model(option3)
option4_chill<-Dynamic_Model(option4)
observed_chill<-Dynamic_Model(observed)
plot(observed_chill~inter$DATE,type="l",lwd=2,col="black",ylab="Chill Portions (cumulative)",
xlab="Date",ylim=c(0,max(c(option1_chill,option2_chill,
option3_chill,option4_chill,
observed_chill))),xaxs="i")
lines(option1_chill~inter$DATE,type="l",lwd=2,col="orange")
lines(option2_chill~inter$DATE,type="l",lwd=2,col="red")
lines(option3_chill~inter$DATE,type="l",lwd=2,col="green")
lines(option4_chill~inter$DATE,type="l",lwd=2,col="blue")
mtext("Observed temperatures",3,adj=0.02,line=-0.8, cex=0.8,
col="black")
mtext("Option 1 - idealized record from proxy data",3,adj=0.02,
line=-1.6, cex=0.8,col="orange")
mtext("Option 2 - idealized record from daily orchard data",3,adj=0.02,
line=-2.4, cex=0.8,col="red")
mtext("Option 3 - linear interpolation of hourly data",3,adj=0.02,
line=-3.2, cex=0.8,col="green")
mtext("Option 4 - use of interpolate_gaps_hourly",3,adj=0.02,
line=-4, cex=0.8,col="blue")
option1_heat<-GDH(option1)
option2_heat<-GDH(option2)
option3_heat<-GDH(option3)
option4_heat<-GDH(option4)
observed_heat<-GDH(observed)
plot(observed_heat~inter$DATE,type="l",lwd=2,col="black",ylab="Growing Degree Hours (cumulative)",
xlab="Date",ylim=c(0,max(c(option1_heat,option2_heat,
option3_heat,option4_heat,
observed_heat))),xaxs="i")
lines(option1_heat~inter$DATE,type="l",lwd=2,col="orange")
lines(option2_heat~inter$DATE,type="l",lwd=2,col="red")
lines(option3_heat~inter$DATE,type="l",lwd=2,col="green")
lines(option4_heat~inter$DATE,type="l",lwd=2,col="blue")
mtext("Observed temperatures",3,adj=0.02,line=-0.8, cex=0.8,
col="black")
mtext("Option 1 - idealized record from proxy data",3,adj=0.02,
line=-1.6, cex=0.8,col="orange")
mtext("Option 2 - idealized record from daily orchard data",3,adj=0.02,
line=-2.4, cex=0.8,col="red")
mtext("Option 3 - linear interpolation of hourly data",3,adj=0.02,
line=-3.2, cex=0.8,col="green")
mtext("Option 4 - use of interpolate_gaps_hourly",3,adj=0.02,
line=-4, cex=0.8,col="blue")
chill_heat_eval<-rbind(data.frame(Option=0,Input_data="observed",
Interpolation_method="none"),eval_table[,1:3])
chill_heat_eval[,"Chill Portions"]<-round(c(observed_chill[length(observed)],
option1_chill[length(option1)],
option2_chill[length(option2)],
option3_chill[length(option3)],
option4_chill[length(option4)]),1)
chill_heat_eval[,"Growing Degree Hours"]<-
round(c(observed_heat[length(observed)],
option1_heat[length(option1)],
option2_heat[length(option2)],
option3_heat[length(option3)],
option4_heat[length(option4)]),0)
knitr::kable(chill_heat_eval,row.names = FALSE) |
dropZLB <- function(tree){
if(!inherits(tree,"phylo")){
stop("tree must be of class 'phylo'")
}
drop_e <- (tree$edge[,2]<(Ntip(tree)+1)) & (tree$edge.length == 0)
drop_t <- (tree$edge[,2])[drop_e]
if((Ntip(tree)-length(drop_t))>1){
tree1 <- drop.tip(tree,drop_t)
if(!is.null(tree$root.time)){
tree1 <- fixRootTime(treeOrig = tree, treeNew = tree1)
}
res <- tree1
}else{
res <- NA
}
return(res)
}
dropExtinct <- function(tree,
tol = 0.01,
ignore.root.time = FALSE
){
if(!inherits(tree,"phylo")){
stop("tree must be of class 'phylo'")
}
if(is.null(tree$root.time)){
message("No tree$root.time: Assuming latest tip is at present (time = 0)")
}
dnode <- node.depth.edgelength(tree)[1:Ntip(tree)]
dnode <- round(dnode,6)
if(!is.null(tree$root.time) & !ignore.root.time){
if(round(tree$root.time,6)>max(dnode)){
stop("all tips are extinct based on tree$root.time!")
}
}
droppers <- which((dnode+tol)<max(dnode))
if((Ntip(tree)-length(droppers))<2){
stop("Less than 2 tips are extant on the tree!")
}
stree <- drop.tip(tree,droppers)
if(!is.null(tree$root.time)){
stree <- fixRootTime(treeOrig = tree, treeNew = stree)
}
return(stree)
}
dropExtant <- function(tree,tol = 0.01){
if(!inherits(tree,"phylo")){
stop("tree must be of class 'phylo'")
}
if(is.null(tree$root.time)){
message("Warning: no tree$root.time! Assuming latest tip is at present (time = 0)")
}
dnode <- node.depth.edgelength(tree)[1:Ntip(tree)]
dnode <- round(dnode,6)
if(!is.null(tree$root.time)){if(round(tree$root.time,6)>max(dnode)){stop("all tips are extinct based on tree$root.time!")}}
droppers <- which((dnode+tol)>max(dnode))
if((Ntip(tree)-length(droppers))<2){stop("Less than 2 tips extinct on the tree!")}
stree <- drop.tip(tree,droppers)
if(!is.null(tree$root.time)){
stree <- fixRootTime(treeOrig = tree, treeNew = stree)
}
return(stree)
}
addTermBranchLength <- function(tree,addtime = 0.001){
if(!inherits(tree,"phylo")){
stop("tree must be of class 'phylo'")
}
branchSel <- tree$edge[,2]<(Ntip(tree)+1)
newBrLen <- tree$edge.length[branchSel]+addtime
tree$edge.length[newBrLen] <- newBrLen
if(any(tree$edge.length<0)){
stop("tree has negative branch lengths!")
}
if(!is.null(tree$root.time)){
tree$root.time <- tree$root.time + addtime
}
return(tree)
}
dropPaleoTip <- function(tree, ...){
tree1 <- drop.tip(phy = tree, ...)
tree1 <- fixRootTime(treeOrig = tree, treeNew = tree1)
return(tree1)
}
bindPaleoTip <- function(tree, tipLabel, nodeAttach = NULL, tipAge = NULL,
edgeLength = NULL, positionBelow = 0, noNegativeEdgeLength = TRUE){
tipLabel <- as.character(tipLabel)
if(!is.character(tipLabel)){
stop("cannot coerce tipLabel to a string value")
}
if(length(tipLabel) != 1){
stop("A string of length = 1 is needed for tipLabel (i.e. for a single tip) is required")
}
if(positionBelow<0){
stop("bindTipPaleo does not accept negative positionBelow values")
}
if(nodeAttach == (Ntip(tree)+1)){
if(positionBelow>0){
if(is.null(tree$root.edge)){
tree$root.edge <- positionBelow
}else{
if(tree$root.edge<positionBelow){
tree$root.edge <- positionBelow
}
}
}
}else{
if(positionBelow>tree$edge.length[tree$edge[,2] == nodeAttach]){
stop(
"positionBelow cannot be greater than the $edge.length of the edge below nodeAttach"
)
}
}
if(is.null(tree$root.time)){
warning(
"No tree$root.time given; Setting root.time such that latest tip is at present (time = 0)"
)
tree$root.time <- max(node.depth.edgelength(tree))
}
if(is.null(tree$edge.length)){
stop("bindTipPaleo is for trees with edge lengths")
}
if(is.null(edgeLength)){
if(!is.null(tipAge)){
nodeHeight <- node.depth.edgelength(tree)[nodeAttach]
modNodeHeight <- nodeHeight-positionBelow
newLength <- tree$root.time-tipAge-modNodeHeight
if(newLength<0){
if(noNegativeEdgeLength){
stop(paste0("Negative edge length created due to tipAge being",
" older than age of nodeAttach + positionBelow"))
}else{
message(paste0("Warning: negative edge length created due to tipAge being",
" older than age of nodeAttach + positionBelow"))
}
}
}else{
stop("either tipAge or edgeLength must be given")
}
}else{
if(!is.null(tipAge)){
stop("both tipAge or edgeLength cannot be given")
}
newLength <- edgeLength
if(newLength<0 & noNegativeEdgeLength){
stop("Negative edgeLength given ?!")
}
}
tree1 <- bind.tip(tree,
tip.label = tipLabel,
where = nodeAttach,
position = positionBelow,
edge.length = newLength
)
if(nodeAttach == (Ntip(tree)+1) & positionBelow>0){
tree1$root.time <- tree1$root.time + positionBelow
}
if(!is.null(tree1$root.edge)){
if(tree1$root.edge == 0){tree1$root.edge <- NULL}
}
return(tree1)
} |
sigtestCI <- function(p) {
if (runif(1) < (1 - p)) {
cat("H0 NOT rejected\n")
cat(100 * (1 - p), "% conf. int.: empty set\n")
} else {
cat("Hurray!!! H0 REJECTED!!!\n")
cat(100 * (1 - p), paste("% conf. int.: -",
expression(infinity), "to +", expression(infinity),
"\n"))
}
} |
skewnessTest <- function(object, test = "agostino") {
if (! inherits(object,"sfacross")) {
stop("Argument 'object' must be of class 'sfacross'")
}
if (test == "agostino") {
object$AgostinoTest
} else {
if (test == "coelli") {
tt=list("data.name" = deparse(substitute(object)),
"statistic" = object$CoelliM3Test["z"],
"p.value" = object$CoelliM3Test["p.value"],
"method" = "
class(tt) <- "htest"
return(tt)
} else {
stop("argument 'test' must be either 'agostino', or 'coelli'",
call. = FALSE)
}
}
}
|
library("leiden")
library("reticulate")
library("igraph")
context("running Leiden on an igraph object")
set.seed(9000)
adj_mat <- matrix(round(runif(10000, 0, 1)), 100, 100)
snn_graph <- graph_from_adjacency_matrix(adj_mat)
modules <- reticulate::py_module_available("leidenalg") && reticulate::py_module_available("igraph")
skip_if_no_python <- function() {
if (!modules)
testthat::skip("leidenalg not available for testing")
}
test_that("run with defaults", {
skip_if_no_python()
partition <- leiden(snn_graph)
expect_length(partition, 100)
})
test_that("run with ModularityVertexPartition", {
skip_if_no_python()
partition <- leiden(snn_graph, partition_type = "ModularityVertexPartition")
expect_length(partition, 100)
})
test_that("run with resolution parameter", {
skip_if_no_python()
partition <- leiden(snn_graph, resolution_parameter = 0.95)
expect_length(partition, 100)
})
test_that("run with max_comm_size", {
skip_if_no_python()
partition <- leiden(snn_graph,
partition_type = "ModularityVertexPartition",
resolution_parameter = 0.2,
max_comm_size = 8,
degree_as_node_size = TRUE,
seed = 9001)
expect_length(partition, length(V(snn_graph)))
expect_equal(sort(unique(partition)), 1:13)
expect_equal(max(table(partition)), 8)
})
test_that("run on igraph object with random seed", {
skip_if_no_python()
partition <- leiden(snn_graph, seed = 42L, weights = NULL)
expect_length(partition, 100)
expect_identical(leiden(snn_graph, seed = 42L, weights = NULL),
leiden(snn_graph, seed = 42L, weights = NULL))
})
weights <- sample(1:10, sum(adj_mat!=0), replace=TRUE)
test_that("run with non-wieghted igraph object and weights vector", {
skip_if_no_python()
partition <- leiden(snn_graph, weights = weights)
expect_length(partition, 100)
})
adj_mat <- ifelse(adj_mat == 1, weights, 0)
snn_graph <- graph_from_adjacency_matrix(adj_mat, weighted = TRUE)
test_that("run with wieghted igraph object", {
skip_if_no_python()
partition <- leiden(snn_graph)
expect_length(partition, 100)
})
rownames(adj_mat) <- 1:nrow(adj_mat)
colnames(adj_mat) <- 1:ncol(adj_mat)
test_that("run with named adjacency matrix", {
skip_if_no_python()
partition <- leiden(snn_graph)
expect_length(partition, 100)
}) |
NULL
daFisher <- function(x, grp, coda=TRUE,
method = "classical",
plotScore = FALSE, ...){
clInfo <- class(x)[1]
if(clInfo == "data.frame") x <- as.matrix(x)
if(length(grp) != dim(x)[1]){
stop(paste("grp must be of length", dim(x)[1]))
}
if(dim(x)[2] < 1){
stop("matrix or data.frame expected.")
}
if(coda){
x <- pivotCoord(x)
}
n <- nrow(x)
p <- ncol(x)
grp <- as.factor(grp)
glev <- levels(grp)
g <- length(glev)
pj <- rep(NA,g)
meanj <- matrix(NA,nrow=p,ncol=g)
cv <- list()
for (j in 1:g){
pj[j] <- sum(grp==glev[j])/n
if(method == "classical"){
meanj[,j] <- apply(x[grp==glev[j],],2,mean)
cv[[j]] <- cov(x[grp==glev[j],])
} else {
robcov <- covMcd(x[grp==glev[j],])
meanj[,j] <- robcov$center
cv[[j]] <- robcov$cov
}
}
meanov <- meanj%*%pj
B <- matrix(0,p,p)
W <- matrix(0,p,p)
for (j in 1:g){
B <- B+pj[j]*((meanj-meanov%*%rep(1,g))%*%t(meanj-meanov%*%rep(1,g)))
W <- W+pj[j]*cv[[j]]
}
l <- min(g-1,p)
B.svd <- svd(B)
l1 <- length(B.svd$d>1e-6)
B12 <- B.svd$u[, 1:l1] %*% diag(sqrt(B.svd$d[1:l1])) %*% t(B.svd$u[, 1:l1])
Bm12 <- B.svd$u[, 1:l1] %*% diag(1/sqrt(B.svd$d[1:l1])) %*% t(B.svd$u[, 1:l1])
K <- eigen(B12 %*% solve(W) %*% t(B12))
l2 <- min(g - 1, p)
l <- min(length(K$val>1e-6),l2)
Vs <- Bm12%*%K$vec[,1:l]
V <- t(t(Vs)/(sqrt(diag(t(Vs)%*%W%*%Vs))))
fs <- matrix(NA,nrow=n,ncol=g)
dimnames(fs)[[2]] <- glev
for (j in 1:g){
xc <- scale(x,meanj[,j],scale=FALSE)
xproj <- xc%*%V
fs[,j] <- sqrt(apply(xproj^2,1,sum)-2*log(pj[j]))
}
grppred <- glev[apply(fs, 1, which.min)]
mc <- table(grp, grppred)
mc <- mc[, matchClasses(mc, method = "exact")]
rate <- 1 - sum(diag(mc)) / sum(mc)
fdiscr <- scale(x,meanov,FALSE)%*%V[,1:2]
if(plotScore){
proj <- data.frame(fdiscr)
proj$grp <- as.factor(grp)
proj$grppred <- as.factor(grppred)
firstscores <- NULL
secondscores <- NULL
colnames(proj) <- c("firstscores", "secondscores","grp", "grppred")
gg <- ggplot(proj, aes(firstscores, secondscores, colour = grp, shape = grppred))
gg <- gg + geom_point()
gg <- gg + xlab("First Fisher scores") + ylab("Second Fisher scores")
print(gg)
}
res <- list(B = B, W = W, loadings = V, scores = fs, mc = mc, mcrate = rate,
coda=coda, grp=grp, grppred=grppred, xc=xc, meanj=meanj, cv=cv,
pj=pj, meanov=meanov, fdiscr = fdiscr)
class(res) <- "daFisher"
res
}
print.daFisher <- function(x,...){
cat("--------------------------------------")
cat("\nResults from Fishers discriminant analysis, coda ==", x$coda)
cat("\n- Variance between the classes: \n")
print(x$B)
cat("\n- Variance within the classes: \n")
print(x$W)
cat("\n- Loadings matrix: \n")
print(x$load)
cat("--------------------------------------\n")
}
predict.daFisher <- function(object, ..., newdata){
g <- ncol(object$meanj)
if (object$coda){
newdata <- pivotCoord(newdata)
}
fs <- matrix(NA,nrow=nrow(newdata),ncol=g)
dimnames(fs)[[2]] <- dimnames(object$mc)[[1]]
for (j in 1:g){
xc <- scale(newdata,object$meanj[,j],scale=FALSE)
xproj <- xc%*%object$loadings
fs[,j] <- sqrt(apply(xproj^2,1,sum)-2*log(object$pj[j]))
}
grp <- apply(fs, 1, which.min)
grpnam <- colnames(fs)[grp]
list(grpnam=grpnam,grp=grp)
}
summary.daFisher <- function(object, ...){
cat("--------------------------------------")
cat("\nMisclassification rate from Fishers discriminant analysis, coda ==", object$coda)
cat("\n")
print(object$mcrate)
cat("\n--------------------------------------")
cat("\nMisclassifications from Fishers discriminant analysis, coda ==", object$coda)
cat("\n")
print(object$mc)
cat("\n--------------------------------------\n")
} |
markerSimParametric = function(kappa = NULL, delta = NULL, states = NULL,
N = 1, alleles = NULL, afreq = NULL, seed = NULL,
returnValue = c("singletons", "alleles", "genotypes", "internal")) {
if(!is.null(seed))
set.seed(seed)
afreq = fixAllelesAndFreqs(alleles, afreq)
alleles = names(afreq)
.a = sample(alleles, size = N, replace = TRUE, prob = afreq)
.b = sample(alleles, size = N, replace = TRUE, prob = afreq)
.c = sample(alleles, size = N, replace = TRUE, prob = afreq)
.d = sample(alleles, size = N, replace = TRUE, prob = afreq)
useKappa = !is.null(kappa)
useDelta = !is.null(delta)
useStates = !is.null(states)
if(useKappa + useDelta + useStates != 1)
stop2("Exactly one of `kappa`, `delta`, `states` must be different from NULL")
if(useKappa)
states = sample(9:7, size = N, replace = TRUE, prob = kappa)
else if(useDelta)
states = sample(1:9, size = N, replace = TRUE, prob = delta)
else if(length(states) == 1)
states = rep_len(states, N)
else if(length(states) != N)
stop2("`states` must have length 1 or ", N)
S1 = states == 1
.b[S1] = .c[S1] = .d[S1] = .a[S1]
S2 = states == 2
.b[S2] = .a[S2]
.d[S2] = .c[S2]
S3 = states == 3
.b[S3] = .c[S3] = .a[S3]
S4 = states == 4
.b[S4] = .a[S4]
S5 = states == 5
.c[S5] = .d[S5] = .a[S5]
S6 = states == 6
.d[S6] = .c[S6]
S7 = states == 7
.c[S7] = .a[S7]
.d[S7] = .b[S7]
S8 = states == 8
.c[S8] = .a[S8]
switch(match.arg(returnValue),
singletons = setMarkers(x = list(singleton(1), singleton(2)),
alleleMatrix = matrix(rbind(.a, .c, .b, .d), nrow = 2,
dimnames = list(1:2, NULL)),
locusAttributes = list(afreq = afreq)),
genotypes = list(paste(.a, .b, sep="/"), paste(.c, .d, sep="/")),
alleles = list(a = .a, b = .b, c = .c, d = .d),
internal = list(a = match(.a, alleles), b = match(.b, alleles),
c = match(.c, alleles), d = match(.d, alleles)))
}
profileSimParametric = function(kappa = NULL, delta = NULL, states = NULL,
N = 1, freqList = NULL, seed = NULL,
returnValue = c("singletons", "alleles", "genotypes", "internal")) {
if(!is.null(seed))
set.seed(seed)
returnValue = match.arg(returnValue)
retval0 = if(returnValue %in% c("singletons", "genotypes")) "alleles" else returnValue
sims_markerwise = lapply(seq_along(freqList), function(i) {
markeri = markerSimParametric(kappa = kappa, delta = delta, states = states[i],
N = N, afreq = freqList[[i]], returnValue = retval0)
do.call(rbind, markeri)
})
sims = lapply(1:N, function(i)
vapply(sims_markerwise, function(locsim) locsim[, i],
FUN.VALUE = if(returnValue == "internal") integer(4) else character(4)))
switch(returnValue,
singletons = lapply(sims, function(s)
setMarkers(list(singleton(1), singleton(2)),
alleleMatrix = matrix(s[c(1,3,2,4), ], nrow = 2, dimnames = list(1:2, NULL)),
locusAttributes = freqList)),
genotypes = lapply(sims, function(s) list(paste(s[1,], s[2,], sep = "/"),
paste(s[3,], s[4,], sep = "/"))),
alleles =,
internal = lapply(sims, function(s) list(a = s[1,], b = s[2,], c = s[3,], d = s[4,])))
} |
context("test-assign_directory")
test_that("canAssignDirectory", {
tdata <- system.file("testdata", "test_dllist.Rdata", package = "binman")
load(tdata)
expect_silent(assign_directory(test_dllist, "myapp"))
}) |
set.lcgseed <-
function(seed = 4711)
{
setRmetricsOptions(lcg.seed = seed)
}
get.lcgseed <-
function()
{
getRmetricsOptions("lcg.seed")
}
runif.lcg <-
function(n, min = 0, max = 1)
{
r.lcg = rep(0, times = n)
a = 13445
c = 0
m = 2^31-1
for (i in 1:n) {
lcg.seed <- getRmetricsOptions("lcg.seed")
setRmetricsOptions(lcg.seed = (a * lcg.seed + c) %% m)
r.lcg[i] = getRmetricsOptions("lcg.seed") / m }
r.lcg = (max-min)*r.lcg + min
r.lcg
}
rnorm.lcg <-
function(n, mean = 0, sd = 1)
{
(qnorm(runif.lcg(n = n, min = 0, max = 1)) - mean)/sd^2
}
rt.lcg <-
function(n, df)
{
qt(runif.lcg(n = n, min = 0, max = 1), df = df)
} |
mdl_config <- function(con = mdl_get_connection() ) {
ret <- tbl(con, "mdl_config") %>%
collect()
class(ret) <- c("mdl_config", class(ret))
ret
} |
RealizedEst=function(RV=RV, JV=NULL){
if (length(JV) == 0){
n=length(RV)
hi.cond.function.NJ=function(theta_tau, h, iv){
theta_tau[1]+theta_tau[3]*h+theta_tau[2]*iv
}
ineqn.NJ=function(theta_tau){
omega_g=theta_tau[1]; alpha_g=theta_tau[2]; gamma=theta_tau[3]
z1=alpha_g+gamma
return(c(z1))
}
likelihood.function.LH.NJ=function(theta_tau){
omega_g=theta_tau[1]; alpha_g=theta_tau[2]; gamma=theta_tau[3]
hi=omega_g/(1-alpha_g-gamma)
likelihood=log(hi)+RV[1]/hi
for (i in 2:n){
hi=hi.cond.function.NJ(theta_tau, hi, RV[i-1])
likelihood=likelihood+log(hi)+RV[i]/hi
}
return(likelihood)
}
thetaLH=Rsolnp::solnp(c(mean(RV),0.45,0.3),fun=likelihood.function.LH.NJ,ineqfun=ineqn.NJ,ineqLB=c(0),ineqUB=c(1),
LB=rep(0,3),UB=rep(1,3))$par
names(thetaLH)=c("omega_g", "alpha_g", "gamma")
hiLH=rep(0,n+1); hiLH[1]=thetaLH[1]/(1-thetaLH[2]-thetaLH[3])
for (i in 2:(n+1)){
hiLH[i]=hi.cond.function.NJ(thetaLH, hiLH[i-1], RV[i-1])
}
return(list("coefficients"=thetaLH, "sigma"=hiLH[1:n], "pred"=hiLH[n+1]))
} else {
if (length(RV) != length(JV)){
stop("realized volatility and jump variation series should be of equal length")
}
if (length(which(RV<0)) != 0){
stop("realized volatility should be non-negative")
}
if (length(which(JV<0)) != 0){
stop("jump variation should be non-negative")
}
n=length(RV)
hi.cond.function=function(theta_tau, h, iv, jv){
theta_tau[1]+theta_tau[4]*h+theta_tau[2]*iv+theta_tau[3]*jv
}
ineqn=function(theta_tau){
omega_g=theta_tau[1]; alpha_g=theta_tau[2]; beta_g=theta_tau[3]; gamma=theta_tau[4]
z1=alpha_g+gamma
return(c(z1))
}
likelihood.function.LH=function(theta_tau){
omega_g=theta_tau[1]; alpha_g=theta_tau[2]; beta_g=theta_tau[3]; gamma=theta_tau[4]
hi=(omega_g+beta_g*stats::median(JV))/(1-alpha_g-gamma)
likelihood=log(hi)+RV[1]/hi
for (i in 2:n){
hi=hi.cond.function(theta_tau, hi, RV[i-1], JV[i-1])
likelihood=likelihood+log(hi)+RV[i]/hi
}
return(likelihood)
}
thetaLH=Rsolnp::solnp(c(mean(RV),0.45,0.5,0.3),fun=likelihood.function.LH,ineqfun=ineqn,ineqLB=c(0),ineqUB=c(1),
LB=c(0,0,0,0),UB=c(1,1,10,1))$par
names(thetaLH)=c("omega_g", "alpha_g", "beta_g", "gamma")
hiLH=rep(0,n+1); hiLH[1]=(thetaLH[1]+thetaLH[3]*stats::median(JV))/(1-thetaLH[2]-thetaLH[4])
for (i in 2:(n+1)){
hiLH[i]=hi.cond.function(thetaLH, hiLH[i-1], RV[i-1], JV[i-1])
}
return(list("coefficients"=thetaLH, "sigma"=hiLH[1:n], "pred"=hiLH[n+1]))
}
} |
oldsvyquantile<-function(x,design,quantiles,...) UseMethod("oldsvyquantile", design)
oldsvyquantile.survey.design<-function(x,design,quantiles,alpha=0.05,
ci=FALSE, method="linear",f=1,
interval.type=c("Wald","score","betaWald"),
na.rm=FALSE,se=ci, ties=c("discrete","rounded"), df=NULL,...){
if (inherits(x,"formula"))
x<-model.frame(x ,model.frame(design), na.action=na.pass)
else if(typeof(x) %in% c("expression","symbol"))
x<-eval(x, model.frame(design,na.action=na.pass))
if (na.rm){
nas<-rowSums(is.na(x))
design<-design[nas==0,]
if (length(nas)>length(design$prob))
x<-x[nas==0,,drop=FALSE]
else
x[nas>0,]<-0
}
w<-weights(design)
epsilon<-0.1*min(w[w>0])/sum(w)
if (is.null(df)){
qcrit<-function(p, lower.tail=TRUE) qt(p, df=degf(design), lower.tail=lower.tail)
} else if(df==Inf){
qcrit <- function(p,lower.tail=TRUE) qnorm(p,lower.tail=lower.tail)
} else {
qcrit <- function(p,lower.tail=TRUE) qt(p,df=df,lower.tail=lower.tail)
}
computeQuantiles<-function(xx,p=quantiles){
if (any(is.na(x))) return(NA*p)
oo<-order(xx)
cum.w<-cumsum(w[oo])/sum(w)
cdf<-approxfun(cum.w,xx[oo],method=method,f=f,
yleft=min(xx),yright=max(xx),ties=min)
cdf(p)
}
computeQuantilesRounded<-function(xx,p=quantiles){
if (any(is.na(xx))) return(NA*p)
ww<-rowsum(w,xx,reorder=TRUE)
xx<-sort(unique(xx))
cum.w <- cumsum(ww)/sum(ww)
cdf <- approxfun(cum.w, xx, method = method, f = f,
yleft = min(xx), yright = max(xx),ties=min)
cdf(p)
}
computeScoreCI<-function(xx,p){
if (any(is.na(xx))) return(c(NA,NA))
U<-function(theta){ ((xx>theta)-(1-p))}
scoretest<-function(theta,qlimit){
umean<-svymean(U(theta),design)
umean/sqrt(attr(umean,"var"))-qlimit
}
iqr<-IQR(xx)
lower<-min(xx)+iqr/100
upper<-max(xx)-iqr/100
tol<-1/(100*sqrt(nrow(design)))
c(uniroot(scoretest,interval=c(lower,upper),
qlimit=qcrit(alpha/2,lower.tail=FALSE),tol=tol)$root,
uniroot(scoretest,interval=c(lower,upper),
qlimit=qcrit(alpha/2,lower.tail=TRUE),tol=tol)$root)
}
computePCI<-function(se,alpha,p){
if (interval.type=="Wald"){
p.up<-p+qcrit(alpha/2,lower.tail=FALSE)*se
p.low<-p+qcrit(alpha/2,lower.tail=TRUE)*se
c(p.low,p.up)
} else if (interval.type=="betaWald"){
n.eff <- (p*(1-p))/(se^2)
n.eff <- n.eff * ( qt(alpha/2, nrow(design)-1)/qt(alpha/2, degf(design)) )^2
p.up<-qbeta(1-alpha/2, n.eff*p+1, n.eff*(1-p))
p.low<-qbeta(alpha/2, n.eff*p, n.eff*(1-p)+1)
c(p.low,p.up)
}
}
computeWaldCI<-function(xx,p){
if (any(is.na(xx))) return(c(NA,NA))
theta0<-computeQuantiles(xx,p)
U<- ((xx>theta0)-(1-p))
wtest<-svymean(U,design)
p.ci<-computePCI(SE(wtest),alpha,p)
p.low<-p.ci[1]
p.up<-p.ci[2]
oo<-order(xx)
cum.w<-cumsum(w[oo])/sum(w)
approx(cum.w,xx[oo],xout=c(p.low,p.up), method=method,f=f,
yleft=min(xx),yright=max(xx),ties=min)$y
}
computeWaldCIRounded<-function(xx,p){
if(any(is.na(xx))) return(c(NA,NA))
theta0<-computeQuantilesRounded(xx,p)
U<- ((xx>theta0)-(1-p))
ww<-rowsum(w,xx, reorder=TRUE)
uxx <- sort(unique(xx))
wtest<-svymean(U,design)
p.ci<-computePCI(SE(wtest),alpha,p)
p.low<-p.ci[1]
p.up<-p.ci[2]
oo<-order(xx)
cum.w<-cumsum(ww)/sum(ww)
approx(cum.w,uxx,xout=c(p.low,p.up), method=method,f=f,
yleft=min(xx),yright=max(xx),ties=min)$y
}
ties<-match.arg(ties)
computeQ<-switch(ties, discrete=computeQuantiles,rounded=computeQuantilesRounded)
if (!is.null(dim(x)))
rval<-t(matrix(apply(x,2,computeQ),nrow=length(quantiles),
dimnames=list(as.character(round(quantiles,2)),colnames(x))))
else
rval<-computeQ(x)
if (!ci & !se) return(rval)
interval.type<-match.arg(interval.type)
computeCI<-switch(paste(interval.type,ties,sep="."), score.discrete=computeScoreCI,
score.rounded=stop("ties=\"rounded\" not available with interval.type=\"score\""),
Wald.rounded=computeWaldCIRounded,
betaWald.rounded=computeWaldCIRounded,
Wald.discrete=computeWaldCI,
betaWald.discrete=computeWaldCI)
if (!is.null(dim(x)))
cis<-array(apply(x,2,function(xx) sapply(quantiles,function(qq) computeCI(xx,qq))),
dim=c(2,length(quantiles),ncol(x)),
dimnames=list(c("(lower","upper)"),
as.character(round(quantiles,2)),
colnames(x)))
else
cis<-sapply(quantiles, function(qq) computeCI(x,qq))
if (ci)
rval<-list(quantiles=rval,CIs=cis)
else
rval<-list(quantiles=rval)
if (is.null(dim(x)))
ses<-(cis[2,]-cis[1,])/(2*qcrit(alpha/2,lower.tail=FALSE))
else
ses<-(cis[2,,]-cis[1,,])/(2*qcrit(alpha/2,lower.tail=FALSE))
attr(rval,"SE")<-ses
class(rval)<-c("oldsvyquantile","svyquantile")
rval
}
oldsvyquantile.svyrep.design<-function(x,design,quantiles,method="linear",
interval.type=c("probability","quantile"),f=1,
return.replicates=FALSE,
ties=c("discrete","rounded"),na.rm=FALSE,
alpha=0.05,df=NULL,...){
if (!exists(".Generic",inherits=FALSE))
.Deprecated("svyquantile")
ties<-match.arg(ties)
interval<-match.arg(interval.type)
if (design$type %in% c("JK1","JKn") && interval=="quantile")
warning("Jackknife replicate weights may not give valid standard errors for quantiles")
if (design$type %in% "other" && interval=="quantile")
warning("Not all replicate weight designs give valid standard errors for quantiles.")
if (inherits(x,"formula"))
x<-model.frame(x,design$variables,na.action=if(na.rm) na.pass else na.fail)
else if(typeof(x) %in% c("expression","symbol"))
x<-eval(x, design$variables)
if (na.rm){
nas<-rowSums(is.na(x))
design<-design[nas==0,]
if (length(nas)>length(design$prob))
x<-x[nas==0,,drop=FALSE]
else
x[nas>0,]<-0
}
if (NROW(x)<=1){
rval<-matrix(rep(as.matrix(x),length(quantiles)),ncol=NCOL(x),nrow=length(quantiles),byrow=TRUE)
dimnames(rval)<-list(paste("q",round(quantiles,2),sep=""), names(x))
if (getOption("survey.drop.replicates") && !is.null(design$selfrep) && all(design$selfrep))
vv<-matrix(0,ncol=NCOL(x),nrow=length(quantiles))
else
vv<-matrix(NA,ncol=NCOL(x),nrow=length(quantiles))
dimnames(vv)<-list(paste("q",round(quantiles,2),sep=""), names(x))
attr(rval,"var")<-vv
attr(rval,"statistic")<-quantiles
if (return.replicates)
rval<-list(mean=rval,replicates=NULL)
class(rval)<-"svrepstat"
return(rval)
}
if (is.null(df))
df<-degf(design)
if (df==Inf)
qcrit<-qnorm
else
qcrit <-function(...) qt(...,df=df)
w<-weights(design,"analysis")
if (interval=="quantile"){
if (ties=="discrete")
computeQuantiles<-function(xx){
oo<-order(xx)
ws<-weights(design,"sampling")
epsilon<-0.1*min(ws[ws>0])/sum(ws)
cum.ws<-cumsum(ws[oo])/sum(ws)
rval<-approx(cum.ws,xx[oo],method=method,f=f,
yleft=min(xx),yright=max(xx),
xout=quantiles,ties=min)$y
cum.w<-apply(w,2,function(wi) cumsum(wi[oo])/sum(wi))
qq<-apply(cum.w, 2,
function(cum.wi){
approx(cum.wi,xx[oo],method=method,f=f,
yleft=min(xx),yright=max(xx),
xout=quantiles,ties=min)$y
}
)
if (length(quantiles)>1)
qq<-t(qq)
else
qq<-as.matrix(qq)
rval<-list(quantiles=rval,
variances=diag(as.matrix(svrVar(qq,design$scale,design$rscales,mse=design$mse,coef=rval))))
if (return.replicates)
rval<-c(rval, list(replicates=qq))
rval
} else {
computeQuantiles<-function(xx){
ws<-weights(design,"sampling")
epsilon<-0.1*min(ws[ws>0])/sum(ws)
wws<-rowsum(ws,xx,reorder=TRUE)
uxx<-sort(unique(xx))
cum.wws<-cumsum(wws)/sum(wws)
rval<-approx(cum.wws,uxx,method=method,f=f,
yleft=min(xx),yright=max(xx),
xout=quantiles,ties=min)$y
cum.w<-apply(rowsum(w,xx,reorder=TRUE),2,function(wi) cumsum(wi)/sum(wi))
qq<-apply(cum.w, 2,
function(cum.wi){
approx(cum.wi,uxx,method=method,f=f,
yleft=min(xx),yright=max(xx),
xout=quantiles,ties=min)$y
}
)
if (length(quantiles)>1)
qq<-t(qq)
else
qq<-as.matrix(qq)
rval<-list(quantiles=rval,
variances=diag(as.matrix(svrVar(qq,design$scale,design$rscales,mse=design$mse,coef=rval))))
if (return.replicates)
rval<-c(rval, list(replicates=qq))
rval
}
}
} else {
if (ties=="discrete"){
computeQuantiles<-function(xx){
oo<-order(xx)
w<-weights(design,"sampling")
epsilon<-0.1*min(w[w>0])/sum(w)
cum.w<- cumsum(w[oo])/sum(w)
Qf<-approxfun(cum.w,xx[oo],method=method,f=f,
yleft=min(xx),yright=max(xx),
ties=min)
point.estimates<-Qf(quantiles)
if(length(quantiles)==1)
estfun<-as.numeric(xx<point.estimates)
else
estfun<-0+outer(xx,point.estimates,"<")
est<-svymean(estfun,design, return.replicates=return.replicates)
if (return.replicates)
q.estimates<-matrix(Qf(est$replicates),nrow=NROW(est$replicates))
zcrit<-abs(qcrit(min(alpha,1-alpha)/2))
ci<-matrix(Qf(c(coef(est)+zcrit*SE(est), coef(est)-zcrit*SE(est))),ncol=2)
variances<-((ci[,1]-ci[,2])/2/zcrit)^2
rval<-list(quantiles=point.estimates,
variances=variances)
if (return.replicates)
rval<-c(rval, list(replicates=q.estimates))
rval
}
} else {
computeQuantiles<-function(xx){
w<-weights(design,"sampling")
epsilon<-0.1*min(w[w>0])/sum(w)
ww<-rowsum(w,xx,reorder=TRUE)
uxx<-sort(unique(xx))
cum.w<- cumsum(ww)/sum(ww)
Qf<-approxfun(cum.w,uxx,method=method,f=f,
yleft=min(xx),yright=max(xx),
ties=min)
point.estimates<-Qf(quantiles)
if(length(quantiles)==1)
estfun<-as.numeric(xx<point.estimates)
else
estfun<-0+outer(xx,point.estimates,"<")
est<-svymean(estfun, design, return.replicates=return.replicates)
if (return.replicates)
q.estimates<-matrix(Qf(est$replicates),nrow=NROW(est$replicates))
zcrit<-abs(qcrit(min(alpha,1-alpha)/2))
ci<-matrix(Qf(c(coef(est)+zcrit*SE(est), coef(est)-zcrit*SE(est))),ncol=2)
variances<-((ci[,1]-ci[,2])/2/zcrit)^2
rval<-list(quantiles=point.estimates,
variances=variances)
if (return.replicates)
rval<-c(rval, list(replicates=q.estimates))
rval
}
}
}
if (!is.null(dim(x)))
results<-apply(x,2,computeQuantiles)
else
results<-computeQuantiles(x)
rval<-matrix(sapply(results,"[[","quantiles"),ncol=NCOL(x),nrow=length(quantiles),
dimnames=list(paste("q",round(quantiles,2),sep=""), names(x)))
vv<-matrix(sapply(results,"[[","variances"),ncol=NCOL(x),nrow=length(quantiles),
dimnames=list(paste("q",round(quantiles,2),sep=""), names(x)))
attr(rval,"var")<-vv
attr(rval, "statistic")<-"quantiles"
if (return.replicates) {
reps<-do.call(cbind,lapply(results,"[[","replicates"))
attr(reps,"scale")<-design$scale
attr(reps,"rscales")<-design$rscales
attr(reps,"mse")<-design$mse
rval<-list(mean=rval, replicates=reps)
}
class(rval)<-"svrepstat"
rval
}
SE.oldsvyquantile<-function(object,...){
attr(object,"SE")
}
vcov.oldsvyquantile<-function(object,...){
se<-SE(object)
if (is.null(se)) stop("no uncertainty information present")
v<-matrix(NA,length(se),length(se))
warning("Only diagonal of vcov() available")
diag(v)<-se
v
}
coef.oldsvyquantile<-function(object,...){
rval<-as.vector(object$quantiles)
if(ncol(object$quantiles)==1)
names(rval)<-rownames(object$quantiles)
else if (nrow(object$quantiles)==1)
names(rval)<-colnames(object$quantiles)
else names(rval)<-t(outer(colnames(object$quantiles),
rownames(object$quantiles),
paste,sep=":"))
rval
}
print.oldsvyquantile<-function(x,...){
print(list(quantiles=x$quantiles, CIs=x$CIs))
}
confint.oldsvyquantile<-function(object,parm=NULL,level=NULL,...){
if (!is.null(level)) stop("need to re-run svyquantile to specify level")
ci<-t(matrix(as.vector(object$CIs),nrow=2))
colnames(ci)<-dimnames(object$CIs)[[1]]
rownames(ci)<-outer(dimnames(object$CIs)[[2]],
dimnames(object$CIs)[[3]],paste,sep="_")
if (is.null(parm))
ci
else
ci[parm,,drop=FALSE]
} |
summary.TrialLevelIT <- function(object, ..., Object){
if (missing(Object)){Object <- object}
cat("\nFunction call:\n\n")
print(Object$Call)
cat("\n\n
cat("\n
cat("\nTotal number of trials: ", Object$N.Trial)
cat("\n\n\n
cat("\n
cat("\n")
print(format(round(Object$R2.ht, 4), nsmall = 4))
} |
plugInLMM <-
function(YS, fixed.part, random.part, reg, con, weights, backTrans, thetaFun){
model <- formula(paste('YS', '~', fixed.part, '+', random.part))
regS <- subset(reg, con == 1)
regR <- subset(reg, con == 0)
if (is.null(weights)) {
weights <- rep(1, nrow(reg))
weightS <- rep(1, nrow(regS))} else {
weightS <- subset(weights, con == 1)}
mEst <- lmer(model, weights = weightS, data.frame(YS, regS, weightS))
tst <- unlist(apply((as.matrix(reg[,names(ranef(mEst))])),2,unique))
if ((length(tst[duplicated(tst)])) > 0) {stop(paste("There are at least two 'random.part' variables with at least one the same value.
Rename the values of 'random.part' variables - you can use qape::modifyDataset"))}
Zobj <- Zfun(model, reg)
Z <- Zobj$Z
ZBlockNames <- Zobj$ZBlockNames
vNames <- make.unique(Zfun(model, reg)$vNames,sep = ".")
colnames(Z) <- vNames
X <- model.matrix(formula(paste('~', fixed.part)), reg)
ZS <- getME(mEst, name = "Z")
vSNames <- make.unique(colnames(ZS),sep = ".")
colnames(ZS) <- vSNames
ZR <- Z[(con == 0),vSNames]
beta <- mEst@beta
Xbeta <- X %*% beta
XS <- getME(mEst, name = 'X')
vS <- as.vector(getME(mEst, name = "b"))
vSDF <- data.frame(vSNames, vS)
eS <- residuals(mEst)
XR <- model.matrix(formula(paste('~', fixed.part)), regR)
sigma2R <- sigma(mEst)^2
R <- diag(sigma2R/weightS, nrow = nrow(regS), ncol = nrow(regS))
G <- sigma(mEst)^2 * crossprod(getME(mEst,"Lambdat"))
Y <- rep(NA,nrow(reg))
Y[con == 1] <- YS
YP <- Y[con == 0] <- XR %*% beta + ZR %*% vS
if (is.null(backTrans))
YbackTrans <- Y else
YbackTrans <- backTrans(Y)
if (is.null(backTrans))
YPbackTrans <- YP else
YPbackTrans <- backTrans(YP)
thetaP <- thetaFun(YbackTrans)
outl <- list(
fixed.part = fixed.part,
random.part = random.part,
thetaP = thetaP,
beta = beta,
Xbeta = Xbeta,
sigma2R = sigma2R,
R = R,
G = G,
model = model,
mEst = mEst,
YS = YS,
reg = reg,
con = con,
regS = regS,
regR = regR,
weights = weights,
weightS = weightS,
Z = Z,
ZBlockNames = ZBlockNames,
X = X,
ZS = ZS,
XR = XR,
ZR = ZR,
eS = eS,
vS = vSDF,
thetaFun = thetaFun,
backTrans = backTrans)
class(outl) = "plugInLMM"
return(outl)
} |
marginal_effects.multinom <-
function(model,
data = find_data(model, parent.frame()),
variables = NULL,
type = NULL,
eps = 1e-7,
varslist = NULL,
as.data.frame = TRUE,
...) {
if (is.null(varslist)) {
varslist <- find_terms_in_model(model, variables = variables)
}
out1 <- lapply(c(varslist$nnames, varslist$lnames), dydx, data = data, model = model, type = NULL, eps = eps, as.data.frame = as.data.frame, ...)
out2 <- list()
for (i in seq_along(varslist$fnames)) {
out2[[i]] <- dydx.factor(data = data, model = model, varslist$fnames[i], fwrap = FALSE, type = NULL, as.data.frame = as.data.frame, ...)
}
out <- c(out1, out2)
if (isTRUE(as.data.frame)) {
out <- do.call("cbind.data.frame", out[vapply(out, function(x) length(x) > 0, FUN.VALUE = logical(1))])
} else {
out <- do.call("cbind", out[vapply(out, function(x) length(x) > 0, FUN.VALUE = logical(1))])
}
return(out)
} |
test_that("Classes", {
expect_equal(class(style_underline("foo")), c("cli_ansi_string", "ansi_string", "character"))
})
test_that("Coloring and highlighting works", {
local_reproducible_output(crayon = TRUE)
expect_equal(c(style_underline("foo")), "\u001b[4mfoo\u001b[24m")
expect_equal(c(col_red("foo")), "\u001b[31mfoo\u001b[39m")
expect_equal(c(bg_red("foo")), "\u001b[41mfoo\u001b[49m")
})
test_that("Applying multiple styles at once works", {
local_reproducible_output(crayon = TRUE)
st <- combine_ansi_styles(col_red, bg_green, "underline")
expect_equal(
c(st("foo")),
"\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39m")
st <- combine_ansi_styles(style_underline, "red", bg_green)
expect_equal(
c(st("foo")),
"\u001b[4m\u001b[31m\u001b[42mfoo\u001b[49m\u001b[39m\u001b[24m")
})
test_that("Nested styles are supported", {
local_reproducible_output(crayon = TRUE)
st <- combine_ansi_styles(style_underline, bg_blue)
expect_equal(
c(col_red("foo", st("bar"), "!")),
"\u001b[31mfoo\u001b[4m\u001b[44mbar\u001b[49m\u001b[24m!\u001b[39m")
})
test_that("Nested styles of the same type are supported", {
local_reproducible_output(crayon = TRUE)
expect_equal(
c(col_red("a", col_blue("b", col_green("c"), "b"), "c")),
"\u001b[31ma\u001b[34mb\u001b[32mc\u001b[34mb\u001b[31mc\u001b[39m")
})
test_that("Reset all styles", {
local_reproducible_output(crayon = TRUE)
st <- combine_ansi_styles("red", bg_green, "underline")
ok <- c(
paste0(
"\033[0m\033[31m\033[42m\033[4mfoo\033[24m\033[49m\033[39m",
"foo\033[0m\033[22m\033[23m\033[24m\033[27m\033[28m",
"\033[29m\033[39m\033[49m"),
paste0("\u001b[0m\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m",
"\u001b[39mfoo\u001b[0m")
)
expect_true(style_reset(st("foo"), "foo") %in% ok)
})
test_that("Variable number of arguments", {
local_reproducible_output(crayon = TRUE)
expect_equal(c(col_red("foo", "bar")), "\u001b[31mfoobar\u001b[39m")
}) |
outlier_labeler <- function(x, standardize = TRUE, ...){
if (standardize) {
x <- scale(x, ...)
}
ifelse(abs(x) >= 3, "3sd", ifelse(abs(x) >= 2 & abs(x) < 3, "2sd",
ifelse(abs(x) >= 1.5 & abs(x) < 2, "1.5sd", "-")))
} |
ggPieDonut=function(data,mapping,
addPieLabel=TRUE,addDonutLabel=TRUE,
showRatioDonut=TRUE,showRatioPie=TRUE,
showRatioPieAbove10=TRUE,title="",
labelposition=1, polar=TRUE,
use.label=TRUE,use.labels=TRUE,
interactive=FALSE){
(cols=colnames(data))
if(use.labels) data=addLabelDf(data,mapping)
count<-NULL
if("y" %in% names(mapping)){
count<-getMapping(mapping,"y")
} else {
if("count" %in% names(mapping)) count<-getMapping(mapping,"count")
}
count
(pies=getMapping(mapping,"pies"))
(donuts=getMapping(mapping,"donuts"))
if((length(pies)+length(donuts))!=2){
(xvar=getMapping(mapping,"x"))
if(length(xvar)>1) {
pies=xvar[1]
donuts=xvar[2]
}
}
if((length(pies)+length(donuts))==1) {
if(is.null(pies)) {
p<-ggDonut(data,mapping,addDonutLabel=addDonutLabel,
showRatio=showRatioDonut,title=title,
labelposition=labelposition, polar=polar,interactive=interactive)
} else {
p<-ggPie(data,mapping,title=title,
addPieLabel=addPieLabel,showRatioPie=showRatioPie,
showRatioPieAbove10=showRatioPieAbove10,
labelposition=labelposition, polar=polar,interactive=interactive)
}
} else {
if(is.null(count)){
dat1=ddply(data,c(pies,donuts),nrow)
colnames(dat1)[3]="n"
dat1$ymax=cumsum(dat1$n)
dat1$ymin=cumsum(dat1$n)-dat1$n
dat1$ypos=dat1$ymin+dat1$n/2
dat1$ratio=dat1$n*100/sum(dat1$n)
dat1$cumratio=dat1$ypos*100/sum(dat1$n)
dat1$hjust=ifelse((dat1$cumratio>25 & dat1$cumratio<75),0,1)
dat1$label=paste0(dat1[[pies]],'<br>',dat1[[donuts]],"<br>",dat1$n,"(",round(dat1$ratio,1),"%)")
data2=ddply(data,pies,nrow)
colnames(data2)[2]="sum"
data2$cumsum=cumsum(data2$sum)
data2$pos=data2$cumsum-data2$sum/2
data2$ymin=data2$cumsum-data2$sum
data2$ratio=data2$sum*100/sum(data2$sum)
data2$label=ifelse(data2$ratio>10,
paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
data2$tooltip=paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)")
} else{
dat1=data
colnames(dat1)[colnames(dat1)==count]="n"
dat1$ymax=cumsum(dat1$n)
dat1$ymin=cumsum(dat1$n)-dat1$n
dat1$ypos=dat1$ymin+dat1$n/2
dat1$ratio=dat1$n*100/sum(dat1$n)
dat1$cumratio=dat1$ypos*100/sum(dat1$n)
dat1$hjust=ifelse((dat1$cumratio>25 & dat1$cumratio<75),0,1)
dat1$label=paste0(dat1[[pies]],"<br>",dat1[[donuts]],"<br>",dat1$n,"(",round(dat1$ratio,1),"%)")
dat1
pies
data2=eval(parse(text="ddply(dat1,pies,summarize,sum(n))"))
data2
colnames(data2)[2]="sum"
data2=data2[order(data2$sum,decreasing=TRUE),]
data2$cumsum=cumsum(data2$sum)
data2$pos=data2$cumsum-data2$sum/2
data2$ymin=data2$cumsum-data2$sum
data2$ratio=data2$sum*100/sum(data2$sum)
data2$label=ifelse(data2$ratio>10,
paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
data2$tooltip=paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)")
}
mainCol=rainbow(nrow(data2))
subCol=subcolors(dat1,pies,mainCol)
p<-ggplot(dat1) +
geom_rect_interactive(aes_string( ymax="ymax", ymin="ymin", xmax="4", xmin="3",
tooltip="label",data_id=donuts),fill=subCol,colour="white")
p<-p+ geom_rect_interactive(aes_string(ymax="cumsum", ymin="ymin", xmax="3", xmin="0",
tooltip="tooltip",data_id=pies),data=data2,
fill=mainCol,colour="white",alpha=0.7)
p<-p+ theme_clean()
if(addDonutLabel) {
label2=dat1[[donuts]]
if(showRatioDonut)
label2=paste0(label2,"\n(",round(dat1$ratio,1),"%)")
if(polar){
if(labelposition==1) {
p<- p+ geom_text(aes_string(label="label2",x="4.3",y="ypos",hjust="hjust"),size=3)+
geom_segment(aes_string(x="4",xend="4.2",y="ypos",yend="ypos"))
} else{
p<- p+ geom_text(aes_string(label="label2",x="3.5",y="ypos"),size=3)
}
} else{
p<-p+ geom_text(aes_string(label="label2",x="3.5",y="ypos"),size=3)
}
}
if(addPieLabel) {
Pielabel=data2[[pies]]
if(showRatioPie) {
if(showRatioPieAbove10) {
Pielabel=ifelse(data2$ratio>10,
paste0(data2[[pies]],"\n(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
}
else Pielabel=paste0(Pielabel,"\n(",round(data2$ratio,1),"%)")
}
p<-p+geom_text(data=data2,aes_string(label="Pielabel",x="1.5",y="pos"),size=4)
}
if(polar) p<-p+coord_polar(theta="y",start=3*pi/2)
if(title!="") p<-p+ggtitle(title)
if(use.label){
labels=c()
for(i in 1:length(cols)) {
temp=get_label(data[[cols[i]]])
labels=c(labels,ifelse(is.null(temp),cols[i],temp))
}
labels
p<-p+scale_x_discrete(labels=labels)
}
if(interactive) {
tooltip_css <- "background-color:white;font-style:italic;padding:10px;border-radius:10px 20px 10px 20px;"
p<-girafe(ggobj=p)
p<-girafe_options(p,
opts_tooltip(css=tooltip_css,opacity=.75),
opts_zoom(min=1,max=10))
}
p
}
p
}
ggDonut=function(data,mapping,
addDonutLabel=TRUE,showRatio=TRUE,
polar=TRUE,labelposition=1,labelsize=3,
title="",
use.label=TRUE,use.labels=TRUE,
alpha=0.7,
interactive=FALSE,palette=NULL,reverse=FALSE,
xmin=3,xmax=4,
start=3*pi/2,
direction=1,
colour="white",
explode=NULL,
explodePos=0.5,...){
if(use.labels) data=addLabelDf(data,mapping)
donuts<-count<-NULL
if("y" %in% names(mapping)){
count<-getMapping(mapping,"y")
} else {
if("count" %in% names(mapping)) count<-getMapping(mapping,"count")
}
if("donuts" %in% names(mapping)) {
donuts<-getMapping(mapping,"donuts")
} else {
if("x" %in% names(mapping)) donuts<-getMapping(mapping,"x")
}
if(is.null(count)){
dat1=ddply(data,donuts,nrow)
colnames(dat1)[2]="n"
} else{
dat1=data
colnames(dat1)[colnames(dat1)==count]="n"
}
dat1$ymax=cumsum(dat1$n)
dat1$ymin=cumsum(dat1$n)-dat1$n
dat1$ypos=dat1$ymin+dat1$n/2
dat1$ratio=dat1$n*100/sum(dat1$n)
dat1$cumratio=dat1$ypos*100/sum(dat1$n)
dat1$hjust=ifelse((dat1$cumratio>25 & dat1$cumratio<75),0,1)
dat1$label=paste0(dat1[[donuts]],"<br>",dat1$n,"(",round(dat1$ratio,1),"%)")
dat1$xmax=xmax
dat1$xmin=xmin
if(!is.null(explode)) {
if(is.numeric(explode)) explode=dat1[[donuts]][explode]
dat1$xmax[dat1[[donuts]] %in% explode]=dat1$xmax[dat1[[donuts]] %in% explode]+explodePos
dat1$xmin[dat1[[donuts]] %in% explode]=dat1$xmin[dat1[[donuts]] %in% explode]+explodePos
}
if(labelposition==1) {
dat1$labelpos=dat1$xmax+0.3
dat1$segxstart=dat1$xmax
dat1$segxend=dat1$xmax+0.2
} else {
dat1$labelpos=dat1$xmax-0.5
}
dat1
labelposition
if(is.null(palette)) {
mainCol=rainbow(nrow(dat1))
} else{
mycolors=palette2colors(palette,reverse=reverse)
if(length(mycolors)<nrow(dat1)) {
mycolors=rep(mycolors,nrow(dat1) %/% length(mycolors) + 1)
}
mainCol=mycolors[1:nrow(dat1)]
}
p<-ggplot(dat1) +
geom_rect_interactive(aes_string( ymax="ymax", ymin="ymin", xmax="xmax", xmin="xmin",
tooltip="label",data_id=donuts),fill=mainCol,alpha=alpha,colour=colour,...)+
coord_polar(theta="y",start=start, direction=direction)+
xlim(0,xmax+labelposition+ifelse(is.null(explode),0,max(0,explodePos)))+
theme_clean()
donutlabel=dat1[[donuts]]
if(showRatio)
donutlabel=paste0(donutlabel,"\n(",round(dat1$ratio,1),"%)")
if(labelposition==1) {
p<- p+ geom_text(aes_string(label="donutlabel",x="labelpos",y="ypos",hjust="hjust"),
size=labelsize)+
geom_segment(aes_string(x="segxstart",xend="segxend",y="ypos",yend="ypos"))
} else{
p<- p+ geom_text(aes_string(label="donutlabel",x="labelpos",y="ypos"),size=labelsize)
}
if(title!="") p<-p+ggtitle(title)
if(interactive) {
tooltip_css <- "background-color:white;font-style:italic;padding:10px;border-radius:10px 20px 10px 20px;"
p<-girafe(ggobj=p)
p<-girafe_options(p,
opts_tooltip(css=tooltip_css,opacity=.75),
opts_zoom(min=1,max=10))
}
p
}
subcolors <- function(.dta,main,mainCol){
tmp_dta = cbind(.dta,1,'col')
tmp1 = unique(.dta[[main]])
for (i in 1:length(tmp1)){
tmp_dta$"col"[.dta[[main]] == tmp1[i]] = mainCol[i]
}
u <- unlist(by(tmp_dta$"1",tmp_dta[[main]],cumsum))
n <- dim(.dta)[1]
subcol=rep(rgb(0,0,0),n);
for(i in 1:n){
t1 = col2rgb(tmp_dta$col[i])/256
subcol[i]=rgb(t1[1],t1[2],t1[3],1/(1+u[i]))
}
return(subcol);
}
ggPie=function(data,mapping,
addPieLabel=TRUE,showRatioPie=TRUE,
showRatioPieAbove10=TRUE,title="",
labelposition=1, polar=TRUE,
use.label=TRUE,use.labels=TRUE,
interactive=FALSE){
(cols=colnames(data))
if(use.labels) data=addLabelDf(data,mapping)
count<-NULL
if("y" %in% names(mapping)){
count<-getMapping(mapping,"y")
} else {
if("count" %in% names(mapping)) count<-getMapping(mapping,"count")
}
(pies=getMapping(mapping,"pies"))
if(is.null(pies)){
(xvar=getMapping(mapping,"x"))
pies=xvar[1]
}
if(is.null(count)){
data2=ddply(data,pies,nrow)
colnames(data2)[2]="sum"
data2$cumsum=cumsum(data2$sum)
data2$pos=data2$cumsum-data2$sum/2
data2$ymin=data2$cumsum-data2$sum
data2$ratio=data2$sum*100/sum(data2$sum)
data2$label=ifelse(data2$ratio>10,
paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
data2$tooltip=paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)")
} else{
data2=data[c(pies,count)]
colnames(data2)[2]="sum"
data2=ddply(data2,pies,summarize,sum=sum(sum))
data2
colnames(data2)[2]="sum"
data2=data2[order(data2$sum,decreasing=TRUE),]
data2
data2$cumsum=cumsum(data2$sum)
data2$pos=data2$cumsum-data2$sum/2
data2$ymin=data2$cumsum-data2$sum
data2$ratio=data2$sum*100/sum(data2$sum)
data2$label=ifelse(data2$ratio>10,
paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
data2$tooltip=paste0(data2[[pies]],"<br>",data2$sum,"(",round(data2$ratio,1),"%)")
}
mainCol=rainbow(nrow(data2))
p<-ggplot(data2) +
geom_rect_interactive(aes_string(ymax="cumsum", ymin="ymin", xmax="3", xmin="0",
tooltip="tooltip",data_id=pies),
fill=mainCol,colour="white",alpha=0.7)
p<-p+ theme_clean()
if(addPieLabel) {
Pielabel=data2[[pies]]
if(showRatioPie) {
if(showRatioPieAbove10) {
Pielabel=ifelse(data2$ratio>10,
paste0(data2[[pies]],"\n(",round(data2$ratio,1),"%)"),
paste0(data2[[pies]]))
}
else Pielabel=paste0(Pielabel,"\n(",round(data2$ratio,1),"%)")
}
p<-p+geom_text(data=data2,aes_string(label="Pielabel",x="1.5",y="pos"),size=4)
}
if(polar) p<-p+coord_polar(theta="y",start=3*pi/2)
if(title!="") p<-p+ggtitle(title)
if(use.label){
labels=c()
for(i in 1:length(cols)) {
temp=get_label(data[[cols[i]]])
labels=c(labels,ifelse(is.null(temp),cols[i],temp))
}
labels
p<-p+scale_x_discrete(labels=labels)
}
if(interactive) {
tooltip_css <- "background-color:white;font-style:italic;padding:10px;border-radius:10px 20px 10px 20px;"
p<-girafe(ggobj=p)
p<-girafe_options(p,
opts_tooltip(css=tooltip_css,opacity=.75),
opts_zoom(min=1,max=10))
}
p
} |
omicdata <- function(file, backgrounddose, check = TRUE,
norm.method = c("cyclicloess", "quantile", "scale", "none"))
{
warning(strwrap(prefix = "\n", initial = "\n",
"omicdata() is a deprecated function that was replaced by microarraydata().
You should replace it by microarraydata(), RNAseqdata(), metabolomicdata()
or equivalentlty continuousmicdata() or continuousanchoringdata()
depending of the type of data you handle. \n"))
microarraydata(file = file, backgrounddose, check = check, norm.method = norm.method)
} |
get_equally_spaced_points <- function(number_of_points) {
parameter_validators$number_of_points$validate(
number_of_points, -4)
equally_spaced_points <- NULL
inc <- pi * (3 - sqrt(5))
off <- 2.0 / number_of_points
for (k in 0:(number_of_points - 1)) {
y <- k * off - 1 + (off / 2)
r <- sqrt(1 - y * y)
phi <- k * inc
x <- cos(phi) * r
z <- sin(phi) * r
equally_spaced_points <- rbind(equally_spaced_points, c(x, y, z))
}
equally_spaced_points
} |
highlight_test_str = function(str, pattern, ignore_case = TRUE,
global = TRUE, perl = TRUE, fixed = FALSE,
color_palette = "Set3") {
match_start = NULL
match_ind = NULL
capture_text = NULL
capture_ind = NULL
in_match_cap_start = NULL
in_match_cap_end = NULL
replacements = NULL
suppressWarnings({
colors = RColorBrewer::brewer.pal(100, color_palette)
})
if (global) {
matches_raw = gregexpr(pattern,
str,
fixed = fixed,
perl = perl & !fixed,
ignore.case = ignore_case & !fixed)[[1]]
if (all(matches_raw == -1)) return(NULL)
matches = regmatches(rep(str, length(matches_raw)),
matches_raw)
} else {
matches_raw = regexpr(pattern,
str,
fixed = fixed,
perl = perl & !fixed,
ignore.case = ignore_case & !fixed)
if (all(matches_raw == -1)) return(NULL)
matches = regmatches(str, matches_raw)[[1]]
}
if (perl & !is.null(attr(matches_raw, "capture.start"))) {
match_end = matches_raw + attr(matches_raw, "match.length") - 1
capture_start = attr(matches_raw, "capture.start")
capture_length = attr(matches_raw, "capture.length") - 1
capture_end = capture_start + capture_length
match_df = data.table::data.table(
match_ind = c(seq_len(length(matches))),
match = matches,
match_start = rep(matches_raw, ncol(capture_end)),
match_end = rep(match_end, ncol(capture_end)),
capture_ind = rep(seq_len(ncol(capture_end)), each = nrow(capture_end)),
capture_start = as.numeric(capture_start),
capture_end = as.numeric(capture_end)
)
match_df = match_df[order(match_ind, capture_start), ]
match_df[, capture_text := stringr::str_sub(
str, capture_start, capture_end
)]
match_df[, in_match_cap_start := capture_start - (match_start - 1)]
match_df[, in_match_cap_end := capture_end - (match_start - 1)]
match_df = unique(
match_df[,
list(match, match_ind, match_start, match_end,
capture_text, capture_ind, in_match_cap_start,
in_match_cap_end)]
)
match_df[, capture_text := paste0(capture_text, "_", capture_ind)]
match_df = match_df[, lapply(
.SD, function(...) list(unique(...))
), by = match]
match_df$replacements = vapply(seq_len(nrow(match_df)), function(.x) {
txt = match_df$match[.x]
buffer = 0
for (i in seq_len(length(match_df$in_match_cap_start[[.x]]))) {
cap_txt = stringr::str_match(
match_df$capture_text[[.x]][i],
"(.+)_\\d+"
)[, 2]
if (match_df$in_match_cap_start[[.x]][i] + buffer <= nchar(txt) &
match_df$in_match_cap_end[[.x]][i] + buffer <= nchar(txt)) {
stringr::str_sub(txt,
match_df$in_match_cap_start[[.x]][i] + buffer,
match_df$in_match_cap_end[[.x]][i] + buffer) = "%s"
replacement = paste0(
"<span style='background-color:", colors[1 + i], "'>",
cap_txt,
"</span>"
)
txt = sprintf(txt, replacement)
buffer = buffer + nchar(replacement) - nchar(cap_txt)
}
}
paste0(
"<span style='background-color:", colors[1], "'>",
txt,
"</span>"
)
}, character(1))
match_df = tidyr::unnest(match_df[, list(match_ind, match, replacements,
match_start, match_end)],
cols = c(match_ind, match_start, match_end))
match_df = unique(match_df)
match_df = data.table::data.table(match_df)
match_df = match_df[order(match_ind, decreasing = TRUE), ]
} else {
match_end = matches_raw + attr(matches_raw, "match.length") - 1
match_df = data.table::data.table(
match_ind = seq_len(length(matches)),
match = matches,
match_start = matches_raw,
match_end = match_end
)
match_df[, replacements := paste0(
"<span style='background-color:", colors[1], "'>",
match,
"</span>"
)]
match_df = match_df[order(match_ind, decreasing = TRUE), ]
}
txt = str
for (i in seq_len(nrow(match_df))) {
stringr::str_sub(txt,
match_df$match_start[i],
match_df$match_end[i]) = "%s"
txt = sprintf(txt, match_df$replacements[i])
}
txt
} |
Plotblsm<-function(Y.ia, model, labels = NULL, xlab = "", ylab = "", plotedges = TRUE, edgecolor = "black",
colEll.i = rgb(.6, .6 ,.6 , alpha=.1), colEll.ia = rgb(1, .6 ,.6 , alpha=.1),
LEVEL = .80,
pchplot = 20, pchEll = 19, pchPl = 19, cexPl = 1.1,
arrowhead = FALSE, curve = 0, xlim = c(-2,2), ylim = c(-2,2), lwdLine = .001, ...){
Z.i=model$lsmbEZ.i
Z.a=model$lsmbEZ.a
D=nrow(model$lsmbVZ.0)
M=nrow(model$lsmbEZ.a)
N=nrow(model$lsmbEZ.i)
VZ1=model$lsmbVZ.1
VZ0=model$lsmbVZ.0
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
par(mar=c(2,2,2,2))
plot(NA, xlim = xlim, ylim = ylim,
ylab=ylab, xlab = xlab,...)
for(n in 1:N)
{
coEl<-ellipse::ellipse(VZ0,centre = Z.i[n,],level=LEVEL,pch=pchEll)
polygon(coEl[,1], coEl[,2], col = colEll.i, border=colEll.i)
}
if (plotedges == TRUE) {
for(i in 1:N){
for(a in 1:M){
if(Y.ia[i,a] == 1)
network.arrow(Z.i[i,1], Z.i[i,2], Z.a[a,1], Z.a[a,2], col = edgecolor,
border = rgb(0, 0, 0, alpha =.02), lwd = .005,
arrowhead = arrowhead, curve = curve)
}
}
}
for(n in 1:M)
{
coEl<-ellipse::ellipse(VZ1,centre = Z.a[n,],level=LEVEL,pch=pchEll)
polygon(coEl[,1], coEl[,2], col = colEll.ia, border=colEll.ia)
}
if(!is.null(labels)){
text(Z.a, labels = labels, col = "black", font = 2, cex=1)
}
} |
d <- read.table("pancreas_refseq_rpkms_counts_3514sc.txt", stringsAsFactors = F)
d <- d[!duplicated(d[,1]), ]
rownames(d) <- d[,1]
d <- d[,3:ncol(d)]
d <- d[,3515:7028]
labs <- read.table("labels.txt", stringsAsFactors = F, header = F)
labs <- as.character(labs)
colnames(d) <- labs
d <- d[,order(colnames(d))]
d <- d[1:(nrow(d) - 1), ]
ann <- read.table("E-MTAB-5061.sdrf.txt", stringsAsFactors = F, header = T, sep = "\t")
rownames(ann) <- ann$Extract.Name
ann <- ann[order(rownames(ann)), ]
ann <- ann[,7:11]
colnames(ann) <- c("cell_quality", "cell_type1", "disease", "sex", "age")
ann$cell_type1 <- unlist(lapply(strsplit(ann$cell_type1, " cell"), "[[", 1))
source("../utils/create_sce.R")
sceset <- create_sce_from_counts(d, ann)
saveRDS(sceset, "segerstolpe.rds") |
set.seed(8675309)
n = 1000
x1 = rnorm(n)
x2 = rnorm(n)
y = 1 + .5*x1 + .2*x2 + rnorm(n)
X = cbind(Intercept = 1, x1, x2)
gd = function(
par,
X,
y,
tolerance = 1e-3,
maxit = 1000,
stepsize = 1e-3,
adapt = FALSE,
verbose = TRUE,
plotLoss = TRUE
) {
beta = par; names(beta) = colnames(X)
loss = crossprod(X %*% beta - y)
tol = 1
iter = 1
while(tol > tolerance && iter < maxit){
LP = X %*% beta
grad = t(X) %*% (LP - y)
betaCurrent = beta - stepsize * grad
tol = max(abs(betaCurrent - beta))
beta = betaCurrent
loss = append(loss, crossprod(LP - y))
iter = iter + 1
if (adapt)
stepsize = ifelse(
loss[iter] < loss[iter - 1],
stepsize * 1.2,
stepsize * .8
)
if (verbose && iter %% 10 == 0)
message(paste('Iteration:', iter))
}
if (plotLoss)
plot(loss, type = 'l', bty = 'n')
list(
par = beta,
loss = loss,
RSE = sqrt(crossprod(LP - y) / (nrow(X) - ncol(X))),
iter = iter,
fitted = LP
)
}
init = rep(0, 3)
gd_result = gd(
init,
X = X,
y = y,
tolerance = 1e-8,
stepsize = 1e-4,
adapt = TRUE
)
str(gd_result)
rbind(
gd = round(gd_result$par[, 1], 5),
lm = coef(lm(y ~ x1 + x2))
) |
context("get_thresholds")
set.seed(2507)
m <- mtcars %>%
machine_learn(outcome = am, tune = FALSE, models = "xgb")
pred <- predict(m, dplyr::sample_n(mtcars, 5))
def <- get_thresholds(pred)
opt_cost <- get_thresholds(pred, optimize = "cost")
test_that("get_thresholds works for model_list", {
expect_s3_class(get_thresholds(m), "tbl_df")
})
test_that("get_thresholds works for predicted_df", {
expect_s3_class(def, "tbl_df")
})
test_that("number of rows is right", {
expect_equal(nrow(get_thresholds(m)),
length(unique(predict(m)$predicted_am)) + 1)
expect_equal(nrow(def),
length(unique(pred$predicted_am)) + 1)
})
test_that("measures are respected", {
expect_false("fnr" %in% names(get_thresholds(m, measures = "acc")))
expect_false("fnr" %in% names(get_thresholds(pred, measures = "acc")))
expect_error(get_thresholds(m, measures = c("mi", "f")), "not available")
})
test_that("cost_fp and cost_fn are respected", {
set1 <- get_thresholds(pred, cost_fn = 10)
set2 <- get_thresholds(pred, measures = "cost", cost_fp = .1, cost_fn = 3)
expect_false(isTRUE(all.equal(def, set1)))
expect_false(isTRUE(all.equal(set1, set2)))
})
test_that("get_thresholds order rows by increasing threshold", {
expect_true(all(diff(def$threshold) < 0))
acc <- get_thresholds(m, measures = "acc")
expect_true(all(diff(acc$threshold) < 0))
})
test_that("get_thresholds return has thresholds_df class", {
expect_s3_class(def, "thresholds_df")
})
test_that("get_thresholds errors nicely if labels aren't present", {
expect_error(get_thresholds(select(pred, -am)), "doesn't have outcomes")
})
test_that("optimize at default doesn't return `optimal` column", {
expect_false("optimal" %in% names(def))
})
test_that("get_thresholds errors informatively if optimize not in measures", {
expect_error(get_thresholds(pred, optimize = "cost", measures = c("ppv", "npv")),
"must be one of the measures")
})
test_that("optimize cost returns a column with TRUE only in lowest-cost row", {
expect_true("optimal" %in% names(opt_cost))
expect_equal(sum(opt_cost$optimal), 1)
expect_equal(which(opt_cost$optimal), which.min(opt_cost$cost))
})
test_that("optimize attaches attribute with name of optimized measure", {
expect_null(attr(def, "optimized"))
expect_equal(attr(opt_cost, "optimized"), "cost")
})
test_that("get_measures", {
expect_error(get_measures("nope"), "not available")
get_all <- get_measures("all")
expect_true("cost" %in% names(get_all))
expect_setequal(get_all, c(-1, 1))
to_get <- c("acc", "tpr")
expect_equal(names(get_measures(to_get)), to_get)
})
context("plot.thresholds_df")
test_that("plot.thresholds_df is a registered S3 method", {
expect_true("plot.thresholds_df" %in% methods("plot"))
})
test_that("plot.thresholds_df returns a ggplot", {
expect_s3_class(plot(def, print = FALSE), "gg")
})
test_that("plot.thresholds_df respects optimize", {
expect_false(isTRUE(all.equal(
plot(def, print = FALSE), plot(opt_cost, print = FALSE)
)))
}) |
seqtransn <- function(seqdata, with.missing=FALSE, norm=FALSE, pweight=FALSE) {
if (!inherits(seqdata,"stslist"))
stop("data is NOT a sequence object, see seqdef function to create one")
dss <- seqdss(seqdata, with.missing=with.missing)
dssl <- seqlength(dss)
nbseq <- nrow(dss)
if (pweight) {
tr <- seqtrate(seqdata)
dss.num <- seqasnum(dss)+1
trans <- matrix(0, nrow=nbseq, ncol=1)
rownames(trans) <- rownames(seqdata)
for (i in 1:nbseq) {
if (dssl[i]>1) {
for (j in 2:dssl[i]) {
trans[i] <- trans[i] + (1-tr[dss.num[i,j-1], dss.num[i,j]])
}
}
}
}
else {
trans <- dssl-1
if (any(dssl==0)) {
trans[dssl==0] <- 0
}
}
if (norm) {
seql <- seqlength(seqdata)
trans <- trans/(seql-1)
if (any(seql==1)) {
trans[seql==1] <- 0
}
}
colnames(trans) <- "Trans."
return(trans)
}
trans.pweight <- function(seqdata, tr) {
res <- 0
for (i in 2:seqlength(seqdata)) {
res <- res + (1-tr[seqdata[i-1], seqdata[i]])
}
return(res)
} |
test_that("oc_config sets OPENCAGE_KEY environment variable", {
withr::local_envvar(c("OPENCAGE_KEY" = key_200))
oc_config()
expect_equal(Sys.getenv("OPENCAGE_KEY"), key_200)
withr::local_envvar(c("OPENCAGE_KEY" = ""))
oc_config(key = key_200)
expect_equal(Sys.getenv("OPENCAGE_KEY"), key_200)
withr::local_envvar(c("OPENCAGE_KEY" = key_402))
oc_config(key = key_200)
expect_equal(Sys.getenv("OPENCAGE_KEY"), key_200)
})
test_that("oc_config requests key from terminal", {
skip_if_not_installed("mockery")
rlang::local_interactive(TRUE)
withr::local_envvar(c("OPENCAGE_KEY" = ""))
mockery::stub(
oc_config,
"readline",
key_200,
)
expect_message(
oc_config(key = ""),
"Please enter your OpenCage API key and press enter:"
)
expect_equal(Sys.getenv("OPENCAGE_KEY"), key_200)
})
test_that("oc_config throws error with faulty OpenCage key", {
withr::local_envvar(c("OPENCAGE_KEY" = ""))
expect_equal(Sys.getenv("OPENCAGE_KEY"), "")
expect_error(oc_config(key = ""), "set the environment variable OPENCAGE_KEY")
expect_error(
oc_config(key = "incomplete_key"),
"(OpenCage API key must be a )*.( string.)"
)
})
test_that("oc_config updates rate limit of oc_get_limit", {
withr::local_envvar(c("OPENCAGE_KEY" = key_200))
rps <- 5L
oc_config(rate_sec = rps)
expect_equal(ratelimitr::get_rates(oc_get_limited)[[1]][["n"]], rps)
rps <- 3L
oc_config(rate_sec = rps)
expect_equal(ratelimitr::get_rates(oc_get_limited)[[1]][["n"]], rps)
oc_config()
expect_equal(ratelimitr::get_rates(oc_get_limited)[[1]][["n"]], 1L)
})
test_that("oc_config sets no_record option", {
withr::local_envvar(c("OPENCAGE_KEY" = key_200))
withr::local_options(list(oc_no_record = NULL))
res <- oc_process("Hamburg", return = "url_only")
expect_match(res[[1]], "&no_record=1", fixed = TRUE)
oc_config()
expect_equal(getOption("oc_no_record"), TRUE)
res <- oc_process("Hamburg", return = "url_only")
expect_match(res[[1]], "&no_record=1", fixed = TRUE)
oc_config(no_record = FALSE)
expect_equal(getOption("oc_no_record"), FALSE)
res <- oc_process("Hamburg", return = "url_only")
expect_match(res[[1]], "&no_record=0", fixed = TRUE)
oc_config(no_record = TRUE)
expect_equal(getOption("oc_no_record"), TRUE)
res <- oc_process("Hamburg", return = "url_only")
expect_match(res[[1]], "&no_record=1", fixed = TRUE)
})
test_that("oc_config sets show_key option", {
withr::local_envvar(c("OPENCAGE_KEY" = key_200))
oc_config()
expect_equal(getOption("oc_show_key"), FALSE)
withr::local_envvar(c("OPENCAGE_KEY" = key_200))
oc_config(show_key = TRUE)
expect_equal(getOption("oc_show_key"), TRUE)
}) |
indtestHsic <- function(x,y,alpha=0.05, pars = list(method = "ExactFastTrace"))
{
if(is.matrix(x)==FALSE){
x<-as.matrix(x)}
if(is.matrix(y)==FALSE){
y<-as.matrix(y)}
len <- dim(x)[1]
xnorm<-as.matrix(dist(x,method="euclidean",diag=TRUE,upper=TRUE))
xnorm<-xnorm^2
ynorm<-as.matrix(dist(y,method="euclidean",diag=TRUE,upper=TRUE))
ynorm<-ynorm^2
if(len>1000)
{
sam <- sample(1:len,1000)
xhilf<-xnorm[sam,sam]
yhilf<-ynorm[sam,sam]
}
else
{
xhilf<-xnorm
yhilf<-ynorm
}
sigmax<-sqrt(0.5*median(xhilf[lower.tri(xhilf,diag=FALSE)]))
sigmay<-sqrt(0.5*median(yhilf[lower.tri(yhilf,diag=FALSE)]))
if(pars$method == "Exact" || pars$method == "ExactFastTrace")
{
ptm <- proc.time()
KX <- exp(-xnorm/(2*sigmax^2))
KY <- exp(-ynorm/(2*sigmay^2))
timeGramMat <- (proc.time() - ptm)[1]
if(pars$method == "Exact")
{
ptm <- proc.time()
H<-diag(1,len)-1/len*matrix(1,len,len)
HSIC <- 1/(len^2)*sum(diag(KX%*%H%*%KY%*%H))
timeHSIC <- (proc.time() - ptm)[1]
}
if(pars$method == "ExactFastTrace")
{
ptm <- proc.time()
H<-diag(1,len)-1/len*matrix(1,len,len)
HSIC <- 1/(len^2) * sum((KX - 1/len*(KX%*%rep(1,len))%*%t(rep(1,len)))*t(KY - 1/len*(KY%*%rep(1,len))%*%t(rep(1,len))))
timeHSIC <- (proc.time() - ptm)[1]
}
ptm <- proc.time()
mux <- (sum(KX)-len)/(len*(len-1))
muy <- (sum(KY)-len)/(len*(len-1))
mean_h0 <- 1/len*(1+mux*muy-mux-muy)
var_h0 <- (2*(len-4)*(len-5))/(len*(len-1)*(len-2)*(len-3)) * 1/((len-1)^2)*sum((KX - 1/len*(KX%*%rep(1,len))%*%t(rep(1,len)))*t(KX - 1/len*(KX%*%rep(1,len))%*%t(rep(1,len)))) * 1/((len-1)^2)*sum((KY - 1/len*(KY%*%rep(1,len))%*%t(rep(1,len)))*t(KY - 1/len*(KY%*%rep(1,len))%*%t(rep(1,len))))
timeGamma <- (proc.time() - ptm)[1]
}
if(pars$method == "IncChol" || pars$method == "IncCholFastTrace")
{
ptm <- proc.time()
LX <- kernlab::inchol(x, kernel="rbfdot", kpar=list(sigma=1/(2*sigmax^2)), tol = 0.0001, maxiter = 300)
LX <- matrix(LX,nrow=dim(LX)[1], ncol=dim(LX)[2])
LY <- kernlab::inchol(y, kernel="rbfdot", kpar=list(sigma=1/(2*sigmay^2)), tol = 0.0001, maxiter = 300)
LY <- matrix(LY,nrow=dim(LY)[1], ncol=dim(LY)[2])
LXc <- LX-1/len*(as.matrix(rep(1,len))%*%colSums(LX))
LYc <- LY-1/len*(as.matrix(rep(1,len))%*%colSums(LY))
timeGramMat <- (proc.time() - ptm)[1]
if(pars$method == "IncChol")
{
ptm <- proc.time()
HSIC <- 1/(len^2)*sum(diag((t(LX)%*%LYc)%*%(t(LY)%*%LXc)))
timeHSIC <- (proc.time() - ptm)[1]
}
if(pars$method == "IncCholFastTrace")
{
ptm <- proc.time()
HSIC <- 1/(len^2)*sum( (t(LX)%*%LYc) * t((t(LY)%*%LXc)))
timeHSIC <- (proc.time() - ptm)[1]
}
ptm <- proc.time()
mux <- (crossprod(colSums(LX))-len)/(len*(len-1))
muy <- (crossprod(colSums(LY))-len)/(len*(len-1))
mean_h0 <- 1/len*(1+mux*muy-mux-muy)
var_h0 <- (2*(len-4)*(len-5))/(len*(len-1)*(len-2)*(len-3))*1/((len-1)^2)*sum(diag((t(LX)%*%LXc)%*%(t(LX)%*%LXc)))*1/((len-1)^2)*sum(diag((t(LY)%*%LYc)%*%(t(LY)%*%LYc)))
timeGamma <- (proc.time() - ptm)[1]
}
a <- (mean_h0^2)/var_h0
b <- len*var_h0/mean_h0
critical_value <- qgamma(1-alpha,shape=a,scale=b)
p_value <- pgamma(len*HSIC,shape=a,scale=b, lower.tail=FALSE)
resu <- list(statistic = len*HSIC, crit.value = critical_value, p.value = p_value, time = c(timeGramMat,timeHSIC,timeGamma))
return(resu)
} |
NULL
selectionGet <- function(id = NULL) {
callFun("selectionGet", id = id)
}
selectionSet <- function(value = NULL, id = NULL) {
callFun("selectionSet", value = value, id = id)
} |
rOverlay = function(las, res, start = c(0,0), buffer = 0)
{
if (is(res, "RasterLayer"))
{
resolution <- raster::res(res)
if (round(resolution[1], 4) != round(resolution[2], 4))
stop("Rasters with different x y resolutions are not supported", call. = FALSE)
return(raster::raster(res))
}
bbox <- raster::extent(las) + 2 * buffer
bbox@xmin <- round_any(bbox@xmin - 0.5 * res - start[1], res) + start[1]
bbox@xmax <- round_any(bbox@xmax - 0.5 * res - start[1], res) + res + start[1]
bbox@ymin <- round_any(bbox@ymin - 0.5 * res - start[2], res) + start[2]
bbox@ymax <- round_any(bbox@ymax - 0.5 * res - start[2], res) + res + start[2]
layout <- suppressWarnings(raster::raster(bbox, res = res, crs = las@proj4string))
layout@data@values <- rep(NA, raster::ncell(layout))
raster::crs(layout) <- raster::crs(las)
return(layout)
}
rMergeList = function(raster_list)
{
if (length(raster_list) == 1)
return(raster_list)
names <- names(raster_list[[1]])
factor <- raster_list[[1]]@data@isfactor
issingle <- sapply(raster_list, function(x) { raster::nrow(x) == 1 & raster::ncol(x) == 1 })
single <- list()
if (any(issingle))
{
single <- raster_list[issingle]
raster_list <- raster_list[!issingle]
}
raster <- do.call(raster::merge, raster_list)
names(raster) <- names
if (is(raster, "RasterBrick") && raster::inMemory(raster))
colnames(raster@data@values) <- names
for (pixel in single)
{
pix = raster::rasterToPoints(pixel, spatial = TRUE)
raster[pix] <- as.matrix(pix@data)
}
raster::crs(raster) <- raster::crs(raster_list[[1]])
return(raster)
}
rBuildVRT = function(file_list, vrt)
{
if (!options("lidR.buildVRT")[[1]])
return(unlist(file_list))
file_list <- unlist(file_list)
layers <- names(raster::stack(file_list[1]))
folder <- dirname(file_list[1])
file <- paste0("/", vrt, ".vrt")
vrt <- paste0(folder, file)
sf::gdal_utils("buildvrt", source = file_list, destination = vrt, quiet = TRUE)
if (!file.exists(vrt)) return(unlist(file_list))
file_list <- raster::brick(vrt)
names(file_list) <- layers
if (dim(file_list)[3] == 1)
return(file_list[[1]])
else
return(file_list)
}
match_chm_and_seeds = function(chm, seeds, field)
{
assert_is_all_of(chm, "RasterLayer")
assert_is_all_of(seeds, "SpatialPointsDataFrame")
stopif_forbidden_name(field)
null = list(cells = integer(), ids = numeric())
if (is.null(raster::intersect(raster::extent(chm), raster::extent(seeds))))
{
warning("No tree can be used as seed: canopy height model and tree tops extents do not overlap.", call. = FALSE)
return(null)
}
if (field %in% names(seeds@data))
{
ids <- seeds@data[[field]]
if (!is.numeric(ids))
stop("Tree IDs much be of a numeric type", call. = FALSE)
if (length(unique(ids)) < length(ids))
stop("Duplicated tree IDs found.", call. = FALSE)
}
else
ids <- 1:nrow(seeds@data)
cells <- raster::cellFromXY(chm, seeds)
if (anyNA(cells))
{
if (all(is.na(cells)))
{
warning("No tree can be used as seed: all tree tops are outside the CHM", call. = FALSE)
return(null)
}
else
{
warning("Some trees are outside the canopy height model: they can't be used as seeds", call. = FALSE)
}
no_na = !is.na(cells)
seeds = seeds[no_na,]
cells = cells[no_na]
}
return(list(cells = cells, ids = ids))
}
raster2dataframe = function(x, xy = FALSE, na.rm = FALSE, fast = FALSE)
{
if (!fast) return(raster::as.data.frame(x, xy = xy, na.rm = na.rm))
v <- raster::getValues(x)
if (xy) {
XY <- data.frame(raster::xyFromCell(x, 1:raster::ncell(x)))
v <- cbind(XY, v)
}
if (na.rm)
v <- stats::na.omit(cbind(1:raster::ncell(x), v))
v <- as.data.frame(v)
if (na.rm) {
rownames(v) <- as.character(v[,1])
v <- v[,-1,drop=FALSE]
}
if (raster::nlayers(x) == 1)
colnames(v)[ncol(v)] <- names(x)
return(v)
} |
NULL
stochastic_matrix <- function(graph, column.wise=FALSE,
sparse=igraph_opt("sparsematrices")) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
column.wise <- as.logical(column.wise)
if (length(column.wise) != 1) {
stop("`column.wise' must be a logical scalar")
}
sparse <- as.logical(sparse)
if (length(sparse) != 1) {
stop("`sparse' must be a logical scalar")
}
on.exit(.Call(C_R_igraph_finalizer))
if (sparse) {
res <- .Call(C_R_igraph_get_stochastic_sparsemat, graph, column.wise)
res <- igraph.i.spMatrix(res)
} else {
res <- .Call(C_R_igraph_get_stochastic, graph, column.wise)
}
if (igraph_opt("add.vertex.names") && is_named(graph)) {
rownames(res) <- colnames(res) <- V(graph)$name
}
res
}
scg_group <- function(V, nt,
mtype=c("symmetric", "laplacian",
"stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"),
p=NULL, maxiter=100) {
V <- as.matrix(structure(as.double(V), dim=dim(V)))
groups <- as.numeric(nt)
mtype <- switch(igraph.match.arg(mtype), "symmetric"=1,
"laplacian"=2, "stochastic"=3)
algo <- switch(igraph.match.arg(algo), "optimum"=1,
"interv_km"=2, "interv"=3, "exact_scg"=4)
if (!is.null(p)) p <- as.numeric(p)
maxiter <- as.integer(maxiter)
on.exit( .Call(C_R_igraph_finalizer) )
res <- .Call(C_R_igraph_scg_grouping, V, as.integer(nt[1]),
if (length(nt)==1) NULL else nt,
mtype, algo, p, maxiter)
res
}
scg_semi_proj <- function(groups,
mtype=c("symmetric", "laplacian",
"stochastic"), p=NULL,
norm=c("row", "col"),
sparse=igraph_opt("sparsematrices")) {
groups <- as.numeric(groups)-1
mtype <- switch(igraph.match.arg(mtype), "symmetric"=1,
"laplacian"=2, "stochastic"=3)
if (!is.null(p)) p <- as.numeric(p)
norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2)
sparse <- as.logical(sparse)
on.exit( .Call(C_R_igraph_finalizer) )
res <- .Call(C_R_igraph_scg_semiprojectors, groups, mtype, p, norm,
sparse)
if (sparse) {
res$L <- igraph.i.spMatrix(res$L)
res$R <- igraph.i.spMatrix(res$R)
}
res
}
scg <- function(X, ev, nt, groups=NULL,
mtype=c("symmetric", "laplacian", "stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"), norm=c("row", "col"),
direction=c("default", "left", "right"),
evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300,
sparse=igraph_opt("sparsematrices"),
output=c("default", "matrix", "graph"), semproj=FALSE,
epairs=FALSE, stat.prob=FALSE)
UseMethod("scg")
scg.igraph <- function(X, ev, nt, groups=NULL,
mtype=c("symmetric", "laplacian", "stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"), norm=c("row", "col"),
direction=c("default", "left", "right"),
evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300,
sparse=igraph_opt("sparsematrices"),
output=c("default", "matrix", "graph"), semproj=FALSE,
epairs=FALSE, stat.prob=FALSE) {
myscg(graph=X, matrix=NULL, sparsemat=NULL, ev=ev, nt=nt,
groups=groups, mtype=mtype, algo=algo,
norm=norm, direction=direction, evec=evec, p=p,
use.arpack=use.arpack, maxiter=maxiter, sparse=sparse,
output=output, semproj=semproj, epairs=epairs,
stat.prob=stat.prob)
}
scg.matrix <- function(X, ev, nt, groups=NULL,
mtype=c("symmetric", "laplacian", "stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"), norm=c("row", "col"),
direction=c("default", "left", "right"),
evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300,
sparse=igraph_opt("sparsematrices"),
output=c("default", "matrix", "graph"), semproj=FALSE,
epairs=FALSE, stat.prob=FALSE) {
myscg(graph=NULL, matrix=X, sparsemat=NULL, ev=ev, nt=nt,
groups=groups, mtype=mtype, algo=algo,
norm=norm, direction=direction, evec=evec, p=p,
use.arpack=use.arpack, maxiter=maxiter, sparse=sparse,
output=output, semproj=semproj, epairs=epairs,
stat.prob=stat.prob)
}
scg.Matrix <- function(X, ev, nt, groups=NULL,
mtype=c("symmetric", "laplacian", "stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"), norm=c("row", "col"),
direction=c("default", "left", "right"),
evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300,
sparse=igraph_opt("sparsematrices"),
output=c("default", "matrix", "graph"), semproj=FALSE,
epairs=FALSE, stat.prob=FALSE) {
myscg(graph=NULL, matrix=NULL, sparsemat=X, ev=ev, nt=nt,
groups=groups, mtype=mtype, algo=algo,
norm=norm, direction=direction, evec=evec, p=p,
use.arpack=use.arpack, maxiter=maxiter, sparse=sparse,
output=output, semproj=semproj, epairs=epairs,
stat.prob=stat.prob)
}
myscg <- function(graph, matrix, sparsemat, ev, nt, groups=NULL,
mtype=c("symmetric", "laplacian", "stochastic"),
algo=c("optimum", "interv_km", "interv",
"exact_scg"), norm=c("row", "col"),
direction=c("default", "left", "right"),
evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300,
sparse=igraph_opt("sparsematrices"),
output=c("default", "matrix", "graph"), semproj=FALSE,
epairs=FALSE, stat.prob=FALSE) {
if (!is.null(graph)) { stopifnot(is_igraph(graph)) }
if (!is.null(matrix)) { stopifnot(is.matrix(matrix)) }
if (!is.null(sparsemat)) { stopifnot(inherits(sparsemat, "Matrix")) }
if (!is.null(sparsemat)) { sparsemat <- as(sparsemat, "dgCMatrix") }
ev <- as.numeric(as.integer(ev))
nt <- as.numeric(as.integer(nt))
if (!is.null(groups)) groups <- as.numeric(groups)
mtype <- igraph.match.arg(mtype)
algo <- switch(igraph.match.arg(algo), "optimum"=1,
"interv_km"=2, "interv"=3, "exact_scg"=4)
if (!is.null(groups)) { storage.mode(groups) <- "double" }
use.arpack <- as.logical(use.arpack)
maxiter <- as.integer(maxiter)
sparse <- as.logical(sparse)
output <- switch(igraph.match.arg(output), "default"=1, "matrix"=2,
"graph"=3)
semproj <- as.logical(semproj)
epairs <- as.logical(epairs)
on.exit( .Call(C_R_igraph_finalizer) )
if (mtype=="symmetric") {
if (!is.null(evec)) { storage.mode(evec) <- "double" }
res <- .Call(C_R_igraph_scg_adjacency, graph, matrix, sparsemat, ev,
nt, algo, evec, groups,
use.arpack, maxiter, sparse, output, semproj, epairs)
} else if (mtype=="laplacian") {
norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2)
if (!is.null(evec)) { storage.mode(evec) <- "complex" }
direction <- switch(igraph.match.arg(direction), "default"=1, "left"=2,
"right"=3)
res <- .Call(C_R_igraph_scg_laplacian, graph, matrix, sparsemat, ev,
nt, algo, norm, direction,
evec, groups, use.arpack, maxiter, sparse, output,
semproj, epairs)
} else if (mtype=="stochastic") {
norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2)
if (!is.null(evec)) { storage.mode(evec) <- "complex" }
if (!is.null(p)) { storage.mode(p) <- "double" }
stat.prob <- as.logical(stat.prob)
res <- .Call(C_R_igraph_scg_stochastic, graph, matrix, sparsemat, ev,
nt, algo, norm, evec, groups, p, use.arpack,
maxiter, sparse, output, semproj, epairs, stat.prob)
}
if (!is.null(res$Xt) &&
class(res$Xt) == "igraph.tmp.sparse") {
res$Xt <- igraph.i.spMatrix(res$Xt)
}
if (!is.null(res$L) && class(res$L) == "igraph.tmp.sparse") {
res$L <- igraph.i.spMatrix(res$L)
}
if (!is.null(res$R) && class(res$R) == "igraph.tmp.sparse") {
res$R <- igraph.i.spMatrix(res$R)
}
res
}
scg_eps <- scg_eps |