code
stringlengths 1
13.8M
|
---|
weighted_mannwhitney <- function(data, ...) {
UseMethod("weighted_mannwhitney")
}
weighted_mannwhitney.default <- function(data, x, grp, weights, ...) {
x.name <- deparse(substitute(x))
g.name <- deparse(substitute(grp))
w.name <- deparse(substitute(weights))
vars <- c(x.name, g.name, w.name)
dat <- suppressMessages(dplyr::select(data, !! vars))
dat <- na.omit(dat)
weighted_mannwhitney_helper(dat)
}
weighted_mannwhitney.formula <- function(formula, data, ...) {
vars <- all.vars(formula)
dat <- suppressMessages(dplyr::select(data, !! vars))
dat <- na.omit(dat)
weighted_mannwhitney_helper(dat)
}
weighted_mannwhitney_helper <- function(dat, vars) {
if (!requireNamespace("survey", quietly = TRUE)) {
stop("Package `survey` needed to for this function to work. Please install it.", call. = FALSE)
}
x.name <- colnames(dat)[1]
group.name <- colnames(dat)[2]
colnames(dat) <- c("x", "g", "w")
if (dplyr::n_distinct(dat$g, na.rm = TRUE) > 2) {
m <- "Weighted Kruskal-Wallis test"
method <- "KruskalWallis"
} else {
m <- "Weighted Mann-Whitney-U test"
method <- "wilcoxon"
}
design <- survey::svydesign(ids = ~0, data = dat, weights = ~w)
mw <- survey::svyranktest(formula = x ~ g, design, test = method)
attr(mw, "x.name") <- x.name
attr(mw, "group.name") <- group.name
class(mw) <- c("sj_wmwu", "list")
mw$method <- m
mw
}
|
orient_rpi = function(file, verbose = TRUE){
L = orient_rpi_file(file = file, verbose = verbose)
L$img = check_nifti(L$img)
return(L)
}
orient_rpi_file = function(file, verbose = TRUE){
file = checkimg(file)
img = RNifti::readNifti(file)
sorient = RNifti::orientation(img)
RNifti::orientation(img) = "LAS"
outfile = tempfile(fileext = ".nii.gz")
RNifti::writeNifti(img, file = outfile)
L = list(img = outfile,
orientation = sorient)
return(L)
}
reverse_orient_rpi = function(
file,
convention = c("NEUROLOGICAL", "RADIOLOGICAL"),
orientation, verbose = TRUE){
img = reverse_orient_rpi_file(file = file,
orientation = orientation,
verbose = verbose)
img = check_nifti(img)
return(img)
}
reverse_orient_rpi_file = function(
file,
convention = c("NEUROLOGICAL", "RADIOLOGICAL"),
orientation,
verbose = TRUE){
file = checkimg(file)
stopifnot(nchar(orientation) == 3)
img = RNifti::readNifti(file)
RNifti::orientation(img) = orientation
outfile = tempfile(fileext = ".nii.gz")
RNifti::writeNifti(img, file = outfile)
return(outfile)
}
is_rpi_oriented = function(file, verbose = FALSE) {
img = RNifti::asNifti(file)
res = RNifti::orientation(img) == "LAS"
return(res)
}
|
"daystoyears" <-
function (x, datemin=NULL, dateformat="m/d/Y") {
x <- x
datemin <- datemin
defyearorig <- 1970
if (length(datemin) > 0 && !any(class(datemin) == "POSIXt")) {
dateformat <- sub("month", "%B", dateformat)
dateformat <- sub("mon", "%b", dateformat)
dateformat <- sub("m", "%m", dateformat)
dateformat <- sub("d", "%d", dateformat)
dateformat <- sub("y", "%y", dateformat)
dateformat <- sub("Y", "%Y", dateformat)
datemin <- strptime(as.character(datemin), format=dateformat)
}
"Julian" <- function(x, d, y) {
if(is.null(origin. <- getOption("chron.origin")))
origin. <- c(month = 1, day = 1, year = 1970)
m <- c(origin.[1], x)
d <- c(origin.[2], d)
y <- c(origin.[3], y)
y <- y + ifelse(m > 2, 0, -1)
m <- m + ifelse(m > 2, -3, 9)
c <- y %/% 100
ya <- y - 100 * c
out <- ((146097 * c) %/% 4 + (1461 * ya) %/% 4 + (153 * m + 2) %/% 5 + d + 1721119)
if(all(origin. == 0))
out <- out[-1]
else
out <- out[-1] - out[1]
out
}
if (length(datemin) > 0) {
dateminval <- Julian(datemin$mon+1, datemin$mday, datemin$year+1900)
x <- x - trunc(min(x, na.rm=TRUE)) + dateminval
}
if(is.null(yearorig <- options("chron.origin")$year))
yearorig <- defyearorig
x <- x/365.25 + yearorig
x
}
|
VERSION <- "2.7.4"
if(!file.exists(sprintf("../windows/harfbuzz-%s/include/png.h", VERSION))){
if(getRversion() < "3.3.0") setInternet2()
download.file(sprintf("https://github.com/rwinlib/harfbuzz/archive/v%s.zip", VERSION), "lib.zip", quiet = TRUE)
dir.create("../windows", showWarnings = FALSE)
unzip("lib.zip", exdir = "../windows")
unlink("lib.zip")
}
|
knitr::opts_chunk$set(
cache = TRUE,
collapse = TRUE,
comment = "
)
load(file.path("..", "R", "sysdata.rda"))
estimators <- unique(results.normal$estimator)
par(mfrow = c(3, 1))
for (i in seq_along(estimators)) {
inds <- which(results.normal[, "estimator"] == estimators[i])
p.value <- results.normal[inds, "size"]
std.err <- results.normal[inds, "std.error"]
x <- 1:length(inds)
m <- results.normal[inds, "m"]
n <- results.normal[inds, "n"]
cols <- c("black", "red", "green")
if (i == 1) {
plot(x, p.value,
ylim = c(0, 0.18),
xlab = "Sample sizes",
ylab = "Size of the test",
main = "N(0, 1)-distribution",
col = cols[i],
xaxt = "n",
yaxt = "n"
)
axis(side = 1, at = 1:10, labels = unique(paste0("(", m, ", ", n, ")")))
axis(side = 2, at = seq(0.025, 0.175, by = 0.025), labels = c("", "0.05", "", "0.1", "", "0.15", ""))
} else {
points(x, p.value,
col = cols[i],
)
}
abline(h = 0.05, lty = "dashed")
}
for (i in seq_along(estimators)) {
inds <- which(results.t[, "estimator"] == estimators[i])
p.value <- results.t[inds, "size"]
std.err <- results.t[inds, "std.error"]
x <- 1:length(inds)
m <- results.t[inds, "m"]
n <- results.t[inds, "n"]
cols <- c("black", "red", "green")
if (i == 1) {
plot(x, p.value,
ylim = c(0, 0.18),
xlab = "Sample sizes",
ylab = "Size of the test",
main = "t(2)-distribution",
col = cols[i],
xaxt = "n",
yaxt = "n"
)
axis(side = 1, at = 1:10, labels = unique(paste0("(", m, ", ", n, ")")))
axis(side = 2, at = seq(0.025, 0.175, by = 0.025), labels = c("", "0.05", "", "0.1", "", "0.15", ""))
} else {
points(x, p.value,
col = cols[i],
)
}
abline(h = 0.05, lty = "dashed")
}
for (i in seq_along(estimators)) {
inds <- which(results.chi[, "estimator"] == estimators[i])
p.value <- results.chi[inds, "size"]
std.err <- results.chi[inds, "std.error"]
x <- 1:length(inds)
m <- results.chi[inds, "m"]
n <- results.chi[inds, "n"]
cols <- c("black", "red", "green")
if (i == 1) {
plot(x, p.value,
ylim = c(0, 0.18),
xlab = "Sample sizes",
ylab = "Size of the test",
main = "Chi^2(3)-distribution",
col = cols[i],
xaxt = "n",
yaxt = "n"
)
axis(side = 1, at = 1:10, labels = unique(paste0("(", m, ", ", n, ")")))
axis(side = 2, at = seq(0.025, 0.175, by = 0.025), labels = c("", "0.05", "", "0.1", "", "0.15", ""))
} else {
points(x, p.value,
col = cols[i],
)
}
legend("bottomleft", legend = c("Huber", "Hampel", "Bisquare"), col = 1:3, pch = 1)
abline(h = 0.05, lty = "dashed")
}
library(robnptests)
sessionInfo()
|
"SMR.clean"
|
convert_BPFCollection <- function(sourceDir,
targetDir,
dbName,
bpfExt = 'par',
audioExt = 'wav',
extractLevels = NULL,
refLevel = NULL,
newLevels = NULL,
newLevelClasses = NULL,
segmentToEventLevels = NULL,
unifyLevels = NULL,
verbose = TRUE)
{
sourceDir = suppressWarnings(normalizePath(sourceDir))
targetDir = suppressWarnings(normalizePath(targetDir))
basePath = file.path(targetDir, paste0(dbName, emuDB.suffix))
res = try(suppressWarnings(dir.create(targetDir)))
if(class(res) == "try-error")
{
stop("Could not create target directory ", targetDir)
}
check_bpfArgumentWithoutLevelClasses(sourceDir = sourceDir,
basePath = basePath,
newLevels = newLevels,
newLevelClasses = newLevelClasses,
standardLevels = BPF_STANDARD_LEVELS,
verbose = verbose,
refLevel = refLevel,
audioExt = audioExt,
extractLevels = extractLevels)
levelClasses = as.list(BPF_STANDARD_LEVEL_CLASSES)
names(levelClasses) = BPF_STANDARD_LEVELS
levelClasses[newLevels] = newLevelClasses
check_bpfArgumentWithLevelClasses(unifyLevels = unifyLevels,
refLevel = refLevel,
extractLevels = extractLevels,
levelClasses = levelClasses,
segmentToEventLevels)
filePairList = create_filePairList(sourceDir,
sourceDir,
bpfExt,
audioExt)
dbHandle = emuDBhandle(dbName, basePath = basePath, uuid::UUIDgenerate(), ":memory:")
queryTxt = paste0("INSERT INTO emu_db (uuid, name) VALUES('", dbHandle$UUID, "', '", dbName,"')")
DBI::dbExecute(dbHandle$connection, queryTxt)
if(verbose)
{
progress = 0
nbFilePairs = length(filePairList) / 2
cat("INFO: Parsing BPF collection containing", nbFilePairs, "file pair(s)...\n")
pb = utils::txtProgressBar(min = 0, max = nbFilePairs, initial = progress, style=3)
utils::setTxtProgressBar(pb, progress)
}
levelTracker = list()
linkTracker = list()
warningsTracker = list(semicolonFound = list())
for(idx in 1:nrow(filePairList)[1])
{
session = get_bpfSession(filePath = filePairList[idx, 1],
sourceDir = sourceDir)
bpfPath = normalizePath(filePairList[idx, 1], winslash = .Platform$file.sep)
bundle = sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(bpfPath))
annotates = basename(filePairList[idx, 2])
session = stringr::str_replace_all(session, "'", "''")
bundle = stringr::str_replace_all(bundle, "'", "''")
annotates = stringr::str_replace_all(annotates, "'", "''")
asspObj = wrassp::read.AsspDataObj(filePairList[idx, 2])
samplerate = attributes(asspObj)$sampleRate
queryTxt = paste0("SELECT name from session WHERE name='", session, "'")
all_sessions = DBI::dbGetQuery(dbHandle$connection, queryTxt)
if(!session %in% all_sessions)
{
queryTxt = paste0("INSERT INTO session VALUES('", dbHandle$UUID, "', '", session, "')")
DBI::dbExecute(dbHandle$connection, queryTxt)
}
queryTxt = paste0("INSERT INTO bundle VALUES('", dbHandle$UUID, "', '", session, "', '", bundle, "', '",
annotates, "', ", samplerate, ", 'NULL')")
DBI::dbExecute(dbHandle$connection, queryTxt)
returnContainer = parse_BPF(dbHandle,
bpfPath = bpfPath,
bundle = bundle,
session = session,
refLevel = refLevel,
extractLevels = extractLevels,
samplerate = samplerate,
segmentToEventLevels = segmentToEventLevels,
levelClasses = levelClasses,
unifyLevels = unifyLevels)
levelInfo = returnContainer$levelInfo
linkInfo = returnContainer$linkInfo
semicolonFound = returnContainer$semicolonFound
if(semicolonFound)
{
warningsTracker$semicolonFound[[length(warningsTracker$semicolonFound) + 1L]] = bpfPath
}
if(length(levelInfo) > 0)
{
levelTracker = update_bpfLevelTracker(levelInfo = levelInfo,
levelTracker = levelTracker)
}
if(length(linkInfo) > 0)
{
linkTracker = update_bpfLinkTracker(linkInfo = linkInfo,
linkTracker = linkTracker)
}
if(verbose)
{
utils::setTxtProgressBar(pb, idx)
}
}
if(verbose)
{
cat("\n")
cat("INFO: Doing some post-processing...\n")
}
if(length(linkTracker) > 0)
{
linkTracker = link_bpfDisambiguation(dbHandle, linkTracker = linkTracker,
refLevel = refLevel)
}
if(!is.null(refLevel))
{
linkTracker = link_bpfUtteranceLevel(dbHandle, linkTracker = linkTracker,
refLevel = refLevel)
}
if(verbose)
{
cat("INFO: Creating EMU database config schema...\n")
}
DBconfig = create_bpfSchema(levelTracker = levelTracker,
linkTracker = linkTracker,
dbName = dbName,
dbUUID = dbHandle$UUID,
audioExt = audioExt)
res = try(dir.create(basePath))
if(class(res) == "try-error")
{
stop("Could not create directory ", basePath)
}
store_DBconfig(dbHandle, DBconfig)
make_bpfDbSkeleton(dbHandle)
copy_bpfMediaFiles(basePath = basePath,
sourceDir = sourceDir,
mediaFiles = filePairList[,2],
verbose = verbose)
rewrite_annots(dbHandle, verbose = verbose)
if(verbose)
{
display_bpfSemicolonWarnings(warningsTracker)
}
}
copy_bpfMediaFiles <- function(basePath,
mediaFiles,
sourceDir,
verbose)
{
if(verbose)
{
progress = 0
nbMediaFiles = length(mediaFiles)
cat("INFO: Copying", nbMediaFiles, "media files to EMU database...\n")
pb = utils::txtProgressBar(min = 0, max = nbMediaFiles, initial = progress, style=3)
utils::setTxtProgressBar(pb, progress)
}
for(idx in 1:length(mediaFiles))
{
targetDir = file.path(basePath,
paste0(get_bpfSession(filePath = mediaFiles[[idx]],
sourceDir = sourceDir),
session.suffix),
paste0(sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(mediaFiles[[idx]])),
bundle.dir.suffix)
)
res = try(file.copy(mediaFiles[[idx]], targetDir))
if(class(res) == "try-error")
{
stop("Could not copy media file from ", mediaFiles[[idx]], " to ", targetDir)
}
if(verbose)
{
utils::setTxtProgressBar(pb, idx)
}
}
if(verbose)
{
cat("\n")
}
}
get_bpfSession <- function(filePath,
sourceDir)
{
DEFAULT_SESSION_NAME = "0000"
session = normalizePath(dirname(filePath), winslash = "/")
sourceDir = normalizePath(sourceDir, winslash = "/")
sourceDir = stringr::str_replace(sourceDir, "/$", "")
session = stringr::str_replace_all(session, sourceDir, "")
session = stringr::str_replace_all(session, .Platform$file.sep, "_")
session = stringr::str_replace_all(session, "^_", "")
if(session == "")
{
session = DEFAULT_SESSION_NAME
}
return(session)
}
check_bpfArgumentWithoutLevelClasses <- function(sourceDir,
basePath,
newLevels,
newLevelClasses,
standardLevels,
verbose,
refLevel,
audioExt,
extractLevels)
{
if(!file.exists(sourceDir))
{
stop("Source directory does not exist!")
}
if(file.exists(basePath))
{
stop('The directory ', basePath, ' already exists. Can not generate a new emuDB here.')
}
if(length(newLevels) != length(newLevelClasses))
{
stop("Length of newLevels and newLevelClasses must be identical.")
}
if(!all(newLevelClasses %in% c(1,2,3,4,5)))
{
stop("Level classes must be integers between 1 and 5. See BPF specifications for details.")
}
if(any(newLevels %in% standardLevels))
{
stop("You cannot introduce a standard BPF level via the newLevels argument. ",
"Standard BPF levels are: '", paste(standardLevels, collapse = "', '"), "'")
}
if(is.null(refLevel) && verbose)
{
ans = readline("WARNING: No reference level has been declared. EMU database will be built without any symbolic links. Do you wish to continue? (y/n)")
if(!ans == "y")
{
stop("BPF converter interrupted.")
}
}
if(!is.null(extractLevels))
{
if(!is.null(refLevel))
{
if(!refLevel %in% extractLevels)
{
stop("Reference level is not in extractLevels")
}
}
}
}
check_bpfArgumentWithLevelClasses <- function(unifyLevels,
refLevel,
extractLevels,
levelClasses,
segmentToEventLevels)
{
for(level in c(unifyLevels, refLevel, extractLevels))
{
if(!level %in% names(levelClasses))
{
stop("Unknown level: ", level, ". If this is not a standard BPF level you need to declare this level via the newLevels argument, and assign it a class via the newLevelClasses argument")
}
}
if(!is.null(refLevel))
{
if(levelClasses[[refLevel]] %in% c(2, 3))
{
stop("Link-less level ", refLevel, " cannot be reference level.")
}
}
if(!is.null(unifyLevels))
{
if(is.null(refLevel))
{
stop("If you want to unify levels with the reference level, you must declare a reference level.")
}
if(refLevel %in% unifyLevels)
{
stop("Reference level cannot be unified with itself.")
}
if(any(levelClasses[unifyLevels] != 1))
{
stop("Levels to be unified with the reference level must be of class 1 (time-less).")
}
}
if(any(!levelClasses[segmentToEventLevels] %in% c(2,4)))
{
stop("Only segment levels (classes 2 and 4) can be listed in segmentToEventLevels.")
}
}
update_bpfLevelTracker <- function(levelInfo,
levelTracker)
{
for(idx in 1:length(levelInfo))
{
found = FALSE
if(length(levelTracker) > 0)
{
for(jdx in 1:length(levelTracker))
{
if(levelTracker[[jdx]][["key"]] == levelInfo[[idx]][["key"]] &&
levelTracker[[jdx]][["type"]] == levelInfo[[idx]][["type"]])
{
for(label in levelInfo[[idx]][["labels"]])
{
if(!label %in% levelTracker[[jdx]][["labels"]])
{
levelTracker[[jdx]][["labels"]][[length(levelTracker[[jdx]][["labels"]]) + 1L]] = label
}
}
found = TRUE
break
}
}
}
if(!found)
{
levelTracker[[length(levelTracker) + 1L]] = levelInfo[[idx]]
}
}
return(levelTracker)
}
update_bpfLinkTracker <- function(linkTracker,
linkInfo)
{
for(jdx in 1:length(linkInfo))
{
found = FALSE
if(length(linkTracker) > 0)
{
for(kdx in 1:length(linkTracker))
{
if(linkTracker[[kdx]][["fromkey"]] == linkInfo[[jdx]][["fromkey"]] &&
linkTracker[[kdx]][["tokey"]] == linkInfo[[jdx]][["tokey"]] &&
linkTracker[[kdx]][["type"]] == linkInfo[[jdx]][["type"]])
{
found = TRUE
linkTracker[[kdx]][["countRight"]] = linkTracker[[kdx]][["countRight"]] + linkInfo[[jdx]][["countRight"]]
linkTracker[[kdx]][["countWrong"]] = linkTracker[[kdx]][["countWrong"]] + linkInfo[[jdx]][["countWrong"]]
break
}
}
}
if(!found)
{
linkTracker[[length(linkTracker) + 1L]] = linkInfo[[jdx]]
}
}
return(linkTracker)
}
link_bpfDisambiguation <- function(emuDBhandle, linkTracker,
refLevel)
{
turnAround = get_bpfTurnAround(linkTracker = linkTracker)
for(idx in 1:length(linkTracker))
{
linkTracker[[idx]][["countRight"]] = NA
linkTracker[[idx]][["countWrong"]] = NA
}
if(length(turnAround) > 0)
{
turn_bpfLinks(emuDBhandle, turnAround = turnAround)
linkTracker = turn_bpfLinkTrackerEntries(turnAround = turnAround,
linkTracker = linkTracker)
}
linkTracker = merge_bpfLinkTypes(linkTracker = linkTracker)
return(linkTracker)
}
get_bpfTurnAround <- function(linkTracker)
{
turnAround = list()
for(idx in 1:length(linkTracker))
{
turnAroundNecessary = FALSE
countRight = 0
countWrong = 0
for(jdx in 1:length(linkTracker))
{
if(linkTracker[[idx]][["fromkey"]] == linkTracker[[jdx]][["fromkey"]] &&
linkTracker[[idx]][["tokey"]] == linkTracker[[jdx]][["tokey"]])
{
countRight = countRight + linkTracker[[jdx]][["countRight"]]
countWrong = countWrong + linkTracker[[jdx]][["countWrong"]]
}
else if(linkTracker[[idx]][["fromkey"]] == linkTracker[[jdx]][["tokey"]] &&
linkTracker[[idx]][["tokey"]] == linkTracker[[jdx]][["fromkey"]])
{
countRight = countRight + linkTracker[[jdx]][["countWrong"]]
countWrong = countWrong + linkTracker[[jdx]][["countRight"]]
turnAroundNecessary = TRUE
}
}
if(turnAroundNecessary)
{
if(countRight > countWrong)
{
turnAround[[length(turnAround) + 1L]] =
list(fromkey = linkTracker[[idx]][["tokey"]], tokey = linkTracker[[idx]][["fromkey"]])
}
else if(countRight < countWrong)
{
turnAround[[length(turnAround) + 1L]] =
list(fromkey = linkTracker[[idx]][["fromkey"]], tokey = linkTracker[[idx]][["tokey"]])
}
else if(countRight == countWrong)
{
found = FALSE
for(link in turnAround)
{
if(link$fromkey == linkTracker[[idx]][["tokey"]] && link$tokey == linkTracker[[idx]][["fromkey"]])
{
found = TRUE
break
}
}
if(!found)
{
turnAround[[length(turnAround) + 1L]] =
list(fromkey = linkTracker[[idx]][["fromkey"]], tokey = linkTracker[[idx]][["tokey"]])
}
}
}
}
turnAround = unique(turnAround)
return(turnAround)
}
turn_bpfLinks <- function(emuDBhandle, turnAround)
{
for(link in turnAround)
{
queryTxt = paste0("UPDATE links SET from_id = to_id, to_id = from_id WHERE from_id IN",
"(SELECT item_id FROM items WHERE level = '", link[["fromkey"]],
"' AND db_uuid = links.db_uuid AND session = links.session AND bundle = links.bundle) ",
"AND to_id IN(SELECT item_id FROM items WHERE level = '", link[["tokey"]], "' ",
"AND db_uuid = links.db_uuid AND session = links.session AND bundle = links.bundle);")
DBI::dbExecute(emuDBhandle$connection, queryTxt)
}
}
turn_bpfLinkTrackerEntries <- function(turnAround = turnAround,
linkTracker = linkTracker)
{
for(idx in 1:length(turnAround))
{
for(jdx in 1:length(linkTracker))
{
if(turnAround[[idx]][["fromkey"]] == linkTracker[[jdx]][["fromkey"]] &&
turnAround[[idx]][["tokey"]] == linkTracker[[jdx]][["tokey"]])
{
linkTracker[[jdx]][["fromkey"]] = turnAround[[idx]][["tokey"]]
linkTracker[[jdx]][["tokey"]] = turnAround[[idx]][["fromkey"]]
if(linkTracker[[jdx]][["type"]] == "ONE_TO_MANY")
{
linkTracker[[jdx]][["type"]] = "MANY_TO_MANY"
}
}
}
}
return(linkTracker)
}
merge_bpfLinkTypes <- function(linkTracker)
{
for(idx in 1:length(linkTracker))
{
for(jdx in 1:length(linkTracker))
{
if(linkTracker[[idx]][["fromkey"]] == linkTracker[[jdx]][["fromkey"]] &&
linkTracker[[idx]][["tokey"]] == linkTracker[[jdx]][["tokey"]])
{
if(linkTracker[[idx]][["type"]] %in% c("ONE_TO_ONE", "ONE_TO_MANY") &&
linkTracker[[jdx]][["type"]] %in% c("ONE_TO_MANY", "MANY_TO_MANY"))
{
linkTracker[[idx]][["type"]] = linkTracker[[jdx]][["type"]]
}
}
}
}
linkTracker = unique(linkTracker)
return(linkTracker)
}
link_bpfUtteranceLevel <- function(emuDBhandle, linkTracker,
refLevel)
{
underUtterance = get_bpfLevelsUnderUtterance(linkTracker = linkTracker,
refLevel = refLevel)
for(level in underUtterance)
{
nbItems = link_bpfUtteranceLevelToCurrentLevel(emuDBhandle, currentLevel = level)
queryTxt = paste0("SELECT DISTINCT db_uuid, session, bundle FROM items WHERE level = '", level, "'")
distinctUuidSessionBundle = DBI::dbGetQuery(emuDBhandle$connection, queryTxt)
nbBundles = nrow(distinctUuidSessionBundle)
if(nbBundles < nbItems)
{
linkType = "ONE_TO_MANY"
}
else
{
linkType = "ONE_TO_ONE"
}
linkTracker[[length(linkTracker) + 1L]] = list(fromkey = "bundle",
tokey = level,
type = linkType)
}
return(linkTracker)
}
get_bpfLevelsUnderUtterance <- function(linkTracker,
refLevel)
{
underUtterance = list(refLevel)
if(length(linkTracker) == 0) { return(underUtterance)}
for(idx in 1:length(linkTracker))
{
if(linkTracker[[idx]][["tokey"]] == refLevel)
{
underUtterance[[length(underUtterance) + 1L]] = linkTracker[[idx]][["fromkey"]]
}
}
return(underUtterance)
}
link_bpfUtteranceLevelToCurrentLevel <- function(emuDBhandle, currentLevel)
{
queryTxt = paste0("SELECT db_uuid, session, bundle, item_id FROM items WHERE level = '", currentLevel, "'")
uuidSessionBundleItemID = DBI::dbGetQuery(emuDBhandle$connection, queryTxt)
for(idx in 1:nrow(uuidSessionBundleItemID))
{
db_uuid = uuidSessionBundleItemID[idx,][["db_uuid"]]
session = uuidSessionBundleItemID[idx,][["session"]]
bundle = uuidSessionBundleItemID[idx,][["bundle"]]
itemID = uuidSessionBundleItemID[idx,][["item_id"]]
queryTxt = paste0("INSERT INTO links VALUES('", db_uuid, "', '", session, "', '", bundle, "', 1, ", itemID, ", NULL)")
DBI::dbExecute(emuDBhandle$connection, queryTxt)
}
nbItems = nrow(uuidSessionBundleItemID)
return(nbItems)
}
create_bpfSchema <- function(levelTracker,
linkTracker,
dbName,
dbUUID,
audioExt)
{
defaultLevelOrder = get_bpfDefaultLevelOrder(levelTracker = levelTracker)
levelDefinitions = get_bpfLevelDefinitions(levelTracker = levelTracker)
linkDefinitions = get_bpfLinkDefinitions(linkTracker = linkTracker)
sc = list(order = c("OSCI","SPEC"),
assign = list(),
contourLims = list())
defPersp = list(name = 'default',
signalCanvases = sc,
levelCanvases = list(order = defaultLevelOrder),
twoDimCanvases = list(order = list()))
dbSchema = list(name = dbName,
UUID = dbUUID,
mediafileExtension = audioExt,
ssffTrackDefinitions = list(),
levelDefinitions = levelDefinitions,
linkDefinitions = linkDefinitions,
EMUwebAppConfig = list(perspectives=list(defPersp),
activeButtons = list(saveBundle = TRUE,
showHierarchy = TRUE)))
return(dbSchema)
}
get_bpfDefaultLevelOrder <- function(levelTracker)
{
defaultLevelOrder = list()
if(length(levelTracker) > 0)
{
for(levelIdx in 1:length(levelTracker))
{
if(levelTracker[[levelIdx]][["type"]] %in% c("SEGMENT", "EVENT"))
{
defaultLevelOrder[[length(defaultLevelOrder)+1L]] = levelTracker[[levelIdx]][["key"]]
}
}
}
return(defaultLevelOrder)
}
get_bpfLevelDefinitions <- function(levelTracker)
{
levelDefinitions = list()
if(length(levelTracker) > 0)
{
for(levelIdx in 1:length(levelTracker))
{
attrDefList = list()
for(label in levelTracker[[levelIdx]][["labels"]])
{
description = ""
if(label != "bundle")
{
description = "Imported from BPF collection"
}
attrDefList[[length(attrDefList) + 1L]] = list(name = label,
type = "STRING",
description = description)
}
levelDefinitions[[length(levelDefinitions) + 1L]] = list(name = levelTracker[[levelIdx]][["key"]],
type = levelTracker[[levelIdx]][["type"]],
attributeDefinitions = attrDefList)
}
}
return(levelDefinitions)
}
get_bpfLinkDefinitions <- function(linkTracker = linkTracker)
{
linkDefinitions = list()
if(length(linkTracker) > 0)
{
for(linkIdx in 1:length(linkTracker))
{
linkDefinitions[[length(linkDefinitions)+1L]] = list(type = linkTracker[[linkIdx]][["type"]],
superlevelName = linkTracker[[linkIdx]][["fromkey"]],
sublevelName = linkTracker[[linkIdx]][["tokey"]])
}
}
return(linkDefinitions)
}
make_bpfDbSkeleton <- function(emuDBhandle)
{
queryTxt = paste0("SELECT name FROM session WHERE db_uuid = '", emuDBhandle$UUID, "'")
sessions = DBI::dbGetQuery(emuDBhandle$connection, queryTxt)
for(idx in 1:nrow(sessions))
{
session = paste0(sessions[idx,], session.suffix)
res = try(dir.create(file.path(emuDBhandle$basePath, session)))
if(class(res) == "try-error")
{
stop("Could not create session directory ", file.path(emuDBhandle$basePath, session))
}
}
queryTxt = paste0("SELECT name, session FROM bundle WHERE db_uuid = '", emuDBhandle$UUID, "'")
bundles = DBI::dbGetQuery(emuDBhandle$connection, queryTxt)
for(jdx in 1:nrow(bundles))
{
bundle = paste0(bundles[jdx,1], bundle.dir.suffix)
session = paste0(bundles[jdx,2], session.suffix)
res = try(dir.create(file.path(emuDBhandle$basePath, session, bundle)))
if(class(res) == "try-error")
{
stop("Could not create bundle directory ", file.path(emuDBhandle$basePath, session, bundle))
}
}
}
display_bpfSemicolonWarnings <- function(warningsTracker)
{
msg = paste0("WARNING: The following BPF files contain links pointing to the space between items (using ';'). ",
"This feature has not been implemented yet, so the affected items were treated as link-less:\n")
for(path in warningsTracker$semicolonFound)
{
msg = paste0(msg, path, "\n")
}
if(length(warningsTracker$semicolonFound) > 0)
{
warning(msg)
}
}
BPF_STANDARD_LEVELS = c(
"KAN", "KAS", "PTR", "ORT", "TRL", "TR2", "SUP", "DAS", "PRS", "NOI",
"POS", "LMA", "TRS", "TRW", "PRO", "SYN", "FUN", "LEX", "TLN",
"IPA", "GES", "USH", "USM", "OCC",
"PRM", "LBG", "LBP",
"SAP", "MAU", "WOR", "PHO", "MAS", "USP", "TRN",
"PRB"
)
BPF_STANDARD_LEVEL_CLASSES = c(
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
3, 3, 3,
4, 4, 4, 4, 4, 4, 4,
5
)
|
test_that("bsFolds splits", {
d = list(data=data.frame(a=rep.int(0, 10)), best=rep.int(0, 10))
class(d) = "llama.data"
dfs = bsFolds(d)
expect_equal(length(dfs$train), 10)
expect_equal(length(dfs$test), 10)
expect_true(all(length(sapply(1:10,
function(x) { intersect(dfs$train[[x]], dfs$test[[x]]) }) == 0)))
d.algo = list(data=cbind(data.frame(p=rep.int(0, 10), f=rep.int(1, 10), algo=rep("a", 10)),
id=c(1:10)),
algorithmFeatures=c("f"),
algorithmNames=c("a"),
ids=c("id"),
algos=c("algo"),
best=rep.int("a", 10))
class(d.algo) = "llama.data"
dfs.algo = bsFolds(d.algo)
expect_equal(length(dfs.algo$train), 10)
expect_equal(length(dfs.algo$test), 10)
expect_true(all(length(sapply(1:10,
function(x) { intersect(dfs.algo$train[[x]], dfs.algo$test[[x]]) }) == 0)))
})
test_that("bsFolds splits with best list", {
d = list(data=data.frame(a=rep.int(0, 10)))
d$best = list(0, 0, 0, c(0,1), 0, 0, c(0,1), 0, 0, 0)
class(d) = "llama.data"
dfs = bsFolds(d, nfolds=2L)
expect_equal(length(dfs$train), 2)
expect_equal(length(dfs$test), 2)
expect_true(all(length(sapply(1:2,
function(x) { intersect(dfs$train[[x]], dfs$test[[x]]) }) == 0)))
d.algo = list(data=data.frame(p=rep.int(0, 10), f=rep.int(1, 10), algo=rep("a", 10),
id=c(1:10)),
algorithmFeatures=c("f"),
algorithmNames=c("a"),
ids=c("id"),
algos=c("algo"))
d.algo$best = list(rep.int("a", 10))
class(d.algo) = "llama.data"
dfs.algo = bsFolds(d.algo, nfolds=2L)
expect_equal(length(dfs.algo$train), 2)
expect_equal(length(dfs.algo$test), 2)
expect_true(all(length(sapply(1:2,
function(x) { intersect(dfs.algo$train[[x]], dfs.algo$test[[x]]) }) == 0)))
})
test_that("bsFolds allows to specify number of folds", {
d = list(data=data.frame(a=rep.int(0, 10)), best=rep.int(0, 10))
class(d) = "llama.data"
dfs = bsFolds(d, nfolds=2L)
expect_equal(length(dfs$train), 2)
expect_equal(length(dfs$test), 2)
expect_true(all(length(sapply(1:2,
function(x) { intersect(dfs$train[[x]], dfs$test[[x]]) }) == 0)))
d.algo = list(data=data.frame(p=rep.int(0, 10), f=rep.int(1, 10), algo=rep("a", 10),
id=c(1:10)), algorithmFeatures=c("f"), algorithmNames=c("a"),
ids=c("id"), algos=c("algo"), best=rep.int("a", 10))
class(d.algo) = "llama.data"
dfs.algo = bsFolds(d.algo, nfolds=2L)
expect_equal(length(dfs.algo$train), 2)
expect_equal(length(dfs.algo$test), 2)
expect_true(all(length(sapply(1:2,
function(x) { intersect(dfs.algo$train[[x]], dfs.algo$test[[x]]) }) == 0)))
})
test_that("bsFolds stratifies", {
d = list(data=data.frame(a=rep.int(0, 10)), best=c(rep.int(0, 5), rep.int(1, 5)))
class(d) = "llama.data"
dfs = bsFolds(d, nfolds=5L, T)
expect_equal(length(dfs$train), 5)
expect_equal(length(dfs$test), 5)
expect_true(all(length(sapply(1:5,
function(x) { intersect(dfs$train[[x]], dfs$test[[x]]) }) == 0)))
d.algo = list(data=cbind(data.frame(p=rep.int(0, 20), f=rep.int(1, 20), algo=rep(c("a1", "a2"), 10)),
id=rep.int(1:10, rep.int(2, 10))),
algorithmFeatures=c("f"),
algorithmNames=c("a1", "a2"),
ids=c("id"),
algos=c("algo"),
best=c(rep.int("a1", 10), rep.int("a2", 10)))
class(d.algo) = "llama.data"
dfs.algo = bsFolds(d.algo, nfolds=5L, T)
expect_equal(length(dfs.algo$train), 5)
expect_equal(length(dfs.algo$test), 5)
expect_true(all(length(sapply(1:5,
function(x) { intersect(dfs.algo$train[[x]], dfs.algo$test[[x]]) }) == 0)))
})
test_that("bsFolds replaces existing splits", {
d = list(data=data.frame(a=rep.int(0, 10)), best=rep.int(0, 10), train=1, test=2)
class(d) = "llama.data"
dfs = bsFolds(d)
expect_equal(length(dfs$train), 10)
expect_equal(length(dfs$test), 10)
expect_true(all(length(sapply(1:10,
function(x) { intersect(dfs$train[[x]], dfs$test[[x]]) }) == 0)))
d.algo = list(data=cbind(data.frame(p=rep.int(0, 20), f=rep.int(1, 20), algo=rep(c("a1", "a2"), 10)),
id=rep.int(1:10, rep.int(2, 10))),
algorithmFeatures=c("f"), ids=c("id"), algos=c("algo"),
algorithmNames=c("a1", "a2"),
best=rep.int("a1", 20), train=1, test=2)
class(d.algo) = "llama.data"
dfs.algo = bsFolds(d.algo)
expect_equal(length(dfs.algo$train), 10)
expect_equal(length(dfs.algo$test), 10)
expect_true(all(length(sapply(1:10,
function(x) { intersect(dfs.algo$train[[x]], dfs.algo$test[[x]]) }) == 0)))
})
|
subpop.sim <-
function(n=list(stage1=32,enrich=NULL,stage2=32),effect=list(early=c(0,0),final=c(0,0)),
outcome=list(early="N",final="N"),control=list(early=NULL,final=NULL),
sprev=0.5,nsim=1000,corr=0,seed=12345678,select="thresh",
weight=NULL,selim=NULL,level=0.025,method="CT-SD",sprev.fixed=TRUE,file=""){
time.out <- function(effect,n,standard=TRUE,method="exponential"){
t.stat <- log(effect[1])-log(effect)
if(method=="exponential"){
n.event <- n*(1-exp(-effect))
}
var.tstat <- 4/(n.event[1]+n.event)
if(standard==TRUE){
t.stat <- -t.stat/sqrt(var.tstat)
}
var.stat <- rep(1,length(effect))
return(list(t.stat=t.stat[2:length(t.stat)],var.stat=var.stat))
}
normal.out <- function(effect,n){
effect <- effect[1]-effect
t.stat <- effect*sqrt(n/2)
var.tstat <- rep(1,length(effect))
return(list(t.stat=t.stat[2:length(t.stat)],var.stat=var.tstat))
}
binary.out <- function(effect,n,standard=TRUE,method="LOR"){
n.risk <- rep(n,length(effect))
n.event <- n*effect
if(length(n.event)!=length(n.risk)){stop("need to set length n.risk = n.event")}
if(sum(n.risk>n.event)!=length(n.risk)){stop("need to set n.risk > n.event")}
lor <- log(n.event/(n.risk-n.event))
t.stat <- lor-lor[1]
var.tstat <- 1/n.event[1]+1/(n.risk[1]-n.event[1])+1/n.event+1/(n.risk-n.event)
if(standard==TRUE){
t.stat <- t.stat/sqrt(var.tstat)
}
var.stat <- 1/n.event+1/(n.risk-n.event)
return(list(t.stat=t.stat[2:length(t.stat)],var.stat=var.stat))
}
report.1 <- function(n,sprev,nsim,enrich,ran.seed,rule,selim,thresh,method,t.level,ofile) {
cat("\n",file=ofile,append=TRUE)
cat("asd: simulations for adaptive seamless designs: v2.0: 11/11/2013","\n",sep="",file=ofile,append=TRUE)
cat("\n",file=ofile,append=TRUE)
cat("sample sizes (per arm): sub-pop stage 1 =",as.integer(sprev*n$stage1),": sub-pop stage 1 =",n$stage1,"\n",sep=" ",file=ofile,append=TRUE)
cat("sample sizes (per arm): sub-pop stage 2 =",as.integer(sprev*n$stage2),": sub-pop stage 2 =",n$stage2,"\n",sep=" ",file=ofile,append=TRUE)
if(enrich==FALSE){
cat("sample sizes (per arm): enrichment: sub-pop stage 2 =",n$enrich,"\n",sep=" ",file=ofile,append=TRUE)
}
cat("simulations: n =",nsim,", seed =",ran.seed,"and rule =",rule,"with limits =",round(selim,2),"\n",sep=" ",file=ofile,append=TRUE)
t.level <- paste(as.character(round(100*t.level,1)),"%",sep="")
cat("method:",method,"and level =",t.level," (one-sided)","\n",sep=" ",file=ofile,append=TRUE)
}
report.2 <- function(out.lab,lab,eff.c,eff.s,eff.f,ofile) {
cat(out.lab,lab,"control =",eff.c,": sub-pop =",round(eff.s,2),": full-pop =",round(eff.f,2),"\n",sep=" ",file=ofile,append=TRUE)
}
report.3 <- function(ecorr.lab,fcorr.lab,correl,ofile) {
cat("correlation: early",ecorr.lab,"and final",fcorr.lab,"=",round(correl,2),"\n",sep=" ",file=ofile,append=TRUE)
}
report.4 <- function(zearly,z1,z2,weight,ofile) {
cat("\n",file=ofile,append=TRUE)
cat("simulation of test statistics:","\n",sep=" ",file=ofile,append=TRUE)
cat("expectation early: sub-pop =",round(zearly[1],2),": full-pop =",
round(zearly[2],2),"\n",sep=" ",file=ofile,append=TRUE)
cat("expectation final stage 1: sub-pop =",round(z1[1],2),": full-pop =",
round(z1[2],2),"\n",sep=" ",file=ofile,append=TRUE)
cat("expectation final stage 2: sub-pop only =",round(z2[1],2),": full-pop only =",
round(z2[2],2),"\n",sep=" ",file=ofile,append=TRUE)
cat("expectation final stage 2, both groups selected: sub-pop =",round(z2[3],2),
": full-pop =",round(z2[4],2),"\n",sep=" ",file=ofile,append=TRUE)
cat("weights: stage 1 =",round(sqrt(weight),2),"and stage 2 =",round(sqrt(1-weight),2),"\n",sep=" ",file=ofile,append=TRUE)
cat("\n")
}
report.5 <- function(sim.res,n,ofile) {
cat("hypotheses rejected and group selection options at stage 1 (n):","\n",file=ofile,append=TRUE)
cat(format(" ",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format("Hs",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format("Hf",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format("Hs+Hf",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format("Hs+f",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format("n",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format("n%",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),"\n",file=ofile,append=TRUE)
cat(format("sub",digits=1,trim=TRUE,justify="left",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[1,1],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[1,2],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[1,3],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[1,4],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[1,5],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(round(100*sim.res$results[1,5]/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),"\n",file=ofile,append=TRUE)
cat(format("full",digits=1,trim=TRUE,justify="left",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[2,1],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[2,2],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[2,3],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[2,4],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[2,5],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(round(100*sim.res$results[2,5]/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),"\n",file=ofile,append=TRUE)
cat(format("both",digits=1,trim=TRUE,justify="left",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[3,1],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[3,2],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[3,3],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[3,4],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sim.res$results[3,5],digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(round(100*sim.res$results[3,5]/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),"\n",file=ofile,append=TRUE)
cat(format("total",digits=1,trim=TRUE,justify="left",scientific=FALSE,nsmall=0,width=6),
"\t",format(sum(sim.res$results[1:3,1]),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sum(sim.res$results[1:3,2]),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sum(sim.res$results[1:3,3]),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sum(sim.res$results[1:3,4]),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format(sum(sim.res$results[1:3,5]),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),
"\t",format("-",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),"\n",file=ofile,append=TRUE)
cat(format("%",digits=1,trim=TRUE,justify="left",scientific=FALSE,nsmall=0,width=6),
"\t",format(round(100*sum(sim.res$results[1:3,1])/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format(round(100*sum(sim.res$results[1:3,2])/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format(round(100*sum(sim.res$results[1:3,3])/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format(round(100*sum(sim.res$results[1:3,4])/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format(round(100*sum(sim.res$results[1:3,5])/n,5),digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=2,width=6),
"\t",format("-",digits=1,trim=TRUE,justify="right",scientific=FALSE,nsmall=0,width=6),"\n",file=ofile,append=TRUE)
all.reject <- 100*(sum(sim.res$results[1:3,1])+sum(sim.res$results[1:3,2])-sum(sim.res$results[1:3,3]))/n
cat("reject Hs and/or Hf = ",paste(round(all.reject,3),"%",sep=""),"\n",sep=" ",file=ofile,append=TRUE)
}
if (length(n$stage1)!=1 | length(n$stage2)!=1) {
stop("Invalid sample size for stages 1 and 2")
}
n$stage1 <- as.integer(n$stage1); n$stage2 <- as.integer(n$stage2)
if(is.null(n$enrich)==FALSE){n$enrich <- as.integer(n$enrich)}
if (length(corr)==1) {
if (abs(corr)>1) {
stop("Correlation must be value between -1 and 1")
}
} else {
stop("Correlation must be value length between -1 and 1")
}
outcome.options <- c("N","B","T")
e.outcome <- as.integer(match(outcome$early,outcome.options,-1))
if (e.outcome < 1) {
stop("Unknown early outcome: current options N, B or T")
}
if(length(effect$early)!=2){
stop("Early effect: need vector length=2")
}
if(length(effect$final)!=2){
stop("Final effect: need vector length=2")
}
if (level >= 1 | level <= 0) {
stop("level must be between 0 and 1")
}
sel.options <- c("thresh","futility")
isel <- as.integer(match(select, sel.options, -1))
if (isel < 1) {
stop("Unknown method: current option thresh")
}
if(select=="thresh"){
if(is.null(selim)==TRUE){
selim[1] <- -6
selim[2] <- 6
}
if(selim[1]>selim[2]){
stop("Limits for threshold rule: selim[1]<selim[2]")
}
}
selection.rules <- c("threshold","futility")
meth.options <- c("CT-Simes","CT-Bonferroni","CT-SD","CEF")
imeth <- as.integer(match(method, meth.options, -1))
if (imeth < 1) {
stop("unknown method: current options CT-Simes, CT-Bonferroni, CT-SD or CEF")
}
test.method <- c("CT-Simes","CT-Bonferroni","CT-SD","CEF")
if(outcome$early=="N"){
if(is.null(control$early)){
early.S <- c(0,effect$early[1])
early.F <- c(0,effect$early[2])
} else {
early.S <- c(control$early,effect$early[1])
early.F <- c(control$early,effect$early[2])
}
early.out <- normal.out
oearly.lab <- "normal, standardized effect sizes:"
ecorr.lab <- "standardized effect"
} else if(outcome$early=="B"){
lbin.test <- sum(effect$early<=0); ubin.test <- sum(effect$early>=1)
if(lbin.test>0 | ubin.test>0){
stop("early effect: rate must be values between 0 and 1")
}
if(is.null(control$early)==TRUE){
stop("control effects: rates must be values between 0 and 1")
}
if(control$early<0 | control$early>1){
stop("control effects: rates must be values between 0 and 1")
}
early.S <- c(control$early,effect$early[1])
early.F <- c(control$early,effect$early[2])
early.out <- binary.out
oearly.lab <- "binary, event rate:"
ecorr.lab <- "log(odds)"
} else if(outcome$early=="T"){
lhaz.test <- sum(effect$early<=0)
if(lhaz.test>0){
stop("Early effect: hazard must be > 0")
}
if(is.null(control$early)){
early.S <- c(1,effect$early[1])
early.F <- c(1,effect$early[2])
} else {
early.S <- c(control$early,effect$early[1])
early.F <- c(control$early,effect$early[2])
}
early.out <- time.out
oearly.lab <- "time-to-event, hazard rate:"
ecorr.lab <- "log(hazard)"
}
f.outcome <- as.integer(match(outcome$final,outcome.options,-1))
if (f.outcome < 1) {
stop("unknown early outcome: current options N, B or T")
}
if(length(effect$final)!=length(effect$early)){
stop("final effect: should be vector of same length as early effect")
}
if(outcome$final=="N"){
if(is.null(control$final)){
final.S <- c(0,effect$final[1])
final.F <- c(0,effect$final[2])
} else {
final.S <- c(control$final,effect$final[1])
final.F <- c(control$final,effect$final[2])
}
final.out <- normal.out
ofinal.lab <- "normal, standardized effect sizes:"
fcorr.lab <- "standardized effect"
} else if(outcome$final=="B"){
lbin.test <- sum(effect$final<=0); ubin.test <- sum(effect$final>=1)
if(lbin.test>0 | ubin.test>0){
stop("Final effect: rate must be value length between 0 and 1")
}
if(is.null(control$final)==TRUE){
stop("control effects: rates must be values between 0 and 1")
}
if(control$final<0 | control$final>1){
stop("control effects: rates must be values between 0 and 1")
}
final.S <- c(control$final,effect$final[1])
final.F <- c(control$final,effect$final[2])
final.out <- binary.out
ofinal.lab <- "binary, event rate:"
fcorr.lab <- "log(odds)"
} else if(outcome$final=="T"){
lhaz.test <- sum(effect$final<=0)
if(lhaz.test>0){
stop("Final effect: hazard must be > 0")
}
if(is.null(control$final)){
final.S <- c(1,effect$final[1])
final.F <- c(1,effect$final[2])
} else {
final.S <- c(control$final,effect$final[1])
final.F <- c(control$final,effect$final[2])
}
final.out <- time.out
ofinal.lab <- "time-to-event, hazard rate:"
fcorr.lab <- "log(hazard)"
}
if(is.null(n$enrich)==TRUE){n$enrich <- sprev*n$stage2}
zearly.S <- early.out(effect=early.S,n=sprev*n$stage1)$t.stat
zearly.F <- early.out(effect=early.F,n=n$stage1)$t.stat
zearly <- c(zearly.S,zearly.F)
z1.S <- final.out(effect=final.S,n=sprev*n$stage1)$t.stat
z1.F <- final.out(effect=final.F,n=n$stage1)$t.stat
z1 <- c(z1.S,z1.F)
z2.S1 <- final.out(effect=final.S,n=n$enrich)$t.stat
z2.F1 <- final.out(effect=final.F,n=n$stage2)$t.stat
z2.S2 <- final.out(effect=final.S,n=sprev*n$stage2)$t.stat
z2.F2 <- final.out(effect=final.F,n=n$stage2)$t.stat
z2 <- c(z2.S1,z2.F1,z2.S2,z2.F2)
if(is.null(weight)==TRUE){
weight <- n$stage1/(n$stage1+n$stage2)
} else if(weight<0 | weight>1){
stop("weight: must be value between 0 and 1")
}
if(is.null(selim)==TRUE){
selim[1] <- zearly.S
selim[2] <- zearly.F
}
if(sprev.fixed==TRUE){
results <- gsubpop.sim(z.early=zearly,z1=z1,z2=z2,sprev=rep(sprev,2),selim=selim,
corr=corr,nsim=nsim,seed=seed,level=level,
select=select,method=method,wt=weight)
} else if(sprev.fixed==FALSE){
s.seed <- runif(n=nsim,min=1,max=10000)
for(k in 1:nsim){
sprev.1 <- rbinom(1,n$stage1,sprev)/n$stage1
sprev.2 <- rbinom(1,n$stage2,sprev)/n$stage2
if(is.null(n$enrich)==TRUE){n$enrich <- sprev.2*n$stage2}
zearly.S <- early.out(effect=early.S,n=sprev.1*n$stage1)$t.stat
zearly.F <- early.out(effect=early.F,n=n$stage1)$t.stat
zearly <- c(zearly.S,zearly.F)
z1.S <- final.out(effect=final.S,n=sprev.1*n$stage1)$t.stat
z1.F <- final.out(effect=final.F,n=n$stage1)$t.stat
z1 <- c(z1.S,z1.F)
z2.S1 <- final.out(effect=final.S,n=n$enrich)$t.stat
z2.F1 <- final.out(effect=final.F,n=n$stage2)$t.stat
z2.S2 <- final.out(effect=final.S,n=sprev.2*n$stage2)$t.stat
z2.F2 <- final.out(effect=final.F,n=n$stage2)$t.stat
z2 <- c(z2.S1,z2.F1,z2.S2,z2.F2)
if(is.null(weight)==TRUE){
weight <- n$stage1/(n$stage1+n$stage2)
} else if(weight<0 | weight>1){
stop("weight: must be value between 0 and 1")
}
results.k <- gsubpop.sim(z.early=zearly,z1=z1,z2=z2,sprev=c(sprev.1,sprev.2),selim=selim,
corr=corr,nsim=1,seed=s.seed[k],level=level,
select=select,method=method,wt=weight)
if(k==1){results <- results.k} else {
results$results <- results$results+results.k$results
}
}
}
report.1(n=n,sprev=sprev,nsim=nsim,enrich=is.null(n$enrich),ran.seed=seed,rule=selection.rules[isel],
selim=selim,method=method,t.level=level,ofile=file)
report.2(out.lab="early outcome:",lab=oearly.lab,
eff.c=round(early.S[1],3),eff.s=round(early.S[2],3),eff.f=round(early.F[2],3),ofile=file)
report.2(out.lab="final outcome:",lab=ofinal.lab,
eff.c=round(final.S[1],3),eff.s=round(final.S[2],3),eff.f=round(final.F[2],3),ofile=file)
report.3(ecorr.lab,fcorr.lab,correl=corr,ofile=file)
report.4(zearly,z1,z2,weight,ofile=file)
report.5(results,n=nsim,ofile=file)
invisible(results)
}
|
selfStart <-
function(model, initial, parameters, template) UseMethod("selfStart")
selfStart.default <- function(model, initial, parameters, template)
{
structure(as.function(model), initial = as.function(initial),
pnames = if(!missing(parameters))parameters,
class = "selfStart")
}
selfStart.formula <-
function(model, initial, parameters, template = NULL)
{
if (is.null(template)) {
nm <- all.vars(model)
if (any(msng <- is.na(match(parameters, nm)))) {
stop(sprintf(ngettext(sum(msng),
"parameter %s does not occur in the model formula",
"parameters %s do not occur in the model formula"),
paste(sQuote(parameters[msng]), collapse=", ")),
domain = NA)
}
template <- function() {}
argNams <- c( nm[ is.na( match(nm, parameters) ) ], parameters )
args <- setNames(rep(alist(a = ), length(argNams)), argNams)
formals(template) <- args
}
structure(deriv(model, parameters, template),
initial = as.function(initial),
pnames = parameters,
class = "selfStart")
}
getInitial <-
function(object, data, ...) UseMethod("getInitial")
getInitial.formula <-
function(object, data, ...)
{
if(!is.null(attr(data, "parameters"))) {
return(attr(data, "parameters"))
}
switch (length(object),
stop("argument 'object' has an impossible length"),
{
func <- get(as.character(object[[2L]][[1L]]))
getInitial(func, data,
mCall = as.list(match.call(func, call = object[[2L]])),
...)
},
{
func <- get(as.character(object[[3L]][[1L]]))
getInitial(func, data,
mCall = as.list(match.call(func, call = object[[3L]])),
LHS = object[[2L]], ...)
})
}
getInitial.selfStart <-
function(object, data, mCall, LHS = NULL, ...)
{
iniFn <- attr(object, "initial")
if(length(formals(iniFn)) > 3L)
iniFn(mCall = mCall, data = data, LHS = LHS, ...)
else {
.Deprecated(msg=
"selfStart initializing functions should have a final '...' argument since R 4.1.0")
iniFn(mCall = mCall, data = data, LHS = LHS)
}
}
getInitial.default <-
function(object, data, mCall, LHS = NULL, ...)
{
if (is.function(object) && !is.null(attr(object, "initial"))) {
stop("old-style self-starting model functions\n",
"are no longer supported.\n",
"New selfStart functions are available.\n",
"Use\n",
" SSfpl instead of fpl,\n",
" SSfol instead of first.order.log,\n",
" SSbiexp instead of biexp,\n",
" SSlogis instead of logistic.\n",
"If writing your own selfStart model, see\n",
" \"help(selfStart)\"\n",
"for the new form of the \"initial\" attribute.", domain = NA)
}
stop(gettextf("no 'getInitial' method found for \"%s\" objects",
data.class(object)), domain = NA)
}
sortedXyData <-
function(x, y, data) UseMethod("sortedXyData")
sortedXyData.default <-
function(x, y, data)
{
if (is.language(x) || ((length(x) == 1L) && is.character(x))) {
x <- eval(asOneSidedFormula(x)[[2L]], data)
}
x <- as.numeric(x)
if (is.language(y) || ((length(y) == 1L) && is.character(y))) {
y <- eval(asOneSidedFormula(y)[[2L]], data)
}
y <- as.numeric(y)
y.avg <- tapply(y, x, mean, na.rm = TRUE)
xvals <- as.numeric(chartr(getOption("OutDec"), ".", names(y.avg)))
ord <- order(xvals)
value <- na.omit(data.frame(x = xvals[ord], y = as.vector(y.avg[ord])))
class(value) <- c("sortedXyData", "data.frame")
value
}
NLSstClosestX <-
function(xy, yval) UseMethod("NLSstClosestX")
NLSstClosestX.sortedXyData <-
function(xy, yval)
{
deviations <- xy$y - yval
if (any(deviations==0))
return(xy$x[match(0, deviations)])
if (any(deviations <= 0)) {
dev1 <- max(deviations[deviations <= 0])
lim1 <- xy$x[match(dev1, deviations)]
if (all(deviations <= 0)) return(lim1)
}
if (any(deviations >= 0)) {
dev2 <- min(deviations[deviations >= 0])
lim2 <- xy$x[match(dev2, deviations)]
if (all(deviations >= 0)) return(lim2)
}
dev1 <- abs(dev1)
dev2 <- abs(dev2)
lim1 + (lim2 - lim1) * dev1/(dev1 + dev2)
}
NLSstRtAsymptote <-
function(xy) UseMethod("NLSstRtAsymptote")
NLSstRtAsymptote.sortedXyData <-
function(xy)
{
in.range <- range(xy$y)
last.dif <- abs(in.range - xy$y[nrow(xy)])
if(match(min(last.dif), last.dif) == 2L)
in.range[2L] + diff(in.range)/8
else
in.range[1L] - diff(in.range)/8
}
NLSstLfAsymptote <-
function(xy) UseMethod("NLSstLfAsymptote")
NLSstLfAsymptote.sortedXyData <-
function(xy)
{
in.range <- range(xy$y)
first.dif <- abs(in.range - xy$y[1L])
if(match(min(first.dif), first.dif) == 2L)
in.range[2L] + diff(in.range)/8
else
in.range[1L] - diff(in.range)/8
}
NLSstAsymptotic <-
function(xy) UseMethod("NLSstAsymptotic")
NLSstAsymptotic.sortedXyData <-
function(xy)
{
xy$rt <- NLSstRtAsymptote(xy)
setNames(coef(nls(y ~ cbind(1, 1 - exp(-exp(lrc) * x)),
data = xy,
start = list(lrc = log(-coef(lm(log(abs(y - rt)) ~ x,
data = xy))[[2L]])),
algorithm = "plinear"))[c(2, 3, 1)],
c("b0", "b1", "lrc"))
}
|
step_stem <-
function(recipe,
...,
role = NA,
trained = FALSE,
columns = NULL,
options = list(),
custom_stemmer = NULL,
skip = FALSE,
id = rand_id("stem")) {
add_step(
recipe,
step_stem_new(
terms = enquos(...),
role = role,
trained = trained,
options = options,
custom_stemmer = custom_stemmer,
columns = columns,
skip = skip,
id = id
)
)
}
step_stem_new <-
function(terms, role, trained, columns, options, custom_stemmer, skip, id) {
step(
subclass = "stem",
terms = terms,
role = role,
trained = trained,
columns = columns,
options = options,
custom_stemmer = custom_stemmer,
skip = skip,
id = id
)
}
prep.step_stem <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_list(training[, col_names])
step_stem_new(
terms = x$terms,
role = x$role,
trained = TRUE,
columns = col_names,
options = x$options,
custom_stemmer = x$custom_stemmer,
skip = x$skip,
id = x$id
)
}
bake.step_stem <- function(object, new_data, ...) {
col_names <- object$columns
stem_fun <- object$custom_stemmer %||%
SnowballC::wordStem
for (i in seq_along(col_names)) {
stemmed_tokenlist <- tokenlist_apply(
new_data[, col_names[i], drop = TRUE],
stem_fun, object$options
)
new_data[, col_names[i]] <- tibble(stemmed_tokenlist)
}
new_data <- factor_to_text(new_data, col_names)
as_tibble(new_data)
}
print.step_stem <-
function(x, width = max(20, options()$width - 30), ...) {
cat("Stemming for ", sep = "")
printer(x$columns, x$terms, x$trained, width = width)
invisible(x)
}
tidy.step_stem <- function(x, ...) {
if (is_trained(x)) {
res <- tibble(
terms = unname(x$columns),
is_custom_stemmer = is.null(x$custom_stemmer)
)
} else {
term_names <- sel2char(x$terms)
res <- tibble(
terms = term_names,
is_custom_stemmer = is.null(x$custom_stemmer)
)
}
res$id <- x$id
res
}
required_pkgs.step_stem <- function(x, ...) {
c("textrecipes", "SnowballC")
}
|
as_rscontract <- function(x) {
UseMethod("as_rscontract")
}
as_rscontract.rscontract_spec <- function(x) {
to_contract(x)
}
as_rscontract.list <- function(x) {
spec <- rscontract_spec()
names_x <- names(x)
for (i in seq_along(x)) {
item <- names_x[[i]]
spec[[item]] <- x[[item]]
}
to_contract(spec)
}
to_contract <- function(x) {
rscontract_ide(
connectionObject = eval_list(x$connection_object),
type = eval_list(x$type),
host = eval_list(x$host),
displayName = eval_list(x$name),
connectCode = eval_list(x$connect_script),
disconnect = eval_char(x$disconnect_code),
previewObject = eval_char(x$preview_code),
listObjectTypes = eval_char(x$object_types),
listObjects = ifelse(
is.null(x$object_list),
spec_list_objects(eval_char(x$catalog_list)),
x$object_list
),
listColumns = ifelse(
is.null(x$object_columns),
spec_list_columns(eval_char(x$catalog_list)),
x$object_columns
),
actions = x$actions,
icon = x$icon
)
}
|
skip_if_not(exists("token"))
if (!exists("verifyFields", mode = "function")) source("global.R")
context("07. DataProducts Delivery Service")
expectedFields <- list(
url = "character",
status = "character",
size = "double",
file = "character",
index = "character",
downloaded = "logical",
requestCount = "double",
fileDownloadTime = "double"
)
F_DUMMY1 <- list(dataProductCode = "TSSD", extension = "csv", locationCode = "BACAX", deviceCategoryCode = "ADCP2MHZ",
dateFrom = "2016-07-27T00:00:00.000Z", dateTo = "2016-07-27T00:00:30.000Z",
dpo_dataGaps = "0", dpo_qualityControl = "1", dpo_resample = "none")
F_DUMMY2 <- list(dataProductCode = "TSSP", extension = "png", locationCode = "CRIP.C1", deviceCategoryCode = "CTD",
dateFrom = "2019-03-20T00:00:00.000Z", dateTo = "2019-03-20T00:30:00.000Z",
dpo_qualityControl = "1", dpo_resample = "none")
F_FAKE <- list(dataProductCode = "FAKECODE", extension = "XYZ", locationCode = "AREA51", deviceCategoryCode = "AK47",
dateFrom = "2019-03-20T00:00:00.000Z", dateTo = "2019-03-20T00:30:00.000Z",
dpo_qualityControl = "1", dpo_resample = "none")
validateRow = function(rows, index="1", status = "complete", downloaded = FALSE) {
row <- NULL
for (r in rows) {
if (r$index == index) {
row <- r
break
}
}
expect_false(is.null(row))
expect_equal(row$status, status)
expect_equal(row$downloaded, downloaded)
}
test_that("01. Order product links only", {
onc <- prepareOnc(outPath = "output/07/01")
result <- onc$orderDataProduct(F_DUMMY1, 100, TRUE, FALSE)
rows <- result$downloadResults
expect_equal(length(rows), 1)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = FALSE)
filesInPath(onc$outPath, 0)
})
test_that("02. Order links with metadata", {
onc <- prepareOnc(outPath = "output/07/02")
result <- onc$orderDataProduct(F_DUMMY1, 100, TRUE, TRUE)
rows <- result$downloadResults
expect_equal(length(rows), 2)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = FALSE)
validateRow(rows, index = "meta", status = "complete", downloaded = FALSE)
filesInPath(onc$outPath, 0)
})
test_that("03. Order and download", {
onc <- prepareOnc(outPath = "output/07/03")
result <- onc$orderDataProduct(F_DUMMY1, 100, FALSE, FALSE)
rows <- result$downloadResults
expect_equal(length(rows), 1)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = TRUE)
filesInPath(onc$outPath, 1)
})
test_that("04. Order and download multiple", {
onc <- prepareOnc(outPath = "output/07/04")
result <- onc$orderDataProduct(F_DUMMY2, 100, FALSE, FALSE)
rows <- result$downloadResults
expect_equal(length(rows), 2)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = TRUE)
validateRow(rows, index = "2", status = "complete", downloaded = TRUE)
filesInPath(onc$outPath, 2)
})
test_that("05. Order and download with metadata", {
onc <- prepareOnc(outPath = "output/07/05")
result <- onc$orderDataProduct(F_DUMMY1, 100, FALSE, TRUE)
rows <- result$downloadResults
expect_equal(length(rows), 2)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = TRUE)
validateRow(rows, index = "meta", status = "complete", downloaded = TRUE)
filesInPath(onc$outPath, 2)
})
test_that("06. Order and download multiple with metadata", {
onc <- prepareOnc(outPath = "output/07/06")
result <- onc$orderDataProduct(F_DUMMY2, 100, FALSE, TRUE)
rows <- result$downloadResults
expect_equal(length(rows), 3)
expect_true(verifyFields(rows[[1]], expectedFields))
validateRow(rows, index = "1", status = "complete", downloaded = TRUE)
validateRow(rows, index = "2", status = "complete", downloaded = TRUE)
validateRow(rows, index = "meta", status = "complete", downloaded = TRUE)
filesInPath(onc$outPath, 3)
})
test_that("07. Wrong order request argument", {
onc <- prepareOnc(outPath = "output/07/07")
result <- onc$orderDataProduct(F_FAKE, 100, TRUE, FALSE)
expect_gte(length(result$errors), 1)
expect_true(isErrorResponse(result))
})
test_that("08. Manual request, run and download", {
onc <- prepareOnc(outPath = "output/07/08")
reqId <- onc$requestDataProduct(F_DUMMY1)[["dpRequestId"]]
runId <- onc$runDataProduct(reqId)[["runIds"]][[1]]
rows <- onc$downloadDataProduct(runId, downloadResultsOnly = FALSE, includeMetadataFile = TRUE)
expect_equal(length(rows), 2)
validateRow(rows, index = "1", status = "complete", downloaded = TRUE)
validateRow(rows, index = "meta", status = "complete", downloaded = TRUE)
filesInPath(onc$outPath, 2)
})
test_that("09. Manual request, run and download results only", {
onc <- prepareOnc(outPath = "output/07/09")
reqId <- onc$requestDataProduct(F_DUMMY1)[["dpRequestId"]]
runId <- onc$runDataProduct(reqId)[["runIds"]][[1]]
rows <- onc$downloadDataProduct(runId, downloadResultsOnly = TRUE, includeMetadataFile = TRUE)
expect_equal(length(rows), 2)
validateRow(rows, index = "1", status = "complete", downloaded = FALSE)
validateRow(rows, index = "meta", status = "complete", downloaded = FALSE)
filesInPath(onc$outPath, 0)
})
test_that("10. Manual run with wrong argument", {
onc <- prepareOnc(outPath = "output/07/10")
result <- onc$runDataProduct(1234568790)
onc$print(result)
expect_true(isErrorResponse(result))
})
test_that("11. Manual download with wrong argument", {
onc <- prepareOnc(outPath = "output/07/11")
expect_error({onc$downloadDataProduct(1234568790, downloadResultsOnly = FALSE, includeMetadataFile = TRUE)})
})
|
print.DiscrFact<-
function (x, ...)
{
cat ("Mean overall discriminant factor:", mean (x$assignfact), "\n")
cat ("Mean discriminant factor per cluster:\n")
print (x$mean.DiscrFact)
idx = x$assignfact > x$threshold
if(!sum(idx))
cat("No decision is considered as doubtful\n")
else
cat(sum(idx), "decisions are considered as doubtful\n")
invisible(x)
}
|
pred3.crr <- function(z, cov1, cov2, time, lps = FALSE) {
np <- length(z$coef)
if (length(z$tfs) <= 1.) {
if (length(z$coef) == length(cov1)) {
lhat <- cumsum(exp(sum(cov1 * z$coef)) * z$bfitj)
lp <- sum(cov1 * z$coef)
} else {
cov1 <- as.matrix(cov1)
lhat <- matrix(0., nrow = length(z$uftime), ncol = nrow(cov1))
lp <- matrix(0., nrow = length(z$uftime), ncol = nrow(cov1))
for (j in 1.:nrow(cov1)) {
lhat[, j] <- cumsum(exp(sum(cov1[j, ] * z$coef)) * z$bfitj)
lp[, j] <- sum(cov1[j, ] * z$coef)
}
lp <- lp[1., ]
}
} else {
if (length(z$coef) == ncol(as.matrix(z$tfs))) {
if (length(z$coef) == length(cov2)) {
lhat <- cumsum(exp(z$tfs %*% c(cov2 * z$coef)) * z$bfitj)
} else {
cov2 <- as.matrix(cov2)
lhat <- matrix(
0.,
nrow = length(z$uftime),
ncol = nrow(cov1)
)
for (j in 1.:nrow(cov2)) {
lhat[, j] <- cumsum(exp(z$tfs %*% c(
cov2[j, ] * z$coef
)) * z$bfitj)
}
}
} else {
if (length(z$coef) == length(cov1) + length(cov2)) {
lhat <- cumsum(exp(sum(cov1 * z$coef[1.:length(
cov1
)]) + z$tfs %*% c(cov2 * z$coef[
(np - length(cov2) + 1.):np
])) * z$
bfitj)
} else {
cov1 <- as.matrix(cov1)
cov2 <- as.matrix(cov2)
lhat <- matrix(
0.,
nrow = length(z$uftime),
ncol = nrow(cov1)
)
for (j in 1.:nrow(cov1)) {
lhat[, j] <-
cumsum(
exp(sum(
cov1[j, ] * z$coef[1.:ncol(cov1)]) + z$tfs %*%
c(cov2[j, ] * z$coef[seq(
(np - ncol(cov2) + 1.), np)])) *
z$bfitj)
}
}
}
}
lhat <- cbind(z$uftime, 1. - exp(-lhat))
lhat <- lhat[lhat[, 1.] <= time + 1e-10, ]
lhat <- lhat[dim(lhat)[1.], -1.]
if (lps) {
lp
} else {
lhat
}
}
|
pcaLocalDimEst <- function(data, ver, alphaFO = .05, alphaFan = 10, betaFan = .8,
PFan = .95, ngap = 5, maxdim = min(dim(data)),
verbose = TRUE) {
lambda <- prcomp(data)$sdev^2
if (ver == 'FO') return(FO(lambda, alphaFO))
if (ver == 'fan') return(fan(lambda, alphaFan, betaFan, PFan))
if (ver == 'maxgap') return(maxgap(lambda))
if (ver == 'cal') return(cal(lambda, ngap, dim(data)[1], maxdim, verbose))
stop('Not a valid version.')
}
FO <- function(lambda, alpha) {
de <- sum(lambda > alpha*lambda[1])
n <- length(lambda)
gaps <- lambda[1:(n-1)]/lambda[2:n]
return(DimEst(de, gap.size = gaps[de]))
}
fan <- function(lambda, alpha = 10, beta = .8, P = .95) {
n <- length(lambda)
r <- which(cumsum(lambda)/sum(lambda) > P)[1]
sigma <- mean(lambda[r:n])
lambda <- lambda - sigma
gaps <- lambda[1:(n-1)]/lambda[2:n]
de <- min(c(which(gaps > alpha),
which(cumsum(lambda)/sum(lambda) > beta)))
return(DimEst(de, gap.size = gaps[de]))
}
maxgap <- function(lambda) {
n <- length(lambda)
gaps <- lambda[1:(n-1)]/lambda[2:n]
de <- which.max(gaps)
return(DimEst(de, gap.size = gaps[de]))
}
cal <- function(lambda, ngap = 5, Ns, maxdim = min(length(lambda), Ns), verbose = TRUE) {
n <- length(lambda)
if (Ns < n) {
n <- Ns
lambda <- lambda[1:n]
}
gaps <- lambda[1:(n-1)]/lambda[2:n]
D <- order(gaps[1:maxdim], decreasing = TRUE)[1:ngap]
lik <- rep(NA,ngap)
for (j in 1:length(D)) {
d <- D[j]
sigma.noi <- mean(lambda[(d+1):n])
sigma.data <- mean(lambda[1:d])
sigma.ball <- 1/(d+2)
R <- sqrt(sigma.data/sigma.ball)
sd.noi <- sqrt(sigma.noi)/R
ntest <- 100
if (verbose) {
cat('Computing likelihood for d =', d, '\n')
cat('R =', R, '\n')
cat('sd.noi =', sd.noi, '\n')
}
tryCatch({
lambdamat <- replicate(ntest, prcomp(cutHyperPlane(Ns, d, n, sd.noi))$sdev^2)
gap <- lambdamat[d,]/lambdamat[d+1,]
last <- lambdamat[n,]
lik[j] <- dt((gaps[d] - mean(gap))/sd(gap), ntest-1)*
dt((lambda[n] - mean(last))/sd(last), ntest-1)
if (verbose) cat('Likelihood:', lik[j], '\n')
}, error = function(ex) {
cat(d, 'removed as possible dimension since reference data could not be constructed \n')
})
}
ind = which.max(lik)
return(DimEst(D[ind], likelihood = lik(ind)))
}
|
library(PerformanceAnalytics)
data(portfolio_bacon)
print(MeanAbsoluteDeviation(portfolio_bacon[,1]))
data(portfolio_bacon)
print(Frequency(portfolio_bacon[,1]))
data(managers)
SharpeRatio(managers[,1,drop=FALSE], Rf=.035/12, FUN="StdDev")
data(portfolio_bacon)
print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2]))
print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2], Method="arithmetic"))
data(managers)
print(CAPM.alpha(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12))
data(managers)
CAPM.beta(managers[, "HAM2", drop=FALSE], managers[, "SP500 TR", drop=FALSE], Rf = managers[, "US 3m TR", drop=FALSE])
data(managers)
print(CAPM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(CAPM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(SystematicRisk(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(SpecificRisk(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(TotalRisk(portfolio_bacon[,1], portfolio_bacon[,2]))
data(managers)
print(round(TreynorRatio(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12),4))
data(portfolio_bacon)
print(TreynorRatio(portfolio_bacon[,1], portfolio_bacon[,2], modified = TRUE))
data(portfolio_bacon)
print(AppraisalRatio(portfolio_bacon[,1], portfolio_bacon[,2], method="appraisal"))
data(portfolio_bacon)
print(AppraisalRatio(portfolio_bacon[,1], portfolio_bacon[,2], method="modified"))
data(portfolio_bacon)
print(FamaBeta(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(Selectivity(portfolio_bacon[,1], portfolio_bacon[,2]))
data(portfolio_bacon)
print(NetSelectivity(portfolio_bacon[,1], portfolio_bacon[,2]))
data(managers)
TrackingError(managers[,1,drop=FALSE], managers[,8,drop=FALSE])
data(managers)
InformationRatio(managers[,"HAM1",drop=FALSE], managers[, "SP500 TR", drop=FALSE])
data(managers)
skewness(managers)
data(portfolio_bacon)
print(skewness(portfolio_bacon[,1], method="sample"))
data(portfolio_bacon)
print(kurtosis(portfolio_bacon[,1], method="moment"))
data(portfolio_bacon)
print(kurtosis(portfolio_bacon[,1], method="excess"))
data(portfolio_bacon)
print(kurtosis(portfolio_bacon[,1], method="sample"))
data(portfolio_bacon)
print(kurtosis(portfolio_bacon[,1], method="sample_excess"))
data(portfolio_bacon)
print(PainIndex(portfolio_bacon[,1]))
data(managers)
CalmarRatio(managers[,1,drop=FALSE])
data(managers)
SterlingRatio(managers[,1,drop=FALSE])
data(portfolio_bacon)
print(BurkeRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
print(BurkeRatio(portfolio_bacon[,1], modified = TRUE))
data(portfolio_bacon)
print(MartinRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
print(PainRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
MAR = 0.5
DownsideDeviation(portfolio_bacon[,1], MAR)
DownsidePotential(portfolio_bacon[,1], MAR)
data(portfolio_bacon)
MAR = 0.005
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="risk"))
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="variance"))
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="potential"))
data(portfolio_bacon)
MAR = 0.005
print(DownsideFrequency(portfolio_bacon[,1], MAR))
data(portfolio_bacon)
print(BernardoLedoitRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
print(DRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
MAR = 0.005
print(OmegaSharpeRatio(portfolio_bacon[,1], MAR))
data(managers)
round(SortinoRatio(managers[, 1]),4)
data(portfolio_bacon)
MAR = 0.005
l = 2
print(Kappa(portfolio_bacon[,1], MAR, l))
data(edhec)
UpsidePotentialRatio(edhec[, 6], MAR=.05/12)
data(portfolio_bacon)
MAR = 0.005
print(VolatilitySkewness(portfolio_bacon[,1], MAR, stat="volatility"))
data(portfolio_bacon)
MAR = 0.005
print(VolatilitySkewness(portfolio_bacon[,1], MAR, stat="variability"))
data(portfolio_bacon)
print(AdjustedSharpeRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
print(SkewnessKurtosisRatio(portfolio_bacon[,1]))
data(portfolio_bacon)
MAR = 0.05
print(ProspectRatio(portfolio_bacon[,1], MAR))
data(portfolio_bacon)
MAR = 0.005
print(M2Sortino(portfolio_bacon[,1], portfolio_bacon[,2], MAR))
data(portfolio_bacon)
MAR = 0.005
print(OmegaExcessReturn(portfolio_bacon[,1], portfolio_bacon[,2], MAR))
data(managers)
table.Variability(managers[,1:8])
data(managers)
table.SpecificRisk(managers[,1:8], managers[,8])
data(managers)
table.InformationRatio(managers[,1:8], managers[,8])
data(managers)
table.Distributions(managers[,1:8])
data(managers)
table.DrawdownsRatio(managers[,1:8])
data(managers)
table.DownsideRiskRatio(managers[,1:8])
data(managers)
table.AnnualizedReturns(managers[,1:8])
|
session <- RevoIOQ:::saveRUnitSession(packages=c("survival","splines"))
melanom <- data.frame(no = c(789, 13, 97, 16, 21, 469, 685, 7,
932, 944, 558, 612, 2, 233, 418, 765, 777, 61, 67,
819, 10, 15, 47, 9, 907, 758, 8, 400, 232, 18, 4,
373, 43, 498, 17, 834, 779, 549, 608, 631, 834, 322,
432, 57, 811, 455, 971, 29, 636, 10, 3, 66, 468, 790,
130, 402, 808, 83, 390, 346, 802, 892, 605, 466, 310,
966, 113, 804, 992, 748, 494, 533, 878, 11, 2, 910,
982, 293, 327, 20, 490, 576, 205, 890, 746, 901, 394,
943, 571, 602, 342, 726, 393, 61, 695, 858, 272, 70,
208, 278, 232, 389, 52, 697, 230, 830, 135, 372, 768,
599, 761, 644, 401, 234, 31, 11, 676, 236, 988, 670,
720, 737, 24, 974, 875, 412, 338, 476, 531, 208, 441,
414, 458, 14, 530, 124, 514, 572, 609, 50, 27, 522,
359, 756, 396, 986, 290, 748, 535, 717, 887, 600, 698,
664, 84, 311, 955, 731, 222, 221, 824, 977, 194, 320,
842, 422, 745, 652, 735, 469, 510, 558, 734, 16, 327,
459, 382, 624, 446, 809, 148, 536, 464, 240, 658, 123,
518, 809, 554, 508, 445, 472, 294, 548, 415, 86, 175,
493, 536, 52, 317, 798, 806, 606, 328), status =
as.factor(c(3, 3, 2, 3, 1, 1, 1, 1, 3, 1, 1, 3,
1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
1, 2, 1, 2, 2, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, 1,
2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2,
2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 1, 1, 2, 3, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2,
2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2,
2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2,
2, 2, 2, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)),
days = c(10, 30, 35, 99, 185, 204, 210, 232, 232, 279,
295, 355, 386, 426, 469, 493, 529, 621, 629, 659, 667,
718, 752, 779, 793, 817, 826, 833, 858, 869, 872, 967,
977, 982, 1041, 1055, 1062, 1075, 1156, 1228, 1252, 1271,
1312, 1427, 1435, 1499, 1506, 1508, 1510, 1512, 1516, 1525,
1542, 1548, 1557, 1560, 1563, 1584, 1605, 1621, 1627,
1634, 1641, 1641, 1648, 1652, 1654, 1654, 1667, 1678,
1685, 1690, 1710, 1710, 1726, 1745, 1762, 1779, 1787,
1787, 1793, 1804, 1812, 1836, 1839, 1839, 1854, 1856,
1860, 1864, 1899, 1914, 1919, 1920, 1927, 1933, 1942,
1955, 1956, 1958, 1963, 1970, 2005, 2007, 2011, 2024,
2028, 2038, 2056, 2059, 2061, 2062, 2075, 2085, 2102,
2103, 2104, 2108, 2112, 2150, 2156, 2165, 2209, 2227,
2227, 2256, 2264, 2339, 2361, 2387, 2388, 2403, 2426,
2426, 2431, 2460, 2467, 2492, 2493, 2521, 2542, 2559,
2565, 2570, 2660, 2666, 2676, 2738, 2782, 2787, 2984,
3032, 3040, 3042, 3067, 3079, 3101, 3144, 3152, 3154,
3180, 3182, 3185, 3199, 3228, 3229, 3278, 3297, 3328,
3330, 3338, 3383, 3384, 3385, 3388, 3402, 3441, 3458,
3459, 3459, 3476, 3523, 3667, 3695, 3695, 3776, 3776,
3830, 3856, 3872, 3909, 3968, 4001, 4103, 4119, 4124,
4207, 4310, 4390, 4479, 4492, 4668, 4688, 4926, 5565
), ulc = as.factor(c(1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2,
2, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
2, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2,
2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 2,
1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 2, 2,
1, 1, 2, 2, 1, 2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2,
1, 2, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1,
1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1,
1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1,
2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2,
1, 1, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2
)), thick = c(676, 65, 134, 290, 1208, 484, 516, 1288,
322, 741, 419, 16, 387, 484, 242, 1256, 580, 706, 548,
773, 1385, 234, 419, 404, 484, 32, 854, 258, 356, 354,
97, 483, 162, 644, 1466, 258, 387, 354, 134, 224, 387,
354, 1742, 129, 322, 129, 451, 838, 194, 16, 258, 129,
16, 162, 129, 210, 32, 81, 113, 516, 162, 137, 24,
81, 129, 129, 97, 113, 580, 129, 48, 162, 226, 58,
97, 258, 81, 354, 97, 178, 194, 129, 322, 153, 129,
162, 162, 32, 484, 129, 97, 306, 354, 162, 258, 194,
81, 773, 97, 1288, 258, 409, 64, 97, 322, 162, 387,
32, 32, 322, 226, 306, 258, 65, 113, 81, 97, 176,
194, 65, 97, 564, 966, 10, 548, 226, 483, 97, 97,
516, 81, 290, 387, 194, 16, 64, 226, 145, 482, 129,
789, 81, 354, 129, 64, 322, 145, 48, 194, 16, 16,
129, 194, 354, 81, 65, 709, 16, 162, 162, 129, 612,
48, 64, 322, 194, 258, 258, 81, 81, 322, 32, 322,
274, 484, 162, 65, 145, 65, 129, 162, 354, 322, 65,
103, 709, 129, 65, 178, 1224, 806, 81, 210, 387, 65,
194, 65, 210, 194, 113, 706, 612, 48, 226, 290),
sex = as.factor(c(2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2,
1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1,
1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2,
2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
2, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2,
2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 1, 2, 2,
2, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2,
2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1,
1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1,
2, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2,
1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1,
2, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1,
2, 1, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 1, 1)))
attach(melanom)
require(survival)
"KM.test.stress" <- function()
{
surv.all <- survfit(Surv(days, status==1)~1)
summary(surv.all)
plot(surv.all)
surv.bysex <- survfit(Surv(days, status==1)~sex)
summary(surv.bysex)
plot(surv.bysex, conf.int=T)
dev.off()
}
"logrank.test.stress" <- function()
{
survdiff(Surv(days, status==1)~ sex)
survdiff(Surv(days, status==1)~ sex + strata(ulc))
}
"coxph.test.stress" <- function()
{
fit.single <- summary(coxph(Surv(days, status==1) ~ sex))
fit.strat <- summary(coxph(Surv(days, status == 1) ~ sex + log(thick) + strata(ulc)))
}
"test.KM.test.stress" <- function()
{
res <- try(KM.test.stress())
checkTrue(!is(res, "try-error"), msg="KM stress test failed")
}
"test.logrank.test.stress" <- function()
{
res <- try(logrank.test.stress())
checkTrue(!is(res, "try-error"), msg="logrank stress test failed")
}
"test.coxph.test.stress" <- function()
{
res <- try(coxph.test.stress())
checkTrue(!is(res, "try-error"), msg="coxph stress test failed")
}
"testzzz.restore.session" <- function()
{
if ("melanom" %in% search()) detach("melanom")
checkTrue(RevoIOQ:::restoreRUnitSession(session), msg="Session restoration failed")
}
|
library(BART)
set.seed(12)
N=50
P=3
x.train=matrix(runif(N*P, -1, 1), nrow=N, ncol=P)
y=x.train[ , 1]^3
x.miss=matrix(1*(runif(N*P)<0.05), nrow=N, ncol=P)
x.train=x.train*(1-x.miss)
x.train[x.train==0]=NA
post=gbart(x.train, y, x.train)
summary(post$yhat.train.mean)
summary(post$yhat.test.mean)
plot(post$yhat.train.mean, post$yhat.test.mean)
|
set_ipd <- function(data,
study,
trt,
y = NULL,
r = NULL, E = NULL,
trt_ref = NULL,
trt_class = NULL) {
if (!inherits(data, "data.frame")) abort("Argument `data` should be a data frame")
if (nrow(data) == 0) {
return(
structure(
list(agd_arm = NULL,
agd_contrast = NULL,
ipd = NULL,
treatments = NULL,
classes = NULL,
studies = NULL),
class = "nma_data")
)
}
if (missing(study)) abort("Specify `study`")
.study <- pull_non_null(data, enquo(study))
if (is.null(.study)) abort("`study` cannot be NULL")
check_study(.study)
if (is.factor(.study)) {
study_original_levels <- levels(.study)
.study <- forcats::fct_drop(.study)
} else {
study_original_levels <- NULL
}
if (missing(trt)) abort("Specify `trt`")
.trt <- pull_non_null(data, enquo(trt))
if (is.null(.trt)) abort("`trt` cannot be NULL")
check_trt(.trt)
if (is.factor(.trt)) {
trt_original_levels <- levels(.trt)
.trt <- forcats::fct_drop(.trt)
} else {
trt_original_levels <- NULL
}
single_arm_studies <- tibble::tibble(.study, .trt) %>%
dplyr::distinct(.data$.study, .data$.trt) %>%
dplyr::group_by(.data$.study) %>%
dplyr::filter(dplyr::n() == 1) %>%
dplyr::pull(.data$.study)
if (length(single_arm_studies)) {
abort(glue::glue("Single-arm studies are not supported: issue with stud{if (length(single_arm_studies) > 1) 'ies' else 'y'} ",
glue::glue_collapse(glue::double_quote(single_arm_studies), sep = ", ", last = " and "), "."))
}
.trtclass <- pull_non_null(data, enquo(trt_class))
if (!is.null(.trtclass)) {
check_trt_class(.trtclass, .trt)
if (is.factor(.trtclass)) {
trtclass_original_levels <- levels(.trtclass)
.trtclass <- forcats::fct_drop(.trtclass)
} else {
trtclass_original_levels <- NULL
}
}
if (!is.null(trt_ref) && length(trt_ref) > 1) abort("`trt_ref` must be length 1.")
.y <- pull_non_null(data, enquo(y))
.r <- pull_non_null(data, enquo(r))
.E <- pull_non_null(data, enquo(E))
check_outcome_continuous(.y, with_se = FALSE)
if (!is.null(.r) && inherits(.r, c("multi_ordered", "multi_competing"))) {
if (inherits(.r, "multi_competing")) abort("Competing multinomial outcomes are not yet supported.")
if (any(! .r[!is.na(.r)] %in% c(0, 1))) abort("Multinomial outcome `r` must equal 0 or 1")
if (any(r_zero_rows <- rowSums(.r, na.rm = TRUE) == 0))
abort(glue::glue("Individual{if (sum(r_zero_rows) > 1) 's' else ''} without outcomes in any category, ",
"row{if (sum(r_zero_rows) > 1) 's' else ''} ",
glue::glue_collapse(which(r_zero_rows), sep = ", ", last = " and "), "."))
if (any(r_multi_rows <- rowSums(.r, na.rm = TRUE) > 1))
abort(glue::glue("Individual{if (sum(r_multi_rows) > 1) 's' else ''} with outcomes in more than one category, ",
"row{if (sum(r_multi_rows) > 1) 's' else ''} ",
glue::glue_collapse(which(r_multi_rows), sep = ", ", last = " and "), "."))
} else {
check_outcome_binary(.r, .E)
}
o_type <- get_outcome_type(y = .y, se = NULL,
r = .r, n = NULL, E = .E)
d <- tibble::tibble(
.study = nfactor(.study),
.trt = nfactor(.trt)
)
if (!is.null(trt_ref)) {
trt_ref <- as.character(trt_ref)
lvls_trt <- levels(d$.trt)
if (! trt_ref %in% lvls_trt)
abort(sprintf("`trt_ref` does not match a treatment in the data.\nSuitable values are: %s",
ifelse(length(lvls_trt) <= 5,
paste0(lvls_trt, collapse = ", "),
paste0(paste0(lvls_trt[1:5], collapse = ", "), ", ..."))))
d$.trt <- forcats::fct_relevel(d$.trt, trt_ref)
}
if (!is.null(.trtclass)) {
d <- tibble::add_column(d, .trtclass = nfactor(.trtclass))
class_lookup <- d %>%
dplyr::distinct(.data$.trt, .data$.trtclass) %>%
dplyr::arrange(.data$.trt)
class_ref <- as.character(class_lookup[[1, ".trtclass"]])
d$.trtclass <- forcats::fct_relevel(d$.trtclass, class_ref)
classes <- forcats::fct_relevel(nfactor(class_lookup$.trtclass), class_ref)
} else {
classes <- NULL
}
if (o_type == "continuous") {
d <- tibble::add_column(d, .y = .y)
} else if (o_type == "binary") {
d <- tibble::add_column(d, .r = .r)
} else if (o_type == "rate") {
d <- tibble::add_column(d, .r = .r, .E = .E)
} else if (o_type %in% c("ordered", "competing")) {
.r <- unclass(.r)
d <- tibble::add_column(d, .r = .r)
}
drop_reserved <- setdiff(colnames(data), colnames(d))
d <- dplyr::bind_cols(d, data[, drop_reserved, drop = FALSE])
d <- drop_original(d, data, enquo(study))
d <- drop_original(d, data, enquo(trt))
if (!is.null(.trtclass)) d <- drop_original(d, data, enquo(trt_class))
out <- structure(
list(agd_arm = NULL,
agd_contrast = NULL,
ipd = d,
treatments = forcats::fct_unique(d$.trt),
classes = classes,
studies = forcats::fct_unique(d$.study),
outcome = list(agd_arm = NA, agd_contrast = NA, ipd = o_type)),
class = "nma_data")
if (is.null(trt_ref)) {
trt_ref <- get_default_trt_ref(out)
trt_sort <- order(forcats::fct_relevel(out$treatments, trt_ref))
out$treatments <- .default(forcats::fct_relevel(out$treatments, trt_ref)[trt_sort])
out$ipd$.trt <- forcats::fct_relevel(out$ipd$.trt, trt_ref)
if (!is.null(.trtclass)) {
class_ref <- as.character(out$classes[trt_sort[1]])
if (!is.null(trtclass_original_levels))
class_ref <- c(class_ref,
setdiff(intersect(trtclass_original_levels, levels(out$classes)),
class_ref))
out$ipd$.trtclass <- forcats::fct_relevel(out$ipd$.trtclass, class_ref)
out$classes <- forcats::fct_relevel(out$classes, class_ref)[trt_sort]
}
}
attr(out$treatments, "original_levels") <- trt_original_levels
attr(out$studies, "original_levels") <- study_original_levels
if (!is.null(.trtclass)) attr(out$classes, "original_levels") <- trtclass_original_levels
return(out)
}
set_agd_arm <- function(data,
study,
trt,
y = NULL, se = NULL,
r = NULL, n = NULL, E = NULL,
sample_size = NULL,
trt_ref = NULL,
trt_class = NULL) {
if (!inherits(data, "data.frame")) abort("Argument `data` should be a data frame")
if (nrow(data) == 0) {
return(
structure(
list(agd_arm = NULL,
agd_contrast = NULL,
ipd = NULL,
treatments = NULL,
classes = NULL,
studies = NULL),
class = "nma_data")
)
}
if (missing(study)) abort("Specify `study`")
.study <- pull_non_null(data, enquo(study))
if (is.null(.study)) abort("`study` cannot be NULL")
check_study(.study)
if (is.factor(.study)) {
study_original_levels <- levels(.study)
.study <- forcats::fct_drop(.study)
} else {
study_original_levels <- NULL
}
if (missing(trt)) abort("Specify `trt`")
.trt <- pull_non_null(data, enquo(trt))
if (is.null(.trt)) abort("`trt` cannot be NULL")
check_trt(.trt)
if (is.factor(.trt)) {
trt_original_levels <- levels(.trt)
.trt <- forcats::fct_drop(.trt)
} else {
trt_original_levels <- NULL
}
single_arm_studies <- tibble::tibble(.study, .trt) %>%
dplyr::group_by(.data$.study) %>%
dplyr::filter(dplyr::n() == 1) %>%
dplyr::pull(.data$.study)
if (length(single_arm_studies)) {
abort(glue::glue("Single-arm studies are not supported: issue with stud{if (length(single_arm_studies) > 1) 'ies' else 'y'} ",
glue::glue_collapse(glue::double_quote(single_arm_studies), sep = ", ", last = " and "), "."))
}
.trtclass <- pull_non_null(data, enquo(trt_class))
if (!is.null(.trtclass)) {
check_trt_class(.trtclass, .trt)
if (is.factor(.trtclass)) {
trtclass_original_levels <- levels(.trtclass)
.trtclass <- forcats::fct_drop(.trtclass)
} else {
trtclass_original_levels <- NULL
}
}
if (!is.null(trt_ref) && length(trt_ref) > 1) abort("`trt_ref` must be length 1.")
.y <- pull_non_null(data, enquo(y))
.se <- pull_non_null(data, enquo(se))
.r <- pull_non_null(data, enquo(r))
.n <- pull_non_null(data, enquo(n))
.E <- pull_non_null(data, enquo(E))
check_outcome_continuous(.y, .se, with_se = TRUE)
if (!is.null(.r) && inherits(.r, c("multi_ordered", "multi_competing"))) {
if (inherits(.r, "multi_competing")) abort("Competing multinomial outcomes are not yet supported.")
} else {
check_outcome_count(.r, .n, .E)
}
o_type <- get_outcome_type(y = .y, se = .se,
r = .r, n = .n, E = .E)
.sample_size <- pull_non_null(data, enquo(sample_size))
if (!is.null(.sample_size)) {
check_sample_size(.sample_size)
} else if (o_type == "count") {
.sample_size <- .n
} else if (o_type %in% c("ordered", "competing")) {
.sample_size <- rowSums(.r, na.rm = TRUE)
}
else inform("Note: Optional argument `sample_size` not provided, some features may not be available (see ?set_agd_arm).")
d <- tibble::tibble(
.study = nfactor(.study),
.trt = nfactor(.trt)
)
if (!is.null(trt_ref)) {
trt_ref <- as.character(trt_ref)
lvls_trt <- levels(d$.trt)
if (! trt_ref %in% lvls_trt)
abort(sprintf("`trt_ref` does not match a treatment in the data.\nSuitable values are: %s",
ifelse(length(lvls_trt) <= 5,
paste0(lvls_trt, collapse = ", "),
paste0(paste0(lvls_trt[1:5], collapse = ", "), ", ..."))))
d$.trt <- forcats::fct_relevel(d$.trt, trt_ref)
}
if (!is.null(.trtclass)) {
d <- tibble::add_column(d, .trtclass = nfactor(.trtclass))
class_lookup <- d %>%
dplyr::distinct(.data$.trt, .data$.trtclass) %>%
dplyr::arrange(.data$.trt)
class_ref <- as.character(class_lookup[[1, ".trtclass"]])
d$.trtclass <- forcats::fct_relevel(d$.trtclass, class_ref)
classes <- forcats::fct_relevel(nfactor(class_lookup$.trtclass), class_ref)
} else {
classes <- NULL
}
if (o_type == "continuous") {
d <- tibble::add_column(d, .y = .y, .se = .se)
} else if (o_type == "count") {
d <- tibble::add_column(d, .r = .r, .n = .n)
} else if (o_type == "rate") {
d <- tibble::add_column(d, .r = .r, .E = .E)
} else if (o_type %in% c("ordered", "competing")) {
.r <- unclass(.r)
d <- tibble::add_column(d, .r = .r)
}
if (!is.null(.sample_size)) d <- tibble::add_column(d, .sample_size = .sample_size)
drop_reserved <- setdiff(colnames(data), colnames(d))
d <- dplyr::bind_cols(d, data[, drop_reserved, drop = FALSE])
d <- drop_original(d, data, enquo(study))
d <- drop_original(d, data, enquo(trt))
if (!is.null(.trtclass)) d <- drop_original(d, data, enquo(trt_class))
out <- structure(
list(agd_arm = d,
agd_contrast = NULL,
ipd = NULL,
treatments = forcats::fct_unique(d$.trt),
classes = classes,
studies = forcats::fct_unique(d$.study),
outcome = list(agd_arm = o_type, agd_contrast = NA, ipd = NA)),
class = "nma_data")
if (is.null(trt_ref)) {
trt_ref <- get_default_trt_ref(out)
trt_sort <- order(forcats::fct_relevel(out$treatments, trt_ref))
out$treatments <- .default(forcats::fct_relevel(out$treatments, trt_ref)[trt_sort])
out$agd_arm$.trt <- forcats::fct_relevel(out$agd_arm$.trt, trt_ref)
if (!is.null(.trtclass)) {
class_ref <- as.character(out$classes[trt_sort[1]])
if (!is.null(trtclass_original_levels))
class_ref <- c(class_ref,
setdiff(intersect(trtclass_original_levels, levels(out$classes)),
class_ref))
out$agd_arm$.trtclass <- forcats::fct_relevel(out$agd_arm$.trtclass, class_ref)
out$classes <- forcats::fct_relevel(out$classes, class_ref)[trt_sort]
}
}
attr(out$treatments, "original_levels") <- trt_original_levels
attr(out$studies, "original_levels") <- study_original_levels
if (!is.null(.trtclass)) attr(out$classes, "original_levels") <- trtclass_original_levels
return(out)
}
set_agd_contrast <- function(data,
study,
trt,
y = NULL, se = NULL,
sample_size = NULL,
trt_ref = NULL,
trt_class = NULL) {
if (!inherits(data, "data.frame")) abort("Argument `data` should be a data frame")
if (nrow(data) == 0) {
return(
structure(
list(agd_arm = NULL,
agd_contrast = NULL,
ipd = NULL,
treatments = NULL,
classes = NULL,
studies = NULL),
class = "nma_data")
)
}
if (missing(study)) abort("Specify `study`")
.study <- pull_non_null(data, enquo(study))
if (is.null(.study)) abort("`study` cannot be NULL")
check_study(.study)
if (is.factor(.study)) {
study_original_levels <- levels(.study)
.study <- forcats::fct_drop(.study)
} else {
study_original_levels <- NULL
}
if (missing(trt)) abort("Specify `trt`")
.trt <- pull_non_null(data, enquo(trt))
if (is.null(.trt)) abort("`trt` cannot be NULL")
check_trt(.trt)
if (is.factor(.trt)) {
trt_original_levels <- levels(.trt)
.trt <- forcats::fct_drop(.trt)
} else {
trt_original_levels <- NULL
}
single_arm_studies <- tibble::tibble(.study, .trt) %>%
dplyr::group_by(.data$.study) %>%
dplyr::filter(dplyr::n() == 1) %>%
dplyr::pull(.data$.study)
if (length(single_arm_studies)) {
abort(glue::glue("Single-arm studies are not supported: issue with stud{if (length(single_arm_studies) > 1) 'ies' else 'y'} ",
glue::glue_collapse(glue::double_quote(single_arm_studies), sep = ", ", last = " and "), "."))
}
.trtclass <- pull_non_null(data, enquo(trt_class))
if (!is.null(.trtclass)) {
check_trt_class(.trtclass, .trt)
if (is.factor(.trtclass)) {
trtclass_original_levels <- levels(.trtclass)
.trtclass <- forcats::fct_drop(.trtclass)
} else {
trtclass_original_levels <- NULL
}
}
if (!is.null(trt_ref) && length(trt_ref) > 1) abort("`trt_ref` must be length 1.")
.y <- pull_non_null(data, enquo(y))
.se <- pull_non_null(data, enquo(se))
if (is.null(.y)) abort("Specify continuous outcome `y`")
if (rlang::is_list(.y) || !is.null(dim(.y)))
abort("Continuous outcome `y` must be a regular column (not a list or matrix column)")
if (is.null(.se)) abort("Specify standard error `se`")
if (rlang::is_list(.se) || !is.null(dim(.se)))
abort("Standard error `se` must be a regular column (not a list or matrix column)")
.sample_size <- pull_non_null(data, enquo(sample_size))
if (!is.null(.sample_size)) {
check_sample_size(.sample_size)
} else {
inform("Note: Optional argument `sample_size` not provided, some features may not be available (see ?set_agd_contrast).")
}
bl <- is.na(.y)
tibble::tibble(.study, .trt, bl, .se) %>%
dplyr::group_by(.data$.study) %>%
dplyr::mutate(n_arms = dplyr::n(),
n_bl = sum(.data$bl)) %>%
{
if (any(.$n_bl > 1))
abort("Multiple baseline arms (where y = NA) in a study or studies.")
else if (any(.$n_bl == 0))
abort("Study or studies without a specified baseline arm (where y = NA).")
else .
} %>%
dplyr::filter(.data$bl, .data$n_arms > 2) %>%
{
check_outcome_continuous(1, .$.se, with_se = TRUE,
append = " on baseline arms in studies with >2 arms.")
}
check_outcome_continuous(.y[!bl], .se[!bl], with_se = TRUE,
append = " for non-baseline rows (i.e. those specifying contrasts against baseline).")
o_type <- get_outcome_type(y = .y[!bl], se = .se[!bl],
r = NULL, n = NULL, E = NULL)
d <- tibble::tibble(
.study = nfactor(.study),
.trt = nfactor(.trt),
.y = .y,
.se = .se)
if (!is.null(trt_ref)) {
trt_ref <- as.character(trt_ref)
lvls_trt <- levels(d$.trt)
if (! trt_ref %in% lvls_trt)
abort(sprintf("`trt_ref` does not match a treatment in the data.\nSuitable values are: %s",
ifelse(length(lvls_trt) <= 5,
paste0(lvls_trt, collapse = ", "),
paste0(paste0(lvls_trt[1:5], collapse = ", "), ", ..."))))
d$.trt <- forcats::fct_relevel(d$.trt, trt_ref)
}
if (!is.null(.trtclass)) {
d <- tibble::add_column(d, .trtclass = nfactor(.trtclass))
class_lookup <- d %>%
dplyr::distinct(.data$.trt, .data$.trtclass) %>%
dplyr::arrange(.data$.trt)
class_ref <- as.character(class_lookup[[1, ".trtclass"]])
d$.trtclass <- forcats::fct_relevel(d$.trtclass, class_ref)
classes <- forcats::fct_relevel(nfactor(class_lookup$.trtclass), class_ref)
} else {
classes <- NULL
}
if (!is.null(.sample_size)) {
d <- tibble::add_column(d, .sample_size = .sample_size)
}
drop_reserved <- setdiff(colnames(data), colnames(d))
d <- dplyr::bind_cols(d, data[, drop_reserved, drop = FALSE])
d <- drop_original(d, data, enquo(study))
d <- drop_original(d, data, enquo(trt))
if (!is.null(.trtclass)) d <- drop_original(d, data, enquo(trt_class))
d <- dplyr::mutate(d, .study_inorder = forcats::fct_inorder(.data$.study)) %>%
dplyr::arrange(.data$.study_inorder) %>%
dplyr::select(-.data$.study_inorder)
out <- structure(
list(agd_arm = NULL,
agd_contrast = d,
ipd = NULL,
treatments = forcats::fct_unique(d$.trt),
classes = classes,
studies = forcats::fct_unique(d$.study),
outcome = list(agd_arm = NA, agd_contrast = o_type, ipd = NA)),
class = "nma_data")
if (is.null(trt_ref)) {
trt_ref <- get_default_trt_ref(out)
trt_sort <- order(forcats::fct_relevel(out$treatments, trt_ref))
out$treatments <- .default(forcats::fct_relevel(out$treatments, trt_ref)[trt_sort])
out$agd_contrast$.trt <- forcats::fct_relevel(out$agd_contrast$.trt, trt_ref)
if (!is.null(.trtclass)) {
class_ref <- as.character(out$classes[trt_sort[1]])
if (!is.null(trtclass_original_levels))
class_ref <- c(class_ref,
setdiff(intersect(trtclass_original_levels, levels(out$classes)),
class_ref))
out$agd_contrast$.trtclass <- forcats::fct_relevel(out$agd_contrast$.trtclass, class_ref)
out$classes <- forcats::fct_relevel(out$classes, class_ref)[trt_sort]
}
}
attr(out$treatments, "original_levels") <- trt_original_levels
attr(out$studies, "original_levels") <- study_original_levels
if (!is.null(.trtclass)) attr(out$classes, "original_levels") <- trtclass_original_levels
return(out)
}
combine_network <- function(..., trt_ref) {
s <- list(...)
if (!purrr::every(s, inherits, what = "nma_data")) {
abort("Expecting to combine objects of class `nma_data`, created using set_* functions")
}
trts <- stringr::str_sort(forcats::lvls_union(purrr::map(s, "treatments")), numeric = TRUE)
trt_original_levels <- purrr::map(purrr::map(s, "treatments"), attr, which = "original_levels")
if (!any(purrr::map_lgl(trt_original_levels, is.null)) &&
all(purrr::map_lgl(trt_original_levels, ~identical(., trt_original_levels[[1]])))) {
trt_original_levels <- trt_original_levels[[1]]
trts <- intersect(trt_original_levels, trts)
} else {
trt_original_levels <- NULL
}
if (!missing(trt_ref)) {
if (! trt_ref %in% trts) {
abort(sprintf("`trt_ref` does not match a treatment in the network.\nSuitable values are: %s",
ifelse(length(trts) <= 5,
paste0(trts, collapse = ", "),
paste0(paste0(trts[1:5], collapse = ", "), ", ..."))))
}
trts <- c(trt_ref, setdiff(trts, trt_ref))
}
has_classes <- purrr::map_lgl(purrr::map(s, "classes"), ~!is.null(.))
if (all(has_classes)) {
class_lookup <- tibble::tibble(.trt = forcats::fct_c(!!! purrr::map(s, "treatments")),
.trtclass = forcats::fct_c(!!! purrr::map(s, "classes"))) %>%
dplyr::mutate(.trt = forcats::fct_relevel(.data$.trt, trts)) %>%
dplyr::distinct(.data$.trt, .data$.trtclass) %>%
dplyr::arrange(.data$.trt)
check_trt_class(class_lookup$.trtclass, class_lookup$.trt)
class_lvls <- stringr::str_sort(levels(class_lookup$.trtclass), numeric = TRUE)
class_original_levels <- purrr::map(purrr::map(s, "classes"), attr, which = "original_levels")
if (!any(purrr::map_lgl(class_original_levels, is.null)) &&
all(purrr::map_lgl(class_original_levels, ~identical(., class_original_levels[[1]])))) {
class_original_levels <- class_original_levels[[1]]
class_lvls <- intersect(class_original_levels, class_lvls)
} else {
class_original_levels <- NULL
}
class_ref <- as.character(class_lookup[[1, ".trtclass"]])
class_lvls <- c(class_ref, setdiff(class_lvls, class_ref))
class_lookup$.trtclass <- forcats::fct_relevel(class_lookup$.trtclass, class_lvls)
classes <- class_lookup$.trtclass
} else if (any(has_classes)) {
warn("Not all data sources have defined treatment classes. Removing treatment class information.")
classes <- NULL
} else {
classes <- NULL
}
all_studs <- purrr::flatten_chr(purrr::map(s, ~levels(.$studies)))
if (anyDuplicated(all_studs)) {
abort(sprintf("Studies with same label found in multiple data sources: %s",
paste0(unique(all_studs[duplicated(all_studs)]), collapse = ", ")))
}
studs <- stringr::str_sort(forcats::lvls_union(purrr::map(s, "studies")), numeric = TRUE)
study_original_levels <- purrr::map(purrr::map(s, "studies"), attr, which = "original_levels")
if (!any(purrr::map_lgl(study_original_levels, is.null)) &&
all(purrr::map_lgl(study_original_levels, ~identical(., study_original_levels[[1]])))) {
study_original_levels <- study_original_levels[[1]]
studs <- intersect(study_original_levels, studs)
} else {
study_original_levels <- NULL
}
ipd <- purrr::map(s, "ipd")
if (!rlang::is_empty(ipd)) {
for (j in 1:length(ipd)) {
if (rlang::is_empty(ipd[[j]])) next
ipd[[j]]$.trt <- forcats::lvls_expand(ipd[[j]]$.trt, trts)
ipd[[j]]$.study <- forcats::lvls_expand(ipd[[j]]$.study, studs)
if (!is.null(classes)) ipd[[j]]$.trtclass <- forcats::lvls_expand(ipd[[j]]$.trtclass, class_lvls)
}
}
agd_arm <- purrr::map(s, "agd_arm")
if (!rlang::is_empty(agd_arm)) {
for (j in 1:length(agd_arm)) {
if (rlang::is_empty(agd_arm[[j]])) next
agd_arm[[j]]$.trt <- forcats::lvls_expand(agd_arm[[j]]$.trt, trts)
agd_arm[[j]]$.study <- forcats::lvls_expand(agd_arm[[j]]$.study, studs)
if (!is.null(classes))
agd_arm[[j]]$.trtclass <- forcats::lvls_expand(agd_arm[[j]]$.trtclass, class_lvls)
}
}
agd_contrast <- purrr::map(s, "agd_contrast")
if (!rlang::is_empty(agd_contrast)) {
for (j in 1:length(agd_contrast)) {
if (rlang::is_empty(agd_contrast[[j]])) next
agd_contrast[[j]]$.trt <- forcats::lvls_expand(agd_contrast[[j]]$.trt, trts)
agd_contrast[[j]]$.study <- forcats::lvls_expand(agd_contrast[[j]]$.study, studs)
if (!is.null(classes))
agd_contrast[[j]]$.trtclass <- forcats::lvls_expand(agd_contrast[[j]]$.trtclass, class_lvls)
}
}
o_ipd <- unique(purrr::map_chr(purrr::map(s, "outcome"), "ipd"))
o_ipd <- o_ipd[!is.na(o_ipd)]
if (length(o_ipd) > 1) abort("Multiple outcome types present in IPD.")
if (length(o_ipd) == 0) o_ipd <- NA
o_agd_arm <- unique(purrr::map_chr(purrr::map(s, "outcome"), "agd_arm"))
o_agd_arm <- o_agd_arm[!is.na(o_agd_arm)]
if (length(o_agd_arm) > 1) abort("Multiple outcome types present in AgD (arm-based).")
if (length(o_agd_arm) == 0) o_agd_arm <- NA
o_agd_contrast <- unique(purrr::map_chr(purrr::map(s, "outcome"), "agd_contrast"))
o_agd_contrast <- o_agd_contrast[!is.na(o_agd_contrast)]
if (length(o_agd_contrast) > 1) abort("Multiple outcome types present in AgD (contrast-based).")
if (length(o_agd_contrast) == 0) o_agd_contrast <- NA
outcome <- list(agd_arm = o_agd_arm,
agd_contrast = o_agd_contrast,
ipd = o_ipd)
check_outcome_combination(outcome)
if (o_ipd %in% c("ordered", "competing"))
check_multi_combine(purrr::map(ipd, ".r"))
if (o_agd_arm %in% c("ordered", "competing"))
check_multi_combine(purrr::map(agd_arm, ".r"))
if (o_ipd %in% c("ordered", "competing") && o_agd_arm %in% c("ordered", "competing"))
check_multi_combine(purrr::map(c(ipd, agd_arm), ".r"))
ipd <- dplyr::bind_rows(ipd)
agd_arm <- dplyr::bind_rows(agd_arm)
agd_contrast <- dplyr::bind_rows(agd_contrast)
out <- structure(
list(agd_arm = agd_arm,
agd_contrast = agd_contrast,
ipd = ipd,
treatments = factor(trts, levels = trts),
classes = classes,
studies = factor(studs, levels = studs),
outcome = outcome),
class = "nma_data")
if (missing(trt_ref)) {
trt_ref <- get_default_trt_ref(out)
trt_sort <- order(forcats::fct_relevel(out$treatments, trt_ref))
out$treatments <- .default(forcats::fct_relevel(out$treatments, trt_ref)[trt_sort])
if (has_ipd(out))
out$ipd$.trt <- forcats::fct_relevel(out$ipd$.trt, trt_ref)
if (has_agd_arm(out))
out$agd_arm$.trt <- forcats::fct_relevel(out$agd_arm$.trt, trt_ref)
if (has_agd_contrast(out))
out$agd_contrast$.trt <- forcats::fct_relevel(out$agd_contrast$.trt, trt_ref)
if (!is.null(classes)) {
class_ref <- as.character(out$classes[trt_sort[1]])
out$classes <- forcats::fct_relevel(out$classes, class_ref)[trt_sort]
if (has_ipd(out))
out$ipd$.trtclass <- forcats::fct_relevel(out$ipd$.trtclass, class_ref)
if (has_agd_arm(out))
out$agd_arm$.trtclass <- forcats::fct_relevel(out$agd_arm$.trtclass, class_ref)
if (has_agd_contrast(out))
out$agd_contrast$.trtclass <- forcats::fct_relevel(out$agd_contrast$.trtclass, class_ref)
}
}
attr(out$treatments, "original_levels") <- trt_original_levels
attr(out$studies, "original_levels") <- study_original_levels
if (!is.null(classes)) attr(out$classes, "original_levels") <- class_original_levels
return(out)
}
multi <- function(..., inclusive = FALSE, type = c("ordered", "competing")) {
if (packageVersion("dplyr") < "1.0.0")
abort("Multinomial outcomes require `dplyr` package version 1.0.0 or later.")
if (!rlang::is_bool(inclusive)) abort("`inclusive` must be a logical value TRUE/FALSE")
type <- rlang::arg_match(type)
if (type == "competing" && inclusive) {
warn("Ignoring inclusive = TRUE, competing outcomes are always given by exclusive counts.")
inclusive <- FALSE
}
q_dots <- rlang::enquos(..., .named = TRUE)
if (length(q_dots) < 2) abort("At least 2 outcomes must be specified in `...`")
if (anyDuplicated(names(q_dots))) {
dups <- unique(names(q_dots)[duplicated(names(q_dots))])
abort(glue::glue("Duplicate outcome category labels ",
glue::glue_collapse(glue::double_quote(dups), sep = ", ", last = " and "),
"."))
}
dots <- purrr::map(q_dots, rlang::eval_tidy)
dots_lengths <- lengths(dots)
if (length(unique(dots_lengths[dots_lengths > 1])) > 1) abort("Input vectors in `...` must be the same length (or length 1).")
out <- do.call(cbind, dots)
if (!is.numeric(out)) abort("Categorical outcome count must be numeric")
if (any(is.nan(out))) abort("Categorical outcome count cannot be NaN")
if (any(is.infinite(out))) abort("Categorical outcome count cannot be Inf")
if (!rlang::is_integerish(out)) abort("Categorical outcome count must be integer-valued")
if (any(out < 0, na.rm = TRUE)) abort("Categorical outcome count must be non-negative")
if (type == "ordered") {
if (any(c1_na <- is.na(out[, 1]))) {
abort(glue::glue("Ordered outcome counts cannot be missing in the lowest category.\n",
"NAs found in row{if (sum(c1_na) > 1) 's' else ''} ",
glue::glue_collapse(which(c1_na), sep = ", ", width = 30, last = " and "), "."))
}
}
if (any(only1 <- apply(out, 1, function(x) sum(!is.na(x))) < 2)) {
abort(glue::glue("Outcome counts must be present for at least 2 categories.\n",
"Issues in row{if (sum(only1) > 1) 's' else ''} ",
glue::glue_collapse(which(only1), sep = ", ", width = 30, last = " and "), "."))
}
if (inclusive) {
if (any(non_decreasing <- apply(out, 1, function(x) max(diff(x[!is.na(x)]))) > 0)) {
abort(glue::glue("Inclusive ordered outcome counts must be decreasing or constant across increasing categories.\n",
"Increasing counts found in row{if (sum(non_decreasing) > 1) 's' else ''} ",
glue::glue_collapse(which(non_decreasing), sep = ", ", width = 30, last = " and "), "."))
}
ncat <- ncol(out)
for (i in 1:nrow(out)) {
j <- 1L
k <- 2L
while (k <= ncat) {
if (is.na(out[i, k])) {
k <- k + 1L
} else {
out[i, j] <- out[i, j] - out[i, k]
j <- k
k <- k + 1L
}
}
}
}
class(out) <- c(switch(type,
ordered = "multi_ordered",
competing = "multi_competing"),
class(out))
return(out)
}
pull_non_null <- function(data, var) {
var_null <- rlang::quo_is_missing(var) | rlang::quo_is_null(var)
if (!var_null) {
if (rlang::is_symbolic(rlang::quo_get_expr(var))) return(dplyr::pull(dplyr::transmute(data, {{ var }})))
else return(dplyr::pull(data, {{ var }}))
}
else return(NULL)
}
drop_original <- function(data, orig_data, var) {
e_var <- rlang::quo_get_expr(var)
if (rlang::is_symbol(e_var)) {
if (stringr::str_starts(rlang::as_name(e_var), "\\.")) return(data)
else return(dplyr::select(data, - {{ var }}))
} else if (rlang::is_integerish(e_var)) {
orig_var <- colnames(orig_data)[e_var]
if (stringr::str_starts(orig_var, "\\.")) return(data)
else return(dplyr::select(data, - {{ orig_var }}))
} else {
return(data)
}
}
get_outcome_type <- function(y, se, r, n, E) {
o <- c()
if (!is.null(y)) o <- c(o, "continuous")
if (!is.null(r)) {
if (inherits(r, "multi_ordered")) o <- c(o, "ordered")
if (inherits(r, "multi_competing")) o <- c(o, "competing")
if (!is.null(E)) o <- c(o, "rate")
if (!is.null(n)) o <- c(o, "count")
if (!inherits(r, c("multi_ordered", "multi_competing")) && is.null(n) && is.null(E)) o <- c(o, "binary")
}
if (length(o) == 0) abort("Please specify one and only one outcome.")
if (length(o) > 1) abort(glue::glue("Please specify one and only one outcome, instead of ",
glue::glue_collapse(o, sep = ", ", last = " and "), "."))
return(o)
}
check_outcome_continuous <- function(y, se = NULL, with_se = TRUE, append = NULL) {
null_y <- is.null(y)
null_se <- is.null(se)
if (with_se) {
if (!null_y && !null_se) {
if (rlang::is_list(y) || !is.null(dim(y)))
abort("Continuous outcome `y` must be a regular column (not a list or matrix column)")
if (rlang::is_list(se) || !is.null(dim(se)))
abort("Standard error `se` must be a regular column (not a list or matrix column)")
if (!is.numeric(y)) abort(paste0("Continuous outcome `y` must be numeric", append))
if (!is.numeric(se)) abort(paste0("Standard error `se` must be numeric", append))
if (any(is.nan(se))) abort(paste0("Standard error `se` cannot be NaN", append))
if (any(is.na(y))) abort(paste0("Continuous outcome `y` contains missing values", append))
if (any(is.na(se))) abort(paste0("Standard error `se` contains missing values", append))
if (any(is.infinite(se))) abort(paste0("Standard error `se` cannot be infinite", append))
if (any(se <= 0)) abort(paste0("Standard errors must be positive", append))
} else {
if (!null_y) abort(paste0("Specify standard error `se` for continuous outcome `y`", append))
if (!null_se) abort(paste0("Specify continuous outcome `y`", append))
}
invisible(list(y = y, se = se))
} else {
if (!null_y) {
if (rlang::is_list(y) || !is.null(dim(y)))
abort("Continuous outcome `y` must be a regular column (not a list or matrix column)")
if (any(is.na(y))) abort(paste0("Continuous outcome `y` contains missing values", append))
if (!is.numeric(y)) abort(paste0("Continuous outcome `y` must be numeric", append))
}
invisible(list(y = y))
}
}
check_outcome_count <- function(r, n, E) {
null_r <- is.null(r)
null_n <- is.null(n)
null_E <- is.null(E)
if (!null_n) {
if (rlang::is_list(n) || !is.null(dim(n)))
abort("Denominator `n` must be a regular column (not a list or matrix column)")
if (!is.numeric(n)) abort("Denominator `n` must be numeric")
if (any(is.na(n))) abort("Denominator `n` contains missing values")
if (any(n != trunc(n))) abort("Denominator `n` must be integer-valued")
if (any(n <= 0)) abort("Denominator `n` must be greater than zero")
if (null_r) abort("Specify outcome count `r`.")
}
if (!null_E) {
if (rlang::is_list(E) || !is.null(dim(E)))
abort("Time at risk `E` must be a regular column (not a list or matrix column)")
if (!is.numeric(E)) abort("Time at risk `E` must be numeric")
if (any(is.na(E))) abort("Time at risk `E` contains missing values")
if (any(E <= 0)) abort("Time at risk `E` must be positive")
if (null_r) abort("Specify outcome count `r`.")
}
if (!null_r) {
if (rlang::is_list(r) || !is.null(dim(r)))
abort("Outcome count `r` must be a regular column (not a list or matrix column)")
if (null_n && null_E) abort("Specify denominator `n` (count outcome) or time at risk `E` (rate outcome)")
if (!is.numeric(r)) abort("Outcome count `r` must be numeric")
if (any(is.na(r))) abort("Outcome count `r` contains missing values")
if (any(r != trunc(r))) abort("Outcome count `r` must be integer-valued")
if (!null_n && any(n < r | r < 0)) abort("Count outcome `r` must be between 0 and `n`")
if (!null_E && any(r < 0)) abort("Rate outcome count `r` must be non-negative")
}
invisible(list(r = r, n = n, E = E))
}
check_outcome_binary <- function(r, E) {
null_r <- is.null(r)
null_E <- is.null(E)
if (!null_E) {
if (null_r) {
abort("Specify count `r` for rate outcome")
} else {
if (rlang::is_list(r) || !is.null(dim(r)))
abort("Rate outcome count `r` must be a regular column (not a list or matrix column)")
if (rlang::is_list(E) || !is.null(dim(E)))
abort("Time at risk `E` must be a regular column (not a list or matrix column)")
if (!is.numeric(E)) abort("Time at risk `E` must be numeric")
if (any(is.na(E))) abort("Time at risk `E` contains missing values")
if (any(E <= 0)) abort("Time at risk `E` must be positive")
if (!is.numeric(r)) abort("Rate outcome count `r` must be numeric")
if (any(is.na(r))) abort("Rate outcome count `r` contains missing values")
if (any(r != trunc(r))) abort("Rate outcome count `r` must be non-negative integer")
if (any(r < 0)) abort("Rate outcome count `r` must be non-negative integer")
}
} else if (!null_r) {
if (rlang::is_list(r) || !is.null(dim(r)))
abort("Binary outcome `r` must be a regular column (not a list or matrix column)")
if (!is.numeric(r)) abort("Binary outcome `r` must be numeric")
if (any(is.na(r))) abort("Binary outcome `r` contains missing values")
if (any(! r %in% c(0, 1))) abort("Binary outcome `r` must equal 0 or 1")
}
invisible(list(r = r, E = E))
}
check_outcome_combination <- function(outcomes) {
valid <- list(
list(agd_arm = c("count", NA),
agd_contrast = c("continuous", NA),
ipd = c("binary", NA)),
list(agd_arm = c("rate", NA),
agd_contrast = c("continuous", NA),
ipd = c("rate", NA)),
list(agd_arm = c("continuous", NA),
agd_contrast = c("continuous", NA),
ipd = c("continuous", NA)),
list(agd_arm = c("ordered", NA),
agd_contrast = c("continuous", NA),
ipd = c("ordered", NA))
)
if (!any(purrr::map_lgl(valid,
~all(c(outcomes$agd_arm %in% .$agd_arm,
outcomes$agd_contrast %in% .$agd_contrast,
outcomes$ipd %in% .$ipd))))) {
rlang::abort(glue::glue("Combining ",
glue::glue_collapse(outcomes[!is.na(outcomes)], sep = ', ', last = ' and '),
" outcomes is not supported."))
}
}
check_sample_size <- function(sample_size) {
if (rlang::is_list(sample_size) || !is.null(dim(sample_size)))
abort("Sample size `sample_size` must be a regular column (not a list or matrix column)")
if (!is.numeric(sample_size))
abort("Sample size `sample_size` must be numeric")
if (any(is.nan(sample_size)))
abort("Sample size `sample_size` cannot be NaN")
if (any(is.na(sample_size)))
abort("Sample size `sample_size` contains missing values")
if (any(sample_size != trunc(sample_size)))
abort("Sample size `sample_size` must be integer-valued")
if (any(sample_size <= 0))
abort("Sample size `sample_size` must be greater than zero")
if (any(is.infinite(sample_size)))
abort("Sample size `sample_size` cannot be infinite")
}
check_trt <- function(trt) {
if (any(is.na(trt)))
abort("`trt` cannot contain missing values")
if (rlang::is_list(trt) || !is.null(dim(trt)))
abort("`trt` must be a regular column (not a list or matrix column)")
}
check_study <- function(study) {
if (any(is.na(study)))
abort("`study` cannot contain missing values")
if (rlang::is_list(study) || !is.null(dim(study)))
abort("`study` must be a regular column (not a list or matrix column)")
}
check_trt_class <- function(trt_class, trt) {
if (rlang::is_list(trt_class) || !is.null(dim(trt_class)))
abort("`trt_class` must be a regular column (not a list or matrix column)")
if (any(is.na(trt)))
abort("`trt` cannot contain missing values")
if (any(is.na(trt_class)))
abort("`trt_class` cannot contain missing values")
if (anyDuplicated(unique(cbind(trt, trt_class))[, "trt"]))
abort("Treatment present in more than one class (check `trt` and `trt_class`)")
}
check_multi_combine <- function(x) {
x <- x[!purrr::map_lgl(x, is.null)]
is_ordered <- purrr::map_lgl(x, ~inherits(., "multi_ordered"))
is_competing <- purrr::map_lgl(x, ~inherits(., "multi_competing"))
if (any(is_ordered) && any(is_competing))
abort("Cannot combine ordered and competing multinomial outcomes.")
x_u <- purrr::map(x, unclass)
n_cat <- purrr::map_int(x_u, ncol)
if (any(n_cat != n_cat[1]))
abort("Cannot combine multinomial outcomes with different numbers of categories.")
l_cat <- purrr::map(x_u, colnames)
if (any(purrr::map_lgl(l_cat, ~any(. != l_cat[[1]]))))
abort("Cannot combine multinomial outcomes with different category labels.")
}
has_ipd <- function(network) {
if (!inherits(network, "nma_data")) abort("Not nma_data object.")
return(!rlang::is_empty(network$ipd))
}
has_agd_arm <- function(network) {
if (!inherits(network, "nma_data")) abort("Not nma_data object.")
return(!rlang::is_empty(network$agd_arm))
}
has_agd_contrast <- function(network) {
if (!inherits(network, "nma_data")) abort("Not nma_data object.")
return(!rlang::is_empty(network$agd_contrast))
}
has_agd_sample_size <- function(network) {
if (!inherits(network, "nma_data")) abort("Not nma_data object.")
ss_a <- !has_agd_arm(network) || tibble::has_name(network$agd_arm, ".sample_size")
ss_c <- !has_agd_contrast(network) || tibble::has_name(network$agd_contrast, ".sample_size")
return(ss_a && ss_c)
}
nfactor <- function(x, ..., numeric = TRUE, resort = FALSE) {
if (is.factor(x) && !resort) {
return(x)
} else {
return(factor(x, levels = stringr::str_sort(unique(x), numeric = numeric), ...))
}
}
|
correlateC <- function(x, w, data, digits=3, stats=FALSE, printC=FALSE,
plot=FALSE, jitter=FALSE, ...)
{
if(missing(x)) stop("Oops. You need to specify the variables to be analyzed. To see how to use this function, try example(correlateC) or help(correlateC).")
if(plot!=FALSE)
{
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
}
if(!missing(w)) w.name = deparse(substitute(w))
check.value(digits, valuetype="numeric")
variables.list <- as.list(substitute(x)[-1])
variable.names = rep(NA, length(variables.list))
for(i in 1:length(variables.list)) variable.names[i] <- deparse(variables.list[[i]])
if(length(variable.names)==1) stop("There's a problem: Your list of variables must contain two or more variables for correlation analysis. To see how to use this function, try example(correlateC) or help(correlateC).")
if(!missing(data))
{
if(is.matrix(data)) data <- data.frame(data)
variable.set <- data[, variable.names]
if(!missing(w)) w <- vector.from.data(substitute(w), data)
}
if(missing(data))
{
variable.set <- data.frame(variables.list)
colnames(variable.set) <- variable.names
}
if(!missing(w))
{
check.variable(w, vartype="numeric")
weighted <- TRUE
}
else
{
weighted <- FALSE
w <- NULL
}
main.heading <- headingbox("Correlation Analysis", marker="=")
if(printC==TRUE) printC(main.heading)
if(ncol(variable.set) == 2)
{
result <- weights::wtd.cor(x=variable.set[, 1], y=variable.set[, 2], weight=w, ...)
result <- data.frame(round(result, digits))
rownames(result) <- NULL
caption = paste("Correlation between", variable.names[1], "and", variable.names[2])
if(weighted==TRUE) caption = paste(caption, ", weighted by ", w.name, sep="")
if(stats==TRUE)
{
print(knitr::kable(format(result, drop0trailing=F, nsmall=digits, digits=digits, scientific=999), format="simple",
caption=caption, align="r"))
return.result <- result
if(printC==TRUE) printC(knitr::kable(format(result, drop0trailing=F, nsmall=digits, digits=digits, scientific=999), format="html",
caption=printCaption(caption), align="r"))
}
if(stats==FALSE)
{
cat("\n")
coef.only <- c(result[ , 1])
names(coef.only) <- c("Correlation Coefficient:")
print(coef.only)
rownames(result) <- "Correlation Coefficient:"
return.result <- coef.only
printc.output <- c("Correlation Coefficient:", coef.only)
class(printc.output) <- "statement"
if(printC==TRUE) printC(printc.output)
}
cat("\n")
if(plot==TRUE)
{
for(k in 1:(1+as.numeric(printC)))
{
if(printC==TRUE & k==2)
{
imagename <- paste("correlateC.plot.", unclass(Sys.time()), ".png", sep="")
grDevices::png(filename=imagename, width=3.5, height=3.5, units="in", type="cairo", pointsize=8, res=300, antialias="default")
class(imagename) <- "image"
printC(imagename)
}
if(nrow(variable.set) > 500)
{
marker.cex = .8
marker.col = "
if(missing(jitter)) jitter = TRUE
message("Note: Because there are many points to plot, correlateC is jittering them. Set jitter=FALSE to prevent this.")
}
else
{
marker.cex = 1
marker.col = "
}
if(jitter==TRUE) for(j in 1:ncol(variable.set)) variable.set[, j] <- jitter(variable.set[, j], amount=0)
par.ask.restore <- graphics::par("ask")
if(printC==TRUE & k==2) graphics::par(ask=FALSE) else graphics::par(ask=TRUE)
main = paste("Scatterplot of", variable.names[1], "and", variable.names[2])
main <- strwrap(main, width=50)
plot(x=variable.set[,1], y=variable.set[,2], xlab=variable.names[1], ylab=variable.names[2],
cex=marker.cex, col=marker.col, main=main)
graphics::par(ask=par.ask.restore)
if(printC==TRUE & k==2) grDevices::dev.off()
}
}
}
if(ncol(variable.set) > 2)
{
result <- suppressWarnings(weights::wtd.cor(x=variable.set, weight=w, ...))
correlation <- round(result[["correlation"]], digits)
variable.names.string <- paste(variable.names, collapse = ", ")
caption = paste("Correlation among", variable.names.string)
if(weighted==TRUE) caption = paste(caption, ", weighted by ", w.name, sep="")
print(knitr::kable(format(correlation, drop0trailing=F, nsmall=digits), format="simple", digits=digits,
caption=caption, align="r"))
slightpause()
if(printC==TRUE) printC(knitr::kable(format(correlation, drop0trailing=F, nsmall=digits), digits=digits,
caption=printCaption(caption), format="html", align="r"))
if(stats==FALSE)
{
cat("\n")
return.result <- correlation
}
if(stats==TRUE)
{
restore.options.scipen <- options("scipen")
options(scipen = 999)
standard.errors <- round(result[["std.err"]], digits)
se.caption = "Standard Errors of Correlation Coefficients"
for(i in 1:ncol(standard.errors)) standard.errors[i, i] <- NA
print(knitr::kable(format(standard.errors, drop0trailing=F, nsmall=digits), format="simple", digits=digits,
caption=se.caption, align="r"))
slightpause()
return.result <- result
if(printC==TRUE) printC(knitr::kable(format(standard.errors, drop0trailing=F, nsmall=digits), digits=digits,
caption=printCaption(se.caption), format="html"))
t.stats <- round(result[["t.value"]], digits)
for(i in 1:ncol(t.stats)) t.stats[i, i] <- NA
t.stats.caption = "t-Statistics of Correlation Coefficients"
print(knitr::kable(format(t.stats, drop0trailing=F, nsmall=digits), format="simple", digits=digits,
caption=t.stats.caption, align="r"))
slightpause()
if(printC==TRUE) printC(knitr::kable(format(t.stats, drop0trailing=F, nsmall=digits), digits=digits,
caption=printCaption(t.stats.caption), format="html"))
p.values <- round(result[["p.value"]], digits)
for(i in 1:ncol(p.values)) p.values[i, i] <- NA
p.values.caption = "p-Values of the t-Statistics"
print(knitr::kable(format(p.values, drop0trailing=F, nsmall=digits), format="simple", digits=digits,
caption=p.values.caption, align="r"))
slightpause()
if(printC==TRUE) printC(knitr::kable(format(p.values, drop0trailing=F, nsmall=digits), digits=digits,
caption=printCaption(p.values.caption), format="html"))
cat("\n")
options(scipen = restore.options.scipen)
}
if(plot==TRUE)
{
for(k in 1:(1+as.numeric(printC)))
{
if(printC==TRUE & k==2)
{
imagename <- paste("compmeansC.plot.", unclass(Sys.time()), ".png", sep="")
grDevices::png(filename=imagename, width=4, height=4, units="in", type="cairo", pointsize=8, res=300, antialias="default")
class(imagename) <- "image"
printC(imagename)
}
if(nrow(variable.set) > 500)
{
marker.cex = .8
marker.col = "
if(missing(jitter)) jitter = TRUE
message("Note: Because there are many points to plot, correlateC is jittering them. Set jitter=FALSE to prevent this.")
}
else
{
marker.cex = 1
marker.col = "
}
if(jitter==TRUE) for(j in 1:ncol(variable.set)) variable.set[, j] <- jitter(variable.set[, j], amount=0)
par.ask.restore <- graphics::par("ask")
if(printC==TRUE & k==2) graphics::par(ask=FALSE) else graphics::par(ask=TRUE)
graphics::pairs(x=variable.set, labels=variable.names, cex=marker.cex, cex.labels=1.6, col=marker.col)
graphics::par(ask=par.ask.restore)
if(printC==TRUE & k==2) grDevices::dev.off()
}
}
}
if(printC==T) printC(match.call(expand.dots = FALSE))
invisible(return.result)
}
|
truePrevPools <-
function(x, n, SE = 1, SP = 1, prior = c(1, 1),
nchains = 2, burnin = 10000, update = 10000,
verbose = FALSE) {
if (missing(x)) stop("'x' is missing")
if (missing(n)) stop("'n' is missing")
checkInput(x, "x", class = "integer", value = c(0, 1))
checkInput(n, "n", class = "integer", minEq = 0)
if (length(x) > 1 & length(n) == 1) n <- rep(n, length(x))
if (length(x) != length(n)) stop("'x' and 'n' must be of same length")
if (length(x) == 1) stop("\"truePrevPools\" requires at least 2 pools")
checkInput(SE, "SE", class = c("formula", "list", "numeric"))
checkInput(SP, "SP", class = c("formula", "list", "numeric"))
Se <- checkBinPrior(SE)
Sp <- checkBinPrior(SP)
checkInput(prior, "prior", class = "numeric", length = 2, minEq = 0)
checkInput(nchains, "nchains", class = "integer", min = 2)
checkInput(burnin, "burnin", class = "integer", min = 1)
checkInput(update, "update", class = "integer", min = 1)
checkInput(verbose, "verbose", class = "logical")
model <- character()
model[1] <- "model {"
model[2] <- "for (i in 1:N) {"
model[3] <- "x[i] ~ dbern(AP[i])"
model[4] <- paste("AP[i] <- SEpool[i] * (1 - pow(1 - TP, n[i])) +",
"(1 - SPpool[i]) * pow(1 - TP, n[i])")
model[5] <- paste("SEpool[i] <- 1 - (pow(1 - SE, n[i] * TP) *",
"pow(SP, n[i] * (1 - TP)))")
model[6] <- "SPpool[i] <- pow(SP, n[i])"
model[7] <- "}"
model <- c(model, writeSeSp("SE", Se))
model <- c(model, writeSeSp("SP", Sp))
model <- c(model, paste0("TP ~ dbeta(", prior[1], ", ", prior[2], ")"))
model <- c(model, "}")
class(model) <- "prevModel"
data <- list(x = x, n = n, N = length(n))
inits <- NULL
if (verbose) cat("JAGS progress:\n\n")
JAGSout <- R2JAGS(model = model, data = data, inits = inits,
nchains = nchains, burnin = burnin, update = update,
nodes = c("SE", "SP", "TP"), verbose = verbose)
mcmc.list <- JAGSout$mcmc.list
class(mcmc.list) <- c("list", "mcmc.list")
nodes <- colnames(mcmc.list[[1]])
mcmc.list_list <- list()
for (i in seq_along(nodes))
mcmc.list_list[[i]] <- mcmc.list[, i]
names(mcmc.list_list) <- nodes
mcmc.list_list <- mcmc.list_list[c("TP", "SE", "SP")]
DIC <- JAGSout$dic
exclude <- which(apply(mcmc.list[[1]], 2, sd) == 0)
if (length(exclude) > 0) {
BGR <- gelman.diag(mcmc.list[, -exclude])
} else {
BGR <- gelman.diag(mcmc.list)
}
out <- new("prev",
par = list(x = x, n = n, SE = Se, SP = Sp, prior = prior,
nchains = nchains, burnin = burnin, update = update,
inits = inits),
model = model,
mcmc = mcmc.list_list,
diagnostics = list(DIC = DIC,
BGR = BGR))
return(out)
}
|
library("perryExamples")
data("coleman")
set.seed(1234)
fit <- lmrob(Y ~ ., data=coleman)
perryFit(fit, data = coleman, y = coleman$Y,
splits = foldControl(K = 5, R = 10),
cost = rtmspe, costArgs = list(trim = 0.1),
seed = 1234)
perryFit(lmrob, formula = Y ~ ., data = coleman,
splits = foldControl(K = 5, R = 10),
cost = rtmspe, costArgs = list(trim = 0.1),
seed = 1234)
call <- call("lmrob", formula = Y ~ .)
perryFit(call, data = coleman, y = coleman$Y,
splits = foldControl(K = 5, R = 10),
cost = rtmspe, costArgs = list(trim = 0.1),
seed = 1234)
|
read_metadata <- function(dataset){
read.csv2(system.file("extdata",
paste0(dataset,'_files_metadata_harmonization.csv'),
package = "microdadosBrasil"),
stringsAsFactors = FALSE, check.names = F) %>% data.frame
}
read_var_translator <- function(dataset, ft){
read.csv2(system.file("extdata",
paste0(dataset,'_',ft,'_varname_harmonization.csv'),
package = "microdadosBrasil"), stringsAsFactors = FALSE, check.names =F)
}
aux_read_fwf <- function(f,dic, nrows = -1L, na = "NA"){
dict = nodic_overlap(dic)
aux_read<- function(f, dic,nrows = -1L, na = "NA"){
f %>% read_fwf(fwf_positions(start=dic$int_pos,end=dic$fin_pos,col_names=dic$var_name),
col_types=paste(dic$col_type,collapse =''),n_max = nrows, na = na) -> d
return(d)
}
lapply(dict, aux_read, f = f, nrows = nrows, na = na) %>% dplyr::bind_cols() -> d
return(d)
}
read_data <- function(dataset,ft,i, metadata = NULL,var_translator=NULL,root_path=NULL, file=NULL, vars_subset = NULL, nrows = -1L, source_file_mark = F){
if(F){
. <- NULL
source_file <- NULL
}
status<- test_path_arguments(root_path, file)
if(status == 0){ stop()}
if (!(dataset %in% get_available_datasets())) {
stop(paste0(dataset, " is not a valid dataset. Available datasets are: ", paste(get_available_datasets(), collapse = ", "))) }
if(is.null(metadata)){metadata<- read_metadata(dataset)}
i_range<- get_available_periods(metadata)
if (!(i %in% i_range)) { stop(paste0("period must be in ", paste(i_range, collapse = ", "))) }
ft_list<- get_available_filetypes(metadata, i)
if (!(ft %in% ft_list )) { stop(paste0('ft (file type) must be one of these: ',paste(ft_list, collapse=", "),
'. See table of valid file types for each period at "http://www.github.com/lucasmation/microdadosBrasil')) }
ft2 <- paste0("ft_",ft)
ft_list2 <- paste0("ft_",ft_list)
var_list <- names(metadata)[ !(names(metadata) %in% ft_list2)]
md <- metadata[metadata$period == i,] %>% select_(.dots =c(var_list,ft2)) %>% rename_(.dots=setNames(ft2,ft))
if (!is.null(var_translator)) {
vt <- var_translator %>% rename_( old_varname = as.name(paste0('varname',i)))
vt <- vt[!is.na(vt$old_varname), c("std_varname", "old_varname")]
}
a <- md %>% select_(.dots = ft) %>% collect %>% .[[ft]]
file_name <- unlist(strsplit(a, split='&'))[2]
delim <- unlist(strsplit(a, split='&'))[1]
format <- md %>% select_(.dots = 'format') %>% collect %>% .[['format']]
missing_symbol <- md %>% select_(.dots = 'missing_symbols') %>% collect %>% .[['missing_symbols']]
missing_symbol <- ifelse(test = is.na(missing_symbol), no = strsplit(missing_symbol,split = "&"), yes = "NA") %>% unlist
data_path <- paste(c(root_path,md$path,md$data_folder)[!is.na(c(root_path,md$path,md$data_folder))] ,collapse = "/")
if(data_path == ""){data_path <- getwd()}
files <- list.files(path=data_path,recursive = TRUE, full.names = TRUE) %>% grep(pattern = paste0(file_name, "$"), value = T, ignore.case = T)
if (!any(file.exists(files)) & status != 3) { stop("Data not found. Check if you have unziped the data" ) }
if(status == 3){
files = file
if (!any(file.exists(file)) & status != 3) { stop("Data not found. Check if you have unziped the data" ) }
}
t0 <- Sys.time()
if(format=='fwf'){
dic <- get_import_dictionary(dataset, i, ft)
if(!is.null(vars_subset)){
dic<- dic[dic$var_name %in% vars_subset,]
if(dim(dic)[1] == 0){
stop("There are no valid variables in the provided subset")
}
}
lapply(files,function(x,...) aux_read_fwf(x, ...)%>% data.table %>% .[, source_file:= x], dic=dic, nrows = nrows, na = missing_symbol) %>% rbindlist -> d
if(any(dic$decimal_places) & dataset == "CENSO"){
sapply(which(as.logical(dic$decimal_places)), function(x){
if(dic$col_type[x] == "d"){
var <- dic$var_name[x]
d[, (var):= (d[, var,with = F] /(10**dic$decimal_places[x]))]
}
})
}
}
if(format=='csv'){
if(!is.null(vars_subset)){warning("You provided a subset of variables for a dataset that doesn't have a dictionary, make sure to provide valid variable names.", call. = FALSE)
d <- lapply(files, function(x,...) data.table::fread(x,...) %>% .[, source_file := x], sep = delim, na.strings = c("NA",missing_symbol), select = vars_subset, nrows = nrows) %>% rbindlist(use.names = T)
}else{
d <- lapply(files, function(x,...) data.table::fread(x,...) %>% .[, source_file := x], sep = delim, na.strings = c("NA",missing_symbol), nrows = nrows) %>% rbindlist(use.names = T)
}
}
t1 <- Sys.time()
print(t1-t0)
print(object.size(d), units = "Gb")
if (!is.null(var_translator)) {
vt <- vt[vt$old_varname %in% names(d) & vt$old_varname != "" & vt$std_varname != "",]
setnames(d, vt$old_varname, vt$std_varname)
}
if(!source_file_mark & "source_file" %in% names(d)){
d[, source_file:= NULL]
}
return(d)
}
|
quantile.manual.thresh.scalewise<-function(x, which.levels=c(1,2,3),
hard = TRUE,quantile=.9, ...)
{
wc.shrink <- x
if (hard) {
for (i in names(x)[which.levels]) {
wci <- x[[i]]
unithresh <- quantile(abs(wci),quantile)
wc.shrink[[i]] <- wci * (abs(wci) > unithresh)
}
}
else {
for (i in names(x)[which.levels]) {
wci <- x[[i]]
unithresh <- quantile(abs(wci),quantile)
wc.shrink[[i]] <- sign(wci) * (abs(wci) - unithresh) *
(abs(wci) > unithresh)
}
}
wc.shrink
}
|
load_image = function(image, reorient) {
reorient_fun = function(x) return(x)
if(reorient) {
reorient_fun = function(x) {
flipud(x)
}
}
if(is.array(image)) {
return(reorient_fun(image))
}
if(is.character(image)) {
if(!file.exists(image)) {
stop("file ", image, " wasn't found")
}
ext = tolower(tools::file_ext(image))
if(ext == "png") {
return(reorient_fun(png::readPNG(image)))
} else if (ext %in% c("jpg","jpeg")) {
return(reorient_fun(jpeg::readJPEG(image)))
} else {
stop("filetype ", ext, " not supported for overlays")
}
}
}
generate_base_shape = function(heightmap, baseshape, angle=0) {
if(baseshape == "circle") {
radius = ifelse(nrow(heightmap) <= ncol(heightmap),nrow(heightmap)/2-1,ncol(heightmap)/2-1)
radmat = gen_circle_psf(radius+1)
if(min(dim(heightmap)) != min(dim(radmat))) {
radmat = radmat[2:nrow(radmat),2:ncol(radmat)]
}
if(max(dim(heightmap)) != max(dim(radmat))) {
difference = max(dim(heightmap)) - max(dim(radmat))
radtemp = matrix(0,nrow=nrow(heightmap),ncol=ncol(heightmap))
if(ncol(heightmap) != ncol(radmat)) {
radtemp[,(difference/2):(difference/2+ncol(radmat)-1)] = radmat
} else {
radtemp[(difference/2):(difference/2+nrow(radmat)-1),] = radmat
}
radmat = radtemp
}
heightmap[radmat == 0] = NA
} else if(baseshape == "hex") {
radius = ifelse(nrow(heightmap) <= ncol(heightmap),nrow(heightmap)/2-1,ncol(heightmap)/2-1)
radmat = gen_hex_psf(radius+1,rotation = angle)
if(min(dim(heightmap)) != min(dim(radmat))) {
radmat = radmat[2:nrow(radmat),2:ncol(radmat)]
}
if(max(dim(heightmap)) != max(dim(radmat))) {
difference = max(dim(heightmap)) - max(dim(radmat))
radtemp = matrix(0,nrow=nrow(heightmap),ncol=ncol(heightmap))
if(ncol(heightmap) != ncol(radmat)) {
radtemp[,(difference/2):(difference/2+ncol(radmat)-1)] = radmat
} else {
radtemp[(difference/2):(difference/2+nrow(radmat)-1),] = radmat
}
radmat = radtemp
}
heightmap[radmat == 0] = NA
}
return(heightmap)
}
|
NULL
setMethod(
f = "smooth_rectangular",
signature = signature(object = "GammaSpectrum"),
definition = function(object, m = 3, ...) {
x <- get_counts(object)
z <- rectangular(x, m = m)
methods::initialize(object, count = z)
}
)
setMethod(
f = "smooth_rectangular",
signature = signature(object = "GammaSpectra"),
definition = function(object, m = 3, ...) {
spc <- lapply(X = object, FUN = smooth_rectangular, m = m)
.GammaSpectra(spc)
}
)
rectangular <- function(x, m) {
m <- as.integer(m)[[1L]]
if (m %% 2 == 0)
stop(sQuote("m"), " must be an odd integer.", call. = FALSE)
k <- (m - 1) / 2
index_k <- seq_len(k)
index_x <- seq_along(x)
index_m <- c(index_k, rep_len(k + 1, length(x) - 2 * k), rev(index_k)) - 1
smoothed <- mapply(
FUN = function(i, k, data) {
index <- seq(from = i - k, to = i + k, by = 1)
mean(data[index])
},
i = index_x,
k = index_m,
MoreArgs = list(data = x)
)
smoothed
}
|
add_pi.lm <- function(df, fit, alpha = 0.05, names = NULL,
yhatName = "pred", log_response = FALSE, ...){
if (log_response)
add_pi_lm_log(df, fit, alpha, names, yhatName)
else {
if (is.null(names)){
names[1] <- paste("LPB", alpha/2, sep = "")
names[2] <- paste("UPB", 1 - alpha/2, sep = "")
}
if ((names[1] %in% colnames(df))) {
warning ("These PIs may have already been appended to your dataframe. Overwriting.")
}
out <- predict(fit, df, interval = "prediction", level = 1 - alpha)
if(is.null(df[[yhatName]]))
df[[yhatName]] <- out[, 1]
if (is.null(df[[names[1]]]))
df[[names[1]]] <- out[, 2]
if (is.null(df[[names[2]]]))
df[[names[2]]] <- out[, 3]
data.frame(df)
}
}
|
pheno.lad.fit <- function(D,limit=1000) {
if(!is.data.frame(D) && !is.matrix(D)) {
stop("lad.fit: argument must be data frame with 3 columns or matrix")
}
if(is.data.frame(D) && length(D)!=3) {
stop("lad.fit: argument must be data frame with 3 columns or matrix")
}
if(is.matrix(D)) {
D <- matrix2raw(D)
}
D <- D[order(D[[3]],D[[2]]),]
o <- as.vector(D[[1]],"numeric")
n <- length(o)
f1 <- factor(D[[2]])
n1 <- nlevels(f1)
f2 <- factor(D[[3]])
n2 <- nlevels(f2)
mm <- model.matrix(~ f1 + f2 - 1,na.action=na.exclude)
if(n > limit) {
ddm <- as.matrix.csr(mm)
m <- ddm@dimension[2]
nnzdmax <- ddm@ia[n + 1] - 1
l1fit <- rq.fit.sfn(ddm,o,tau=0.5,control=list(tmpmax=1000*m,nnzlmax=100*nnzdmax,small=1e-06))
}
else {
l1fit <- rq.fit(mm,o,tau=0.5,method="br")
}
p2 <-l1fit$coef[-(1:n1)]
s1 <- -sum(p2)/n2
p2 <-append(s1,p2+s1)
p1 <- as.vector(l1fit$coef[1:n1],"numeric")-s1
resid <- o - (p1[match(f1,levels(f1))]+p2[match(f2,levels(f2))])
ierr <- l1fit$ierr
return(list(f1=p1,f1.lev=levels(f1),f2=p2,f2.lev=levels(f2),resid=resid,ierr=ierr,D=D,fit=l1fit))
}
|
"selec.table"
|
context('dynamic-class')
test_that('dynamic classes work', {
stasis_egg <- tr(egg ~ egg, p(0.4))
stasis_larva <- tr(larva ~ larva, p(0.3))
stasis_adult <- tr(adult ~ adult, p(0.8))
hatching <- tr(larva ~ egg, p(0.5))
fecundity <- tr(egg ~ adult, p(0.2) * r(3))
pupation <- tr(adult ~ larva, p(0.2))
clonal <- tr(larva ~ larva, r(1.4))
stasis <- dynamic(stasis_egg,
stasis_larva,
stasis_adult)
growth <- dynamic(hatching,
pupation)
reproduction <- dynamic(fecundity,
clonal)
all1 <- dynamic(stasis_egg,
stasis_larva,
stasis_adult,
hatching,
pupation,
fecundity,
clonal)
all2 <- dynamic(stasis, growth, reproduction)
expect_equal(all2, all1)
all3 <- dynamic(stasis_egg,
stasis_larva,
stasis_adult,
growth,
reproduction)
expect_equal(all3, all1)
all4 <- dynamic(stasis_egg,
stasis_larva,
stasis_adult,
growth,
fecundity,
clonal)
expect_equal(all4, all1)
growth2 <- dynamic(growth)
expect_equal(growth2, growth)
expect_s3_class(stasis, 'dynamic')
expect_s3_class(growth, 'dynamic')
expect_s3_class(reproduction, 'dynamic')
expect_s3_class(all1, 'dynamic')
expect_s3_class(all2, 'dynamic')
expect_true(is.dynamic(stasis))
expect_true(is.dynamic(growth))
expect_true(is.dynamic(reproduction))
expect_true(is.dynamic(all1))
expect_true(is.dynamic(all2))
expect_false(is.dynamic(list()))
expect_false(is.dynamic(NA))
expect_false(is.dynamic(NULL))
expect_false(is.dynamic(stasis_egg))
expect_false(is.dynamic(fecundity))
obj1 <- pop:::as.dynamic(list())
obj2 <- pop:::as.dynamic(NA)
obj3 <- pop:::as.dynamic(Inf)
expect_s3_class(obj1, 'dynamic')
expect_s3_class(obj2, 'dynamic')
expect_s3_class(obj3, 'dynamic')
expect_equal(capture.output(print(all1)),
'dynamic: transitions between: egg, larva, adult')
expect_equal(capture.output(print(reproduction)),
'dynamic: transitions between: egg, adult, larva')
mat_stasis <- as.matrix(stasis)
mat_growth <- as.matrix(growth)
mat_reproduction <- as.matrix(reproduction)
mat_all1 <- as.matrix(all1)
mat_all2 <- as.matrix(all2)
expect_s3_class(mat_stasis, c('matrix', 'transition_matrix'))
expect_s3_class(mat_growth, c('matrix', 'transition_matrix'))
expect_s3_class(mat_reproduction, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all1, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all2, c('matrix', 'transition_matrix'))
expect_equal(dim(mat_stasis), c(3, 3))
expect_equal(dim(mat_growth), c(3, 3))
expect_equal(dim(mat_reproduction), c(3, 3))
expect_equal(dim(mat_all1), c(3, 3))
expect_equal(dim(mat_all2), c(3, 3))
expect_equal(mat_all1, mat_all2)
mat_all1_F <- as.matrix(all1, which = 'F')
mat_all2_F <- as.matrix(all2, which = 'F')
mat_all1_P <- as.matrix(all1, which = 'P')
mat_all2_P <- as.matrix(all2, which = 'P')
mat_all1_R <- as.matrix(all1, which = 'R')
mat_all2_R <- as.matrix(all2, which = 'R')
expect_s3_class(mat_all1_F, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all2_F, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all1_P, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all2_P, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all1_R, c('matrix', 'transition_matrix'))
expect_s3_class(mat_all2_R, c('matrix', 'transition_matrix'))
expect_equal(dim(mat_all1_F), c(3, 3))
expect_equal(dim(mat_all2_F), c(3, 3))
expect_equal(dim(mat_all1_P), c(3, 3))
expect_equal(dim(mat_all2_P), c(3, 3))
expect_equal(dim(mat_all1_R), c(3, 3))
expect_equal(dim(mat_all2_R), c(3, 3))
plot_stasis <- plot(stasis)
plot_growth <- plot(growth)
plot_reproduction <- plot(reproduction)
plot_all1 <- plot(all1)
plot_all2 <- plot(all2)
expect_s3_class(plot_stasis, 'igraph')
expect_s3_class(plot_growth, 'igraph')
expect_s3_class(plot_reproduction, 'igraph')
expect_s3_class(plot_all1, 'igraph')
expect_s3_class(plot_all2, 'igraph')
expected_param_all <- list(stasis_egg = list(p = 0.4),
stasis_larva = list(p = 0.3),
stasis_adult = list(p = 0.8),
hatching = list(p = 0.5),
pupation = list(p = 0.2),
fecundity = list(p = 0.2, r = 3),
clonal = list(r = 1.4))
expect_equal(parameters(all1), expected_param_all)
expect_equal(parameters(all2), expected_param_all)
expected_param_all_updated <- expected_param_all
expected_param_all_updated$fecundity$p <- 0.5
parameters(all1) <- expected_param_all_updated
expect_equal(parameters(all1), expected_param_all_updated)
all <- all1
ls <- landscape(all)
n <- 10
ls_new <- as.landscape(list(coordinates = data.frame(x = runif(n),
y = runif(n)),
area = area(ls),
population = population(ls),
features = features(ls)))
landscape(all) <- ls_new
mat <- as.matrix(all)
expect_true(is.matrix(mat))
expect_equal(dim(mat), rep(n * 3, 2))
adult_dispersal <- tr(adult ~ adult, p(0.5) * d(3))
all_disp <- dynamic(all,
adult_dispersal)
landscape(all_disp) <- ls_new
plot_all_disp <- plot(all_disp)
mat_disp <- as.matrix(all_disp)
matA_disp <- as.matrix(all_disp, which = 'A')
matP_disp <- as.matrix(all_disp, which = 'P')
matF_disp <- as.matrix(all_disp, which = 'F')
matR_disp <- as.matrix(all_disp, which = 'R')
expect_s3_class(mat_disp, c('matrix', 'transition_matrix'))
expect_s3_class(matA_disp, c('matrix', 'transition_matrix'))
expect_s3_class(matP_disp, c('matrix', 'transition_matrix'))
expect_s3_class(matF_disp, c('matrix', 'transition_matrix'))
expect_s3_class(matR_disp, c('matrix', 'transition_matrix'))
expect_equal(dim(mat_disp), c(30, 30))
expect_equal(dim(matA_disp), c(30, 30))
expect_equal(dim(matP_disp), c(30, 30))
expect_equal(dim(matF_disp), c(30, 30))
expect_equal(dim(matR_disp), c(30, 30))
idx <- seq(0, 30, by = 3)[-1]
cells <- as.matrix(expand.grid(idx, idx))
expect_true(all(matA_disp[cells] > 0))
expect_true(all(matP_disp[cells] > 0))
expect_true(all(matF_disp[cells] == 0))
})
|
load(test_path("data", "asreml_model.Rdata"), .GlobalEnv)
test_that("function works", {
skip_if_not(requireNamespace("asreml", quietly = TRUE))
quiet(library(asreml))
oats.logl <- logl_test(model.obj = model.asr, rand.terms = c("Blocks", "Blocks:Wplots"),
resid.terms = c("ar1(Row)", "ar1(Column)"), decimals = 5, quiet = TRUE)
oats.logl2 <- logl_test(model.obj = model.asr, rand.terms = c("Blocks", "Blocks:Wplots"),
resid.terms = c("ar1(Row)", "ar1(Column)"), decimals = 5, numeric = TRUE, quiet = TRUE)
oats.logl3 <- logl_test(model.obj = model.asr, rand.terms = c("Blocks", "Blocks:Wplots"),
resid.terms = c("ar1(Row)", "ar1(Column)"), decimals = 1, quiet = TRUE)
expect_equal(oats.logl$Term, c("Blocks", "Blocks:Wplots", "ar1(Row)", "ar1(Column)"))
expect_equal(oats.logl$LogLRT.pvalue, c("0.05795", "0.13142", "0.00559", "0.82896"))
expect_equal(oats.logl2$LogLRT.pvalue, c(0.05795, 0.13142, 0.00559, 0.82896))
expect_true(is.numeric(oats.logl2$LogLRT.pvalue))
expect_equal(oats.logl3$LogLRT.pvalue, c('0.1', '0.1', '<0.1', '0.8'))
expect_warning(logl_test(model.obj = model.asr, rand.terms = c("Blocks", "Blocks:Wplots"),
resid.terms = c("ar1(Row)", "ar1(Column)"), decimals = 5),
"Model did not converge")
})
test_that("logltest gives an error on different model type", {
dat.aov <- aov(Petal.Length ~ Petal.Width, data = iris)
expect_error(logl_test(dat.aov), "Only asreml models are supported at this time.")
})
test_that("logltest gives an error on different model type", {
skip_if_not(requireNamespace("asreml", quietly = TRUE))
quiet(library(asreml))
expect_error(logl_test(model.asr), "One of rand.terms or resid.terms must be provided")
})
|
library(testthat);
suppressMessages(require(valection));
context("run increasing with overlap");
if (valection::check.for.library()) {
out.dir <- tempdir();
out.file <- paste0(out.dir, "/outfile_example.txt");
valection::run.increasing.with.overlap(
budget = 5,
infile = system.file(
"extdata/infile_example.tsv",
package = "valection"
),
outfile = out.file,
seed = 123
);
samplingResult <- read.table(out.file);
file.remove(out.file);
expectedResult <- read.table("expected.run.increasing.with.overlap.txt");
test_that("Increasing with overlap sampling works", {
expect_equal(samplingResult, expectedResult);
});
}
|
gradcols <- function(col_vec = NULL){
cols <- RColorBrewer::brewer.pal(11, 'Spectral')
if(!is.null(col_vec)){
chk_cols <- row.names(RColorBrewer::brewer.pal.info)
if(any(chk_cols %in% col_vec)){
col_vec <- chk_cols[which(chk_cols %in% col_vec)][1]
max_cols <- RColorBrewer::brewer.pal.info[col_vec, 'maxcolors']
cols <- RColorBrewer::brewer.pal(max_cols, col_vec)
} else {
cols <- col_vec
}
}
return(cols)
}
|
nhl_url_seasons <- function(seasons = NULL) {
nhl_url(endPoint = "seasons", suffixes = list(nhl_make_seasons(seasons)))
}
nhl_seasons <- function(seasons = NULL) {
x <- nhl_url_seasons(seasons = seasons)
x <- nhl_get_data(x)
x <- util_remove_get_data_errors(x)
x <- nhl_process_results(x, elName = "seasons")
x
}
|
plot.glarma <- function(x, which = c(1L,3L,5L,7L,8L,9L), fits = 1L:3L,
ask = prod(par("mfcol")) <
length(which) && dev.interactive(),
lwdObs = 1, lwdFixed = 1, lwdGLARMA = 1,
colObs = "black", colFixed = "blue", colGLARMA = "red",
ltyObs = 2, ltyFixed = 1, ltyGLARMA = 1,
pchObs = 1, legend = TRUE, residPlotType = "h",
bins = 10, line = TRUE, colLine = "red",
colHist = "royal blue", lwdLine = 2,
colPIT1 = "red", colPIT2 = "black",
ltyPIT1 = 1, ltyPIT2 = 2, typePIT = "l",
ltyQQ = 2, colQQ = "black",
titles, ...)
{
show <- rep(FALSE, 10)
show[which] <- TRUE
showFits <- rep(FALSE, 3)
showFits[fits] <- TRUE
if (missing(titles)) {
titles <- vector("list", 10)
titles[[5]] <- "Histogram of Uniform PIT"
titles[[6]] <- "Q-Q Plot of Uniform PIT"
titles[[7]] <- "Histogram of Randomized Residuals"
titles[[8]] <- "Q-Q Plot of Randomized Residuals"
titles[[9]] <- "ACF of Randomized Residuals"
titles[[10]] <- "PACF of Randomized Residuals"
} else {
defaultTitles <- vector("list", 10)
defaultTitles[which] <- titles
titles <- defaultTitles
}
if (x$type == "Poi" | x$type == "NegBin") {
if (show[1L] & any(showFits == TRUE)) {
obs.logic <- showFits[1]
fixed.logic <- showFits[2]
glarma.logic <- showFits[3]
fits <- list(obs = x$y, fixed = exp(x$eta), glarma = x$mu)
legendNames <- names(fits)
titleNames <- c("Observed", "Fixed", "GLARMA")
ltyAll <- c(ltyObs, ltyFixed, ltyGLARMA)
lwdAll <- c(lwdObs, lwdFixed, lwdGLARMA)
colAll <- c(colObs, colFixed, colGLARMA)
yRange <- c(diff(range(fits$obs)), diff(range(fits$fixed)),
diff(range(fits$glarma)))
yRange[!showFits] <- -Inf
yLim <- which.max(yRange)
}
if (any(show[2L:4L] == TRUE)) {
residuals <- x$residuals
if (is.null(titles[[2]])) {
titles[2] <- paste("ACF of", x$residType, "Residuals")
}
if (is.null(titles[[3]])) {
titles[3] <- paste(x$residType, "Residuals")
}
if (is.null(titles[[4]])) {
titles[4] <-
paste("Normal Q-Q Plot of ",x$residType, "Residuals")
}
}
if (ask) {
oask <- devAskNewPage(TRUE)
on.exit(devAskNewPage(oask))
}
if (show[1L] & any(showFits == TRUE)) {
dev.hold()
if (is.null(titles[[1]])){
main <- paste(titleNames[showFits], collapse = " vs ")
} else {
main <- titles[1]
}
ts.plot(fits[[yLim]], ylab = "Counts", xlab = "Time",
col = NA, main = main, ...)
if (obs.logic)
lines(fits$obs, lwd = lwdObs, lty = ltyObs, col = colObs)
if (fixed.logic)
lines(fits$fixed, lwd = lwdFixed, lty = ltyFixed,
col = colFixed)
if (glarma.logic)
lines(fits$glarma, lwd = lwdGLARMA, lty = ltyGLARMA,
col = colGLARMA)
if (legend & any(showFits == TRUE)) {
par(xpd = NA)
mfrow <- par("mfrow")
graph.param <-
legend("top", legend = legendNames[showFits],
lty = ltyAll[showFits],
ncol = 3,
cex = 0.7 - (mfrow[1] - 1)/10 - (mfrow[2] - 1)/10,
bty = "n", plot = FALSE)
legend(graph.param$rect$left,
graph.param$rect$top + graph.param$rect$h,
legend = legendNames[showFits], col = colAll[showFits],
lwd = lwdAll[showFits], lty = ltyAll[showFits],
ncol = 3,
cex = 0.7 - (mfrow[1] - 1)/10 - (mfrow[2] - 1)/10,
bty = "n",
text.font = 4)
par(xpd = FALSE)
}
dev.flush()
}
if (show[2L]) {
dev.hold()
acf(residuals, main = titles[2], ...)
dev.flush()
}
if (show[3L]) {
dev.hold()
plot.ts(residuals, ylab = "Residuals", type = residPlotType,
main = titles[3], ...)
dev.flush()
}
if (show[4L]) {
dev.hold()
qqnorm(residuals, ylab = "Residuals", main = titles[4], ...)
abline(0, 1, lty = 2)
dev.flush()
}
if (show[5L]) {
dev.hold()
histPIT(x, bins = bins, line = line, colLine = colLine,
colHist = colHist, lwdLine = lwdLine, main = titles[[5]], ...)
dev.flush()
}
if (show[6L]) {
dev.hold()
qqPIT(x, bins = bins, col1 = colPIT1, col2 = colPIT2,
lty1 = ltyPIT1, lty2 = ltyPIT2, type = typePIT,
main = titles[[6]], ...)
dev.flush()
}
if (any(show[7L:10L] == TRUE)) {
rt <- normRandPIT(x)$rt
}
if (show[7L]) {
dev.hold()
hist(rt, breaks = bins, main = titles[[7]],
col = colHist, xlab = expression(r[t]), ...)
box()
dev.flush()
}
if (show[8L]) {
dev.hold()
qqnorm(rt, main = titles[[8]], ...)
abline(0, 1, lty = ltyQQ, col = colQQ, ...)
dev.flush()
}
if (show[9L]) {
dev.hold()
acf(rt, main = titles[[9]], ...)
dev.flush()
}
if (show[10L]) {
dev.hold()
pacf(rt, main = titles[[10]], ...)
dev.flush()
}
}
if (x$type == "Bin") {
if (show[1L] & any(showFits = TRUE)) {
obs.logic <- showFits[1]
fixed.logic <- showFits[2]
glarma.logic <- showFits[3]
observed <- x$y[, 1]/apply(x$y, 1, sum)
fits <- list(fixed = 1/(1 + exp(-x$eta)),
glarma = 1/(1 + exp(-x$W)))
legendNames <- c("obs", names(fits)[1], names(fits)[2])
titleNames <- c("Observed", "Fixed", "GLARMA")
pchAll <- c(pchObs, NA, NA)
ltyAll <- c(ltyObs, ltyFixed, ltyGLARMA)
lwdAll <- c(NA, lwdFixed, lwdGLARMA)
colAll <- c(colObs, colFixed, colGLARMA)
}
if (any(show[2L:4L] == TRUE)) {
residuals <- x$residuals
residuals <- x$residuals
if (is.null(titles[[2]])) {
titles[2] <- paste("ACF of", x$residType, "Residuals")
}
if (is.null(titles[[3]])) {
titles[3] <- paste(x$residType, "Residuals")
}
if (is.null(titles[[4]])) {
titles[4] <-
paste("Normal Q-Q Plot of ",x$residType, "Residuals")
}
}
if (ask) {
oask <- devAskNewPage(TRUE)
on.exit(devAskNewPage(oask))
}
if (show[1L] & any(showFits == TRUE)) {
dev.hold()
if (is.null(titles[[1]])){
main <- paste(titleNames[showFits], collapse = " vs ")
} else {
main <- titles[1]
}
plot(1:length(observed), observed, ylab = "Counts", xlab = "Time",
col = NA, main = main, ...)
if (obs.logic)
points(observed, pch = pchObs, col = colObs)
if (fixed.logic)
lines(fits$fixed, lwd = lwdFixed, lty = ltyFixed,
col = colFixed)
if (glarma.logic)
lines(fits$glarma, lwd = lwdGLARMA, lty = ltyGLARMA,
col = colGLARMA)
if (legend & any(showFits == TRUE)) {
par(xpd = NA)
mfrow <- par("mfrow")
graph.param <-
legend("top", legend = legendNames[showFits],
pch = pchAll[showFits],
lty = ltyAll[showFits], ncol = 3,
cex = 0.7 - (mfrow[1] - 1)/10 - (mfrow[2] - 1)/10,
text.font = 4, plot = FALSE)
legend(graph.param$rect$left,
graph.param$rect$top + graph.param$rect$h,
legend = legendNames[showFits], pch = pchAll[showFits],
col = colAll[showFits], lwd = lwdAll[showFits],
lty = ltyAll[showFits], ncol = 3,
cex = 0.7 - (mfrow[1] - 1)/10 - (mfrow[2] - 1)/10,
bty = "n", text.font = 4)
par(xpd = FALSE)
}
dev.flush()
}
if (show[2L]) {
dev.hold()
acf(residuals, main = titles[2], ...)
dev.flush()
}
if (show[3L]) {
dev.hold()
plot.ts(residuals, ylab = "Residuals", type = residPlotType,
main = titles[3], ...)
dev.flush()
}
if (show[4L]) {
dev.hold()
qqnorm(residuals, ylab = "Residuals", main = titles[4], ...)
abline(0, 1, lty = 2)
dev.flush()
}
if (show[5L]) {
dev.hold()
histPIT(x, bins = bins, line = line, colLine = colLine,
colHist = colHist, lwdLine = lwdLine, main = titles[5], ...)
dev.flush()
}
if (show[6L]) {
dev.hold()
qqPIT(x, bins = bins, col1 = colPIT1, col2 = colPIT2,
lty1 = ltyPIT1, lty2 = ltyPIT2, type = typePIT,
main = titles[6], ...)
dev.flush()
}
if (any(show[7L:10L] == TRUE)) {
rt <- normRandPIT(x)$rt
}
if (show[7L]) {
dev.hold()
hist(rt, breaks = bins, main = titles[[7]],
col = colHist, xlab = expression(r[t]), ...)
box()
dev.flush()
}
if (show[8L]) {
dev.hold()
qqnorm(rt, main = titles[[8]], ...)
abline(0, 1, lty = ltyQQ, col = colQQ, ...)
dev.flush()
}
if (show[9L]) {
dev.hold()
acf(rt, main = titles[[9]], ...)
dev.flush()
}
if (show[10L]) {
dev.hold()
pacf(rt, main = titles[[10]], ...)
dev.flush()
}
}
invisible()
}
|
corbetw2mat <-
function(x, y, what=c("paired", "bestright", "bestpairs", "all"),
corthresh=0.9)
{
if(!is.matrix(x)) x <- as.matrix(x)
if(!is.matrix(y)) y <- as.matrix(y)
n <- nrow(x)
if(nrow(y) != n)
stop("nrow(x)=", n, ", which is not equal to nrow(y)=", nrow(y))
px <- ncol(x)
py <- ncol(y)
what <- match.arg(what)
if(is.null(colnames(x))) colnames(x) <- paste("V", 1:ncol(x), sep="")
if(is.null(colnames(y))) colnames(y) <- paste("V", 1:ncol(y), sep="")
if(what=="paired" && py != px)
stop("what=\"paired\", but ncol(x)=", px, ", which is not equal to ncol(y)=", py)
if(what=="paired") {
res <- .C("R_corbetw2mat_paired",
as.integer(n),
as.integer(px),
as.double(x),
as.double(y),
cor=as.double(rep(NA, px)),
PACKAGE="lineup",
NAOK=TRUE)$cor
names(res) <- colnames(x)
}
else if(what=="bestright") {
res <- .C("R_corbetw2mat_unpaired_lr",
as.integer(n),
as.integer(px),
as.double(x),
as.integer(py),
as.double(y),
cor=as.double(rep(NA, px)),
index=as.integer(rep(NA, px)),
PACKAGE="lineup",
NAOK=TRUE)
res <- data.frame(cor=res$cor, yindex=res$index)
rownames(res) <- colnames(x)
res <- cbind(res, ycol=colnames(y)[res[,2]])
}
else if(what=="bestpairs") {
res <- .C("R_corbetw2mat_unpaired_best",
as.integer(n),
as.integer(px),
as.double(x),
as.integer(py),
as.double(y),
cor=as.double(rep(NA, px*py)),
xindex=as.integer(rep(NA, px*py)),
yindex=as.integer(rep(NA, px*py)),
numpairs=as.integer(0),
as.double(corthresh),
PACKAGE="lineup",
NAOK=TRUE)
res <- data.frame(cor=res$cor[1:res$numpairs],
xindex=res$xindex[1:res$numpairs],
yindex=res$yindex[1:res$numpairs])
res <- cbind(res, xcol=colnames(x)[res[,2]], ycol=colnames(y)[res[,3]])
}
else {
res <- .C("R_corbetw2mat_unpaired_all",
as.integer(n),
as.integer(px),
as.double(x),
as.integer(py),
as.double(y),
cor=as.double(rep(NA, px*py)),
PACKAGE="lineup",
NAOK=TRUE)$cor
res <- matrix(res, nrow=px, ncol=py)
dimnames(res) <- list(colnames(x), colnames(y))
}
res
}
|
rounding <- function(x, fmt = '%.3f', ...) {
idx_na <- is.na(x)
if (is.factor(x) || is.logical(x) || is.character(x)) {
out <- as.character(x)
if (settings_equal("escape", TRUE)) {
out <- escape_string(out)
}
if (settings_equal("output_format", c("latex", "latex_tabular")) &&
settings_equal("siunitx_scolumns", TRUE)) {
out <- sprintf("{%s}", out)
}
} else {
if (is.character(fmt)) {
out <- sprintf(fmt, x, ...)
} else if (is.numeric(fmt)) {
if (fmt == 0) {
out <- sprintf("%.0f", x)
} else {
out <- trimws(format(round(x, fmt), nsmall = fmt, ...))
}
} else if (is.function(fmt)) {
out <- fmt(x)
} else {
out <- x
}
out <- gsub('^NA$|^NaN$|^-Inf$|^Inf$', '', out)
if (settings_equal("output_format", c("latex", "latex_tabular"))) {
if (!isTRUE(settings_get("siunitx_scolumns"))) {
if (settings_equal("format_numeric_latex", "siunitx")) {
out <- sprintf("\\num{%s}", out)
} else if (settings_equal("format_numeric_latex", c("dollars", "mathmode"))) {
out <- sprintf("$%s$", out)
}
}
}
if (settings_equal("output_format", c("html", "kableExtra"))) {
if (settings_equal("format_numeric_html", "minus")) {
out <- gsub("\\-", "\u2212", out)
} else if (settings_equal("format_numeric_html", c("mathjax", "dollars"))) {
out <- sprintf("$%s$", out)
}
}
}
out[idx_na] <- ""
return(out)
}
|
plotAbundances <- function(nmfMod,source, slice=1) {
dims <- NMF::misc(nmfMod)
nRows <- dims$nRows
nCols <- dims$nCols
strComp <- match(names(dims),"nSlices")
if(sum(is.na(strComp)) < length(strComp)) {
nSlices <- dims$nSlices
}
else {
nSlices <- 1
}
H <- NMF::coef(nmfMod)[source,]
H <- array(H,c(nRows,nCols,nSlices))
if (length(dim(H))==3) {
H <- H[,,slice]
}
grDevices::dev.new()
graphics::plot(1:nRows, 1:nCols, type = "n")
rasterImage::rasterImage2(z = t(H[nRows:1,]))
}
|
ft_max_abs_scaler <- function(x, input_col = NULL, output_col = NULL,
uid = random_string("max_abs_scaler_"), ...) {
check_dots_used()
UseMethod("ft_max_abs_scaler")
}
ml_max_abs_scaler <- ft_max_abs_scaler
ft_max_abs_scaler.spark_connection <- function(x, input_col = NULL, output_col = NULL,
uid = random_string("max_abs_scaler_"), ...) {
spark_require_version(x, "2.0.0", "MaxAbsScaler")
.args <- list(
input_col = input_col,
output_col = output_col,
uid = uid
) %>%
c(rlang::dots_list(...)) %>%
validator_ml_max_abs_scaler()
estimator <- spark_pipeline_stage(
x, "org.apache.spark.ml.feature.MaxAbsScaler",
input_col = .args[["input_col"]], output_col = .args[["output_col"]], uid = .args[["uid"]]
) %>%
new_ml_max_abs_scaler()
estimator
}
ft_max_abs_scaler.ml_pipeline <- function(x, input_col = NULL, output_col = NULL,
uid = random_string("max_abs_scaler_"), ...) {
stage <- ft_max_abs_scaler.spark_connection(
x = spark_connection(x),
input_col = input_col,
output_col = output_col,
uid = uid,
...
)
ml_add_stage(x, stage)
}
ft_max_abs_scaler.tbl_spark <- function(x, input_col = NULL, output_col = NULL,
uid = random_string("max_abs_scaler_"), ...) {
stage <- ft_max_abs_scaler.spark_connection(
x = spark_connection(x),
input_col = input_col,
output_col = output_col,
uid = uid,
...
)
if (is_ml_transformer(stage)) {
ml_transform(stage, x)
} else {
ml_fit_and_transform(stage, x)
}
}
new_ml_max_abs_scaler <- function(jobj) {
new_ml_estimator(jobj, class = "ml_max_abs_scaler")
}
new_ml_max_abs_scaler_model <- function(jobj) {
new_ml_transformer(jobj, class = "ml_max_abs_scaler_model")
}
validator_ml_max_abs_scaler <- function(.args) {
validate_args_transformer(.args)
}
|
write.sav <- function(x, file = "SPSS_Data.sav", var.attr = NULL, pspp.path = NULL, digits = 2,
write.csv = FALSE, sep = c(";", ","), na = "", write.sps = FALSE, check = TRUE) {
if (isTRUE(missing(x))) {
stop("Please specify a matrix or data frame for the argument 'x'.", call. = FALSE)
}
if (isTRUE(!is.matrix(x) && !is.data.frame(x))) {
stop("Please specifiy a matrix or data frame for the argument 'x'.", call. = FALSE)
}
x <- as.data.frame(x, stringsAsFactors = FALSE)
varnames <- colnames(x)
var.length <- length(varnames)
file <- ifelse(length(grep(".sav", file)) == 1L, file <- gsub(".sav", "", file), file)
sep <- ifelse(all(c(";", ".") %in% sep), ";", sep)
if (isTRUE(!is.logical(check))) {
stop("Please specify TRUE or FALSE for the argument 'check'.", call. = FALSE)
}
if (isTRUE(check)) {
if (isTRUE(!is.null(pspp.path))) {
if (isTRUE(length(grep("pspp.exe", list.files(paste0(pspp.path, "/bin/")))) != 1L)) {
stop("PSPP file \'pspp.exe\' was not found in the folder specified in the pspp.path argument.", call. = FALSE)
}
}
if (isTRUE(!is.null(var.attr))) {
if (isTRUE(nrow(var.attr) != ncol(x))) {
stop("Number of rows in the data frame or matrix specified in the argument var.attr does not match with the number of columns in x.",
call. = FALSE)
}
if (isTRUE(all(is.na(match(names(var.attr), c("label", "values", "missing")))))) {
stop("None of the column names of the data frame or matrix specified in the argument var.attr match with \"label\", \"values\" or \"missing\".",
call. = FALSE)
}
if (isTRUE(any(!is.na(match(names(var.attr), "values"))))) {
for (i in seq_len(var.length)) {
value.labels <- as.character(var.attr[i, "values"])
if (isTRUE(value.labels != "")) {
value.labels.split <- unlist(strsplit(value.labels, ";"))
value.labels.split.matrix <- matrix(misty::chr.trim(unlist(sapply(value.labels.split, function(y) strsplit(y, "=")))), ncol = length(value.labels.split))
if(isTRUE(!all(as.numeric(value.labels.split.matrix[1, ]) %in% x[, varnames[i]]))) {
warning(paste0("Values in the column \"values\" specified in 'var.attr' does not match with the variable '",
varnames[i], "'."), call. = FALSE)
}
}
}
}
}
if (isTRUE(digits %% 1L != 0L || digits < 0L)) {
stop("Specify a positive integer number for the argument digits.", call. = FALSE)
}
if (isTRUE(write.csv & any(!sep %in% c(";", ",")))) {
stop("Specify either \";\" or \",\" for the argument sep.", call. = FALSE)
}
}
if (isTRUE(is.null(pspp.path))) {
if (isTRUE(!requireNamespace("haven", quietly = TRUE))) {
stop("Package \"haven\" is needed for this function to work, please install it.",
call. = FALSE )
}
if (isTRUE(is.null(var.attr))) {
haven::write_sav(x, paste0(file, ".sav"), compress = FALSE)
} else {
labels <- as.character(var.attr[, match("values", colnames(var.attr))])
na <- as.character(var.attr[, match("missing", colnames(var.attr))])
label <- as.character(var.attr[, match("label", colnames(var.attr))])
for (i in which(vapply(x, is.numeric, FUN.VALUE = logical(1L)))) {
if (misty::chr.trim(labels[i]) == "") {
if (isTRUE(misty::chr.trim(na[i]) == "")) {
labels.i <- NULL
} else {
x.na <- misty::chr.trim(unlist(strsplit(na[i], ";")))
labels.i <- paste0("c(", paste(sapply(x.na, function(y) paste("\"NA\" = ", y)), collapse = ", "), ")")
}
} else {
x.labels <- unlist(strsplit(labels[i], ";"))
x.labels <- matrix(misty::chr.trim(unlist(sapply(x.labels, function(y) strsplit(y, "=")))), ncol = length(x.labels))
if (misty::chr.trim(na[i]) == "") {
labels.i <- paste0("c(", paste(apply(x.labels, 2, function(y) paste(paste0("\"", y[2L], "\""), y[1], sep = " = ")), collapse = ", "), ")")
} else {
x.na <- misty::chr.trim(unlist(strsplit(na[i], ";")))
labels.i <- paste0("c(", paste(c(apply(x.labels, 2, function(y) paste(paste0("\"", y[2L], "\""), y[1], sep = " = ")),
paste(sapply(x.na, function(y) paste("\"NA\" = ", y)), collapse = ", ")), collapse = ", "), ")")
}
}
if (isTRUE(misty::chr.trim(na[i]) == "")) {
na.i <- NULL
} else {
na.i <- paste0("c(", paste(misty::chr.trim(unlist(strsplit(na[i], ";"))), collapse = ", "), ")")
}
eval(parse(text = paste0("x$", colnames(x)[i], " <- haven::labelled_spss(as.double(x$", colnames(x)[i], "), labels = ", ifelse(is.null(labels.i), "NULL", labels.i), ", na_values = ", ifelse(is.null(na.i), "NULL", na.i), ", label = \"", label[i], "\")")))
if (isTRUE(all(na.omit(x[, i]) %% 1L == 0L))) {
eval(parse(text = paste0("attr(x$", colnames(x)[i], ", \"format.spss\") <- \"F8.0\"")))
} else {
eval(parse(text = paste0("attr(x$", colnames(x)[i], ", \"format.spss\") <- \"F8.", digits, "\"")))
}
}
haven::write_sav(x, paste0(file, ".sav"), compress = FALSE)
}
if (isTRUE(write.csv)) {
if (isTRUE(sep == ";")) {
write.csv2(x, paste0(file, ".csv"), row.names = FALSE, quote = FALSE, na = na)
} else {
write.csv(x, paste0(file, ".csv"), row.names = FALSE, quote = FALSE, na = na)
}
}
} else {
add.quote <- function(x) { paste0("\"", x, "\"") }
any.factors <- any(vapply(x, is.factor, FUN.VALUE = logical(1)))
if (isTRUE(any.factors)) {
xf <- data.frame(lapply(x, function(x) if (is.factor(x) | is.logical(x)) as.numeric(x) else x),
stringsAsFactors = FALSE)
} else {
xf <- x
}
utils::write.csv2(xf, paste0(file, ".csv"), row.names = FALSE, quote = FALSE, na = na)
type <- rep("F", times = var.length)
width <- rep(8L, times = var.length)
decimals <- rep(NA, times = var.length)
for (i in seq_len(var.length)) {
if (isTRUE(is.numeric(xf[, i]))) {
i.nchar <- nchar(round(xf[, i], digits = digits))
if (isTRUE(any(na.omit(i.nchar) > 8L))) { width[i] <- max(i.nchar) }
decimals[i] <- ifelse(is.integer(xf[, i]), 0L, digits)
decimals[i] <- ifelse(all(xf[, i] %% 1 == 0L), 0, digits)
} else {
type[i] <- "A"
width[i] <- max(nchar(xf[, i]))
}
}
variables <- paste(varnames, ifelse(!is.na(decimals), paste0(type, paste(width, decimals, sep = ".")), paste0(type, width)), collapse = "\n ")
code <- paste0(file, ".sps")
cat(paste0("GET DATA\n",
" /TYPE=TXT \n",
" /FILE='", getwd(), "/", file, ".csv' \n",
" /ARRANGEMENT=DELIMITED\n",
" /DELCASE=LINE \n",
" /FIRSTCASE=2 \n",
" /DELIMITERS=';'\n" ,
" /QUALIFIER='' \n" ,
" /VARIABLES=\n"), file = code)
cat(paste0(" ", variables, " ."), file = code, append = TRUE)
if (isTRUE(!is.null(var.attr))) {
label <- as.character(var.attr[, match("label", colnames(var.attr))])
indices <- which(label != "")
variable.label <- paste(varnames[indices], add.quote(label[indices]), collapse = " \n ")
cat("\nVARIABLE LABELS\n ", file = code, append = TRUE)
cat(paste0(" ", variable.label, " ."), file = code, append = TRUE)
if (isTRUE(any(var.attr[, match("values", colnames(var.attr))] != ""))) {
for (i in seq_len(var.length)) {
value.labels <- as.character(var.attr[i, match("values", colnames(var.attr))])
if (isTRUE(value.labels != "")) {
x <- unlist(strsplit(value.labels, ";"))
x <- matrix(misty::chr.trim(unlist(sapply(x, function(x) strsplit(x, "=")))), ncol = length(x))
cat("\nVALUE LABELS\n",
paste0(" ", varnames[i], paste0(paste0(" ", x[1L, ], " '", x[2L, ], sep = "'"), collapse = "")), ".", file = code, append = TRUE)
}
}
}
if (isTRUE(any.factors)) {
x.factor <- which(vapply(x, is.factor, FUN.VALUE = logical(1)))
for (i in x.factor) {
values <- unique(as.numeric(x[, i]))
labels <- levels(x[, i])
cat("\nVALUE LABELS\n",
paste0(" ", names(xf)[i], paste0(paste0(" ", values, " '", labels, sep = "'"), collapse = "")), ".", file = code, append = TRUE)
}
}
miss.unique <- unique(misty::chr.trim(as.character(unique(var.attr[, match("missing", colnames(var.attr))]))))
miss.unique <- miss.unique[!miss.unique %in% c("", NA)]
if (isTRUE(length(miss.unique) == 1L)) {
cat(paste0("\nMISSING VALUES\n ", paste(varnames[which(var.attr$missing == miss.unique)], collapse = " "),
" (", gsub(";", " ", miss.unique), ")", "."), file = code, append = TRUE)
}
if (isTRUE(length(miss.unique) > 1L)) {
for (i in seq_len(var.length)) {
missing.values <- var.attr[i, match("missing", colnames(var.attr))]
if (isTRUE(missing.values != "")) {
cat("\nMISSING VALUES\n " , paste0(varnames[i], " (", paste(gsub(";", " ", missing.values), collapse = " "), ")", "."), file = code, append = TRUE)
}
}
}
} else {
if (isTRUE(any.factors)) {
x.factor <- which(vapply(x, is.factor, FUN.VALUE = logical(1)))
for (i in x.factor) {
values <- unique(as.numeric(x[, i]))
labels <- levels(x[, i])
cat("\nVALUE LABELS\n",
paste0(" ", names(xf)[i], paste0(paste0(" ", values, " '", labels, sep = "'"), collapse = "")), ".", file = code, append = TRUE)
}
}
}
cat("\nEXECUTE.\n", file = code, append = TRUE)
cat(paste0( "\nSAVE OUTFILE='", getwd() , "/" , file , ".sav'.\nEXECUTE."),
file = code, append = TRUE)
system(paste0("\"", pspp.path, "/bin/pspp.exe\" ", code))
if (!isTRUE(write.sps)) { unlink(paste0(file, ".sps")) }
if (!isTRUE(write.csv) | sep == ",") { unlink(paste0(file, ".csv")) }
if (isTRUE(write.csv) & sep == ",") { utils::write.csv(xf, paste0(file, ".csv"), row.names = FALSE, quote = FALSE, na = na) }
}
}
|
context("Posterior Frame")
test_that("Basic Test", {
testData <- rnorm(100)
testDP <- DirichletProcessGaussian(testData)
testDP <- Fit(testDP, 1, progressBar = FALSE)
testFrame <- PosteriorFrame(testDP, seq(-2, 2, length.out = 10))
expect_is(testFrame, "data.frame")
expect_equal(nrow(testFrame), 10)
expect_equal(ncol(testFrame), 4)
})
|
mean_test1<-function(x, mu=0, sigma=-1, side=0){
n<-length(x); xb<-mean(x)
if (sigma>=0){
z<-(xb-mu)/(sigma/sqrt(n))
P<-p_value(pnorm, z, side=side)
data.frame(mean=xb, df=n, Z=z, p_value=P)
}
else{
t<-(xb-mu)/(sd(x)/sqrt(n))
P<-p_value(pt, t, paramet=n-1, side=side)
data.frame(mean=xb, df=n-1, T=t, p_value=P)
}
}
|
setClass("sp_network_pair",
slots = c(orig_net_id = "character",
orig_nnodes = "maybe_numeric",
dest_net_id = "character",
dest_nnodes = "maybe_numeric",
network_pair_id = "character",
pair_data = "maybe_data.frame",
npairs = "maybe_numeric"))
setMethod(
f = "dat",
signature = "sp_network_pair", function(object) {
return(object@pair_data)
})
setReplaceMethod(
f = "dat",
signature = "sp_network_pair", function(object, value) {
object@pair_data <- value
object@npairs <- nrow(value)
validObject(object)
return(object)
})
setMethod(
f = "id",
signature = "sp_network_pair",
function(object) {
return(c(
"pair" = object@network_pair_id,
"orig" = object@orig_net_id,
"dest" = object@dest_net_id
))
})
setReplaceMethod(
f = "id",
signature = "sp_network_pair",
function(object,value) {
split_ids <- unlist(strsplit(value,"_"))
new_id_orig <- split_ids[1]
new_id_dest <- split_ids[2]
object@orig_net_id <- new_id_orig
object@dest_net_id <- new_id_dest
object@network_pair_id <- value
validObject(object)
return(object)
})
setMethod(
f = "npairs",
signature = "sp_network_pair",
function(object) {
return(object@npairs)
})
setMethod(
f = "nnodes",
signature = "sp_network_pair",
function(object) {
return(c(
"orig" = object@orig_nnodes,
"dest" = object@dest_nnodes
))
})
setMethod(
f = "show",
signature = "sp_network_pair",
function(object){
cat("Spatial network pair with id:",id(object)["pair"])
cat("\n")
cat(print_line(50))
od_explain <- "\n%s network id: %s (with %s nodes)"
cat(sprintf(od_explain,
"Origin", id(object)["orig"],
nnodes(object)["orig"] %||% "[?]"))
cat(sprintf(od_explain,
"Destination", id(object)["dest"],
nnodes(object)["dest"] %||% "[?]"))
has_all_counts <- length(c(npairs(object),nnodes(object))) == 3
if (has_all_counts) {
cat("\nNumber of pairs:", npairs(object))
pair_explain <- "\nCompleteness of pairs: %s (%i/%i)"
cat(sprintf(pair_explain,
format_percent(npairs(object) / prod(nnodes(object))),
npairs(object),
prod(nnodes(object))
))
}
has_data <- !is.null(dat(object))
if (has_data) {
cat("\n\nData on node-pairs:\n")
print(dat(object))
}
cat("\n")
invisible(object)
})
setValidity("sp_network_pair", function(object) {
ids <- id(object)
if (!valid_network_pair_id(ids["pair"])) {
error_msg <-
"The id of the pair object is invalid.\n Please ensure that the id " %p%
"is based on two alphanumeric strings sperated by an underscore, " %p%
"as for example 'alnum1_alnum2'!"
return(error_msg)
}
if (is.null(dat(object)))
return(TRUE)
data_keys <- attr_key_od(dat(object))
keys_exist <- all(data_keys %in% names(dat(object)))
if (is(dat(object),"data.table")) {
data_keys <- unique(dat(object)[,data_keys, with = FALSE])
} else {
data_keys <- unique(dat(object)[,data_keys, drop = FALSE])
}
unique_identification <- nrow(data_keys) == nrow(dat(object))
if (!all(keys_exist, unique_identification)) {
error_msg <-
"Based on the origin and destination key columns the observations " %p%
"are not unequely identifyed!"
return(error_msg)
}
return(TRUE)
})
sp_network_pair <- function(
orig_net_id,
dest_net_id,
pair_data = NULL,
orig_key_column,
dest_key_column
) {
network_pair <- new(
"sp_network_pair",
orig_net_id = orig_net_id,
orig_nnodes = NULL,
dest_net_id = dest_net_id,
dest_nnodes = NULL,
network_pair_id = orig_net_id %p% "_" %p% dest_net_id,
pair_data = NULL,
npairs = NULL)
if (is.null(pair_data) && validObject(network_pair))
return(network_pair)
assert_inherits(pair_data, "data.frame")
od_key_cols <- c(orig_key_column, dest_key_column)
has_orig_key <- orig_key_column %in% colnames(pair_data)
has_dest_key <-
assert(all(od_key_cols %in% colnames(pair_data)),
"The origin and destination key columns are not found in " %p%
"the pair data!")
attr_key_od(pair_data) <- od_key_cols
pair_data[[od_key_cols[1]]] <- factor_in_order(pair_data[[od_key_cols[1]]])
pair_data[[od_key_cols[2]]] <- factor_in_order(pair_data[[od_key_cols[2]]])
pair_data <- pair_data[order(pair_data[[od_key_cols[1]]],
pair_data[[od_key_cols[2]]]), ]
network_pair@pair_data <- pair_data
network_pair@orig_nnodes <- nlevels(pair_data[[od_key_cols[1]]])
network_pair@dest_nnodes <- nlevels(pair_data[[od_key_cols[2]]])
network_pair@npairs <- nrow(pair_data)
validObject(network_pair)
return(network_pair)
}
matrix_form_control <- function(sp_net_pair) {
matrix_arguments <- list(
"mat_complet" = npairs(sp_net_pair) / prod(nnodes(sp_net_pair)),
"mat_within" = id(sp_net_pair)["orig"] == id(sp_net_pair)["dest"],
"mat_npairs" = npairs(sp_net_pair),
"mat_nrows" = nnodes(sp_net_pair)["orig"],
"mat_ncols" = nnodes(sp_net_pair)["dest"],
"mat_format" = NULL)
if (matrix_arguments[["mat_complet"]] == 1) {
matrix_arguments[["mat_format"]] <- function(vec) {
matrix(vec,
nrow = matrix_arguments[["mat_nrows"]],
ncol = matrix_arguments[["mat_ncols"]])
}
}
if (matrix_arguments[["mat_complet"]] < 1) {
od_keys <- attr_key_od(dat(sp_net_pair))
mat_i_rows <- as.integer(dat(sp_net_pair)[[od_keys[1]]])
mat_j_cols <- as.integer(dat(sp_net_pair)[[od_keys[2]]])
matrix_arguments[["mat_format"]] <- function(vec) {
mat <- matrix(0,
nrow = matrix_arguments[["mat_nrows"]],
ncol = matrix_arguments[["mat_ncols"]])
mat[cbind(mat_i_rows, mat_j_cols)] <- vec
mat
}
}
if (matrix_arguments[["mat_complet"]] < .5) {
od_keys <- attr_key_od(dat(sp_net_pair))
matrix_arguments[["mat_format"]] <- function(vec) {
sparseMatrix(i= mat_i_rows, j=mat_j_cols,
x= vec,
dims = c(matrix_arguments[["mat_nrows"]],
matrix_arguments[["mat_ncols"]]))
}
}
return(matrix_arguments)
}
split_pair_id <- function(pair_id){
strsplit(pair_id,"_")[[1]]
}
attr_key_orig <- function(df) {
attr(df, "orig_key_column")
}
`attr_key_orig<-` <- function(df, value) {
attr(df, "orig_key_column") <- value
df
}
attr_key_dest <- function(df) {
attr(df, "dest_key_column")
}
`attr_key_dest<-` <- function(df, value) {
attr(df, "dest_key_column") <- value
df
}
attr_key_od <- function(df) {
c(attr_key_orig(df),
attr_key_dest(df))
}
`attr_key_od<-` <- function(df, value) {
attr_key_orig(df) <- value[1]
attr_key_dest(df) <- value[2]
df
}
valid_network_pair_id <- function(key) {
split_strings <- unlist(strsplit(key,"_",fixed = TRUE))
is_single_character(key) &&
length(split_strings) == 2 &&
valid_network_id(split_strings[1]) &&
valid_network_id(split_strings[2])
}
|
getclass.DN <- function(model){
mfamily <- NA
mclass <- attr(model, "class")[1]
if (mclass == "coxph.null")
stop("Error in model syntax: the model is null")
if (!mclass %in% c("lm", "glm", "coxph", "ols", "lrm", "Glm", "cph", "gam", "Gam", "glmnet"))
stop("Unrecognized model object type.")
if (mclass %in% c("elnet", "lognet", "multnet", "fishnet", "coxnet", "mrelnet")){
mclass <- "glmnet"
mfamily <- attr(model, "class")[1]
}
if (mclass %in% c("glm", "Glm"))
mfamily <- model$family$family
if (mclass == "lrm")
mfamily <- mclass
list(model.class = mclass, model.family = mfamily)
}
|
getKernel <- function(Kernel){
if (class(Kernel) != "character"){
return (Kernel)
}
switch(
Kernel,
"gaussian" = {
kernelFun <- stats::dnorm
},
"epanechnikov" = {
kernelFun <- function(x){return( as.numeric(abs(x) < 1) * (1-x^2) * 3 / 4 )}
},
"triangular" = {
kernelFun <- function(x){return( as.numeric(abs(x) < 1) * ( 1-abs(x) ) )}
},
{stop("kernel ", Kernel, " not implemented yet. ",
"Possible choices are 'gaussian', 'epanechnikov' and 'triangular'. ")}
)
return (kernelFun)
}
|
rfkrigeidwcv <- function (longlat, trainx, trainy, mtry = function(p) max(1, floor(sqrt(p))), ntree = 500, transformation = "none", delta = 1, formula = res1 ~ 1, vgm.args = c("Sph"), anis = c(0, 1), alpha = 0, block = 0, beta, nmaxkrige = 12, idp = 2, nmaxidw = 12, hybrid.parameter = 2, lambda = 1, validation = "CV", cv.fold = 10, predacc = "VEcv", ...) {
if (validation == "LOO") {idx <- 1:length(trainy)}
if (validation == "CV") {idx <- datasplit(trainy, k.fold = cv.fold)}
names(longlat) <- c("long", "lat")
n <- nrow(trainx)
p <- ncol(trainx)
cv.pred <- NULL
if (validation == "LOO") {
for (i in 1 : length(trainy)) {
data.dev <- trainx[idx != i, , drop = FALSE]
data.pred <- trainx[idx == i, , drop = FALSE]
rf1 <- randomForest::randomForest(data.dev, trainy[idx != i], mtry = mtry(p), ntree=ntree)
pred.rf1 <- stats::predict(rf1, data.pred)
dev.rf1 <- stats::predict(rf1, data.dev)
data.dev1 <- longlat[idx != i, , drop = FALSE]
data.pred1 <- longlat[idx == i, , drop = FALSE]
res1 <- trainy[idx != i] - dev.rf1
data.dev1$res1 <- res1
gstat1 <- gstat::gstat(id = "res1", formula = res1 ~ 1, locations = ~ long + lat, data = data.dev1, set = list(idp = idp), nmax = nmaxidw)
pred.idw1 <- stats::predict(gstat1, data.pred1)
if (transformation == "none") {data.dev1$res1 = res1} else (
if (transformation == "sqrt") {data.dev1$res1 = sqrt(res1 + abs(min(res1)))} else (
if (transformation == "arcsine") {data.dev1$res1 = asin(sqrt((res1 + abs(min(res1))) / 100))} else (
if (transformation == "log") {data.dev1$res1 = log(res1 + abs(min(res1)) + delta)} else (
stop ("This transfromation is not supported in this version!")))))
sp::coordinates(data.dev1) = ~ long + lat
vgm1 <- gstat::variogram(object = formula, data.dev1, alpha = alpha)
model.1 <- gstat::fit.variogram(vgm1, gstat::vgm(mean(vgm1$gamma), vgm.args, mean(vgm1$dist), min(vgm1$gamma)/10, anis = anis))
if (model.1$range[2] <= 0) (cat("A zero or negative range was fitted to variogram", "\n"))
if (model.1$range[2] <= 0) (model.1$range[2] <- min(vgm1$dist))
sp::coordinates(data.pred1) = ~long + lat
pred.krige1 <- gstat::krige(formula = formula, data.dev1, data.pred1, model = model.1, nmax=nmaxkrige, block = block, beta = beta)$var1.pred
if (transformation == "none") {pred.krige = pred.krige1}
if (transformation == "sqrt") {pred.krige = pred.krige1 ^ 2 - abs(min(res1))}
if (transformation == "arcsine") {pred.krige = (sin(pred.krige1)) ^ 2 * 100 - abs(min(res1))}
if (transformation == "log") {pred.krige = exp(pred.krige1) - abs(min(res1)) - delta}
cv.pred[idx == i] <- (pred.krige * (2 - lambda) + pred.idw1$res1.pred * lambda + pred.rf1 * hybrid.parameter) / hybrid.parameter
}
}
if (validation == "CV") {
for (i in 1 : cv.fold) {
data.dev <- trainx[idx != i, , drop = FALSE]
data.pred <- trainx[idx == i, , drop = FALSE]
rf1 <- randomForest::randomForest(data.dev, trainy[idx != i], mtry = mtry(p), ntree=ntree)
pred.rf1 <- stats::predict(rf1, data.pred)
dev.rf1 <- stats::predict(rf1, data.dev)
data.dev1 <- longlat[idx != i, , drop = FALSE]
data.pred1 <- longlat[idx == i, , drop = FALSE]
res1 <- trainy[idx != i] - dev.rf1
data.dev1$res1 <- res1
gstat1 <- gstat::gstat(id = "res1", formula = res1 ~ 1, locations = ~ long + lat, data = data.dev1, set = list(idp = idp), nmax = nmaxidw)
pred.idw1<- stats::predict(gstat1, data.pred1)
if (transformation == "none") {data.dev1$res1 = res1} else (
if (transformation == "sqrt") {data.dev1$res1 = sqrt(res1 + abs(min(res1)))} else (
if (transformation == "arcsine") {data.dev1$res1 = asin(sqrt((res1 + abs(min(res1))) / 100))} else (
if (transformation == "log") {data.dev1$res1 = log(res1 + abs(min(res1)) + delta)} else (
stop ("This transfromation is not supported in this version!")))))
sp::coordinates(data.dev1) = ~ long + lat
vgm1 <- gstat::variogram(object = formula, data.dev1, alpha = alpha)
model.1 <- gstat::fit.variogram(vgm1, gstat::vgm(mean(vgm1$gamma), vgm.args, mean(vgm1$dist), min(vgm1$gamma)/10, anis = anis))
if (model.1$range[2] <= 0) (cat("A zero or negative range was fitted to variogram", "\n"))
if (model.1$range[2] <= 0) (model.1$range[2] <- min(vgm1$dist))
sp::coordinates(data.pred1) = ~long + lat
pred.krige1 <- gstat::krige(formula = formula, data.dev1, data.pred1, model = model.1, nmax=nmaxkrige, block = block, beta = beta)$var1.pred
if (transformation == "none") {pred.krige = pred.krige1}
if (transformation == "sqrt") {pred.krige = pred.krige1 ^ 2 - abs(min(res1))}
if (transformation == "arcsine") {pred.krige = (sin(pred.krige1)) ^ 2 * 100 - abs(min(res1))}
if (transformation == "log") {pred.krige = exp(pred.krige1) - abs(min(res1)) - delta}
cv.pred[idx == i] <- (pred.krige * (2 - lambda) + pred.idw1$res1.pred * lambda + pred.rf1* hybrid.parameter) / hybrid.parameter
}
}
if (predacc == "VEcv") {predictive.accuracy = spm::vecv(trainy, cv.pred)} else (
if (predacc == "ALL") {predictive.accuracy = spm::pred.acc(trainy, cv.pred)} else (
stop ("This measure is not supported in this version!")))
predictive.accuracy
}
|
print.cv.relaxed <- function(x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\nCall: ", deparse(x$call), "\n\n")
cat("Measure:", x$name, "\n\n")
x = x$relaxed
optlams = c(x$lambda.min, x$lambda.1se)
wg1 = match(x$gamma.min, x$gamma)
wl1 = match(x$lambda.min, x$statlist[[wg1]]$lambda)
s1 = with(x$statlist[[wg1]], c(x$gamma.min,wg1, x$lambda.min,wl1,
cvm[wl1], cvsd[wl1], x$nzero.min))
wg2 = match(x$gamma.1se, x$gamma)
wl2 = match(x$lambda.1se, x$statlist[[wg2]]$lambda)
s2 = with(x$statlist[[wg2]], c(x$gamma.1se,wg2, x$lambda.1se,wl2,
cvm[wl2], cvsd[wl2], x$nzero.1se))
mat = rbind(s1, s2)
dimnames(mat) = list(c("min", "1se"), c("Gamma","Index", "Lambda","Index",
"Measure", "SE", "Nonzero"))
mat = data.frame(mat, check.names = FALSE)
class(mat) = c("anova", class(mat))
print(mat, digits = digits)
}
|
screen_duplicates <- function(
x,
max_file_size
){
if(!missing(max_file_size)){
initial_file_size <- options("shiny.maxRequestSize")
options(shiny.maxRequestSize = max_file_size * 1024^2)
on.exit(options(initial_file_size))
}
input_data <- list(
raw = NULL,
columns = NULL,
grouped = NULL
)
if(missing(x)){
x <- NULL
}
if(!is.null(x)){
accepted_inputs <- c("bibliography", "data.frame")
if(any(accepted_inputs == class(x)) == FALSE){
stop("only classes 'bibliography' or 'data.frame' accepted by screen_duplicates")}
if(class(x) == "bibliography"){
x <- as.data.frame(x)
}
colnames(x) <- tolower(colnames(x))
input_data$columns <- colnames(x)
if(!any(colnames(x) == "label")){
x$label <- create_index("ref", nrow(x))
x <- x[, c(ncol(x), seq_len(ncol(x)-1))]
}else{
x$label <- make.unique(x$label, sep = "_")
}
}
input_data$raw <- x
ui_data <- screen_duplicates_ui()
ui <- shinydashboard::dashboardPage(
title = "revtools | screen_duplicates",
ui_data$header,
ui_data$sidebar,
ui_data$body,
skin = "black"
)
server <- function(input, output, session){
data <- reactiveValues(
raw = input_data$raw,
columns = input_data$columns,
grouped = NULL
)
display <- reactiveValues(
data_present = FALSE,
columns = input_data$columns
)
progress <- reactiveValues(
entry = NULL
)
output$header <- renderPlot({
revtools_logo(text = "screen_duplicates")
})
observeEvent(input$data_in, {
if(is.null(data$raw)){
data_in <- x
}else{
data_in <- data$raw
}
import_result <- import_shiny(
source = input$data_in,
current_data = data_in
)
if(any(colnames(import_result) == "label")){
import_result$label <- make.unique(
names = import_result$label,
sep = "_"
)
}else{
import_result$label <- paste0(
"v",
seq_len(nrow(import_result))
)
}
data$raw <- import_result
data$columns <- colnames(import_result)
display$columns <- data$columns
})
output$data_selector <- renderUI({
if(!is.null(data$raw)){
selectInput(
inputId = "duplicates_present",
label = "Is there a variable describing duplicates in this dataset?",
choices = c("No", "Yes")
)
}
})
observeEvent(input$duplicates_present, {
if(input$duplicates_present == "Yes"){
display$data_present <- TRUE
}else{
display$data_present <- FALSE
}
})
output$response_selector <- renderUI({
if(!is.null(data$columns)){
if(display$data_present){
if(any(data$columns == "matches")){
selected <- "matches"
}else{
selected <- data$columns[1]
}
shiny::tagList(
selectInput(
inputId = "match_columns",
label = "Select column containing duplicate data",
choices = data$columns,
selected = selected
),
actionButton(
inputId = "go_duplicates",
label = "Select",
width = "85%"
)
)
}else{
if(any(data$columns == "title")){
selected <- "title"
}else{
selected <- data$columns[1]
}
selectInput(
inputId = "response_selector_result",
label = "Select column to search for duplicates",
choices = data$columns,
selected = selected
)
}
}
})
output$group_selector <- renderUI({
if(!is.null(data$columns) & !display$data_present){
checkboxGroupInput(
inputId = "group_selector_result",
label = "Select grouping variable(s)",
choices = data$columns,
selected = NULL
)
}
})
output$display_selector <- renderUI({
if(!is.null(data$columns)){
checkboxGroupInput(
inputId = "display_result",
label = "Select variables to display",
choices = data$columns,
selected = data$columns
)
}
})
observeEvent(input$display_result, {
display$columns <- input$display_result
})
observe({
output$algorithm_selector <- renderUI({
if(input$match_function == "fuzzdist"){
algorithm_list <- list(
"M Ratio" = "fuzz_m_ratio",
"Partial Ratio" = "fuzz_partial_ratio",
"Token Sort Ratio" = "fuzz_token_sort_ratio",
"Token Set Ratio" = "fuzz_token_set_ratio"
)
}else{
algorithm_list <- c(
"osa", "lv", "dl",
"hamming", "lcs",
"qgram", "cosine",
"jaccard", "jw", "soundex"
)
}
if(input$match_function != "exact"){
selectInput(
inputId = "match_algorithm",
label = "Select method",
choices = algorithm_list
)
}
})
})
observe({
output$threshold_selector <- renderUI({
if(input$match_function == "fuzzdist"){
max_val <- 1
initial_val <- 0.1
step_val <- 0.05
}else{
max_val <- 20
initial_val <- 5
step_val <- 1
}
if(input$match_function != "exact"){
sliderInput(
inputId = "match_threshold",
label = "Select maximum distance",
min = 0,
max = max_val,
value = initial_val,
step = step_val
)
}
})
})
observeEvent(input$go_duplicates, {
data$raw$matches <- data$raw[, input$match_columns]
group_result <- split(data$raw, data$raw$matches)
group_result <- group_result[
which(unlist(lapply(group_result, nrow)) > 1)
]
if(length(group_result) > 0){
progress$entry <- 1
data$grouped <- group_result
}else{
progress$entry <- NULL
}
})
observeEvent(input$calculate_duplicates, {
if(length(input$response_selector_result) < 1 & length(input$group_selector_result) < 1){
if(length(input$response_selector_result) < 1){
error_modal("Please select a variable to match records by<br><br>
<em>Click anywhere to exit</em>"
)
}else{
error_modal("Please select 1 or more variables to group records by<br><br>
<em>Click anywhere to exit</em>"
)
}
}else{
calculating_modal()
data$raw$matches <- find_duplicates(
data = data$raw,
match_variable = input$response_selector_result,
group_variables = input$group_selector_result,
match_function = input$match_function,
method = input$match_algorithm,
threshold = input$match_threshold,
to_lower = input$match_lower,
remove_punctuation = input$match_punctuation
)
group_result <- split(data$raw, data$raw$matches)
row_counts <- unlist(lapply(group_result, nrow))
if(any(row_counts > 2)){
large_list <- group_result[which(row_counts > 2)]
cleaned_list <- lapply(large_list, function(a){
apply(
combn(nrow(a), 2),
2,
function(b, lookup){lookup[as.numeric(b), ]},
lookup = a
)
})
extracted_list <- do.call(c, cleaned_list)
if(any(row_counts == 2)){
group_result <- c(
group_result[which(row_counts == 2)],
extracted_list
)
}else{
group_result <- extracted_list
}
}else{
group_result <- group_result[which(row_counts > 1)]
}
if(length(group_result) > 0){
progress$entry <- 1
data$grouped <- group_result
removeModal()
}else{
progress$entry <- NULL
removeModal()
no_duplicates_modal()
}
}
})
output$selector_1 <- renderUI({
if(!is.null(progress$entry)){
actionButton(
inputId = "selected_1",
label = "Select Entry
width = "100%"
)
}
})
output$selector_2 <- renderUI({
if(!is.null(progress$entry)){
actionButton(
inputId = "selected_2",
label = "Select Entry
width = "100%"
)
}
})
output$selector_bar <- renderUI({
if(is.null(data$raw)){
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 780px",
renderText({"Load data to continue"})
)
}else{
if(is.null(data$grouped)){
text_out <- HTML(
paste0(
"Dataset with ",
nrow(data$raw),
" entries"
)
)
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 780px",
renderText({text_out})
)
}else{
text_out <- HTML(
paste0("Dataset with ",
nrow(data$raw),
" entries | ",
" Showing duplicate ",
progress$entry,
" of ",
length(data$grouped)
)
)
div(
list(
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 556px",
renderText({text_out})
),
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 20px",
renderText(" ")
),
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 40px",
actionButton(
inputId = "selected_previous",
label = "<",
width = "40px",
style = "background-color:
)
),
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 110px",
actionButton(
inputId = "selected_none",
label = "Not duplicates",
width = "110px",
style = "background-color:
)
),
div(
style = "
display: inline-block;
vertical-align: top;
text-align: right;
width: 40px",
actionButton(
inputId = "selected_next",
label = ">",
width = "40px",
style = "background-color:
)
)
)
)
}
}
})
output$text_1 <- renderPrint({
validate(
need(length(data$grouped) > 0, "")
)
format_duplicates(
x = data$grouped[[progress$entry]][1, ],
columns = display$columns,
breaks = input$author_line_breaks
)
})
output$text_2 <- renderPrint({
validate(
need(length(data$grouped) > 0, "")
)
format_duplicates(
x = data$grouped[[progress$entry]][2, ],
columns = display$columns,
breaks = input$author_line_breaks
)
})
observeEvent(input$selected_1, {
label_exclude <- data$grouped[[progress$entry]]$label[2]
data$raw <- data$raw[which(data$raw$label != label_exclude), ]
data$grouped <- data$grouped[-progress$entry]
if(progress$entry > length(data$grouped)){
if(length(data$grouped) == 0){
progress$entry <- NULL
save_modal(
x = data$raw,
title = "Screening Complete: Save results?"
)
}else{
progress$entry <- length(data$grouped)
}
}
})
observeEvent(input$selected_2, {
label_exclude <- data$grouped[[progress$entry]]$label[1]
data$raw <- data$raw[which(data$raw$label != label_exclude), ]
data$grouped <- data$grouped[-progress$entry]
if(progress$entry > length(data$grouped)){
if(length(data$grouped) == 0){
progress$entry <- NULL
save_modal(
x = data$raw,
title = "Screening Complete: Save results?"
)
}else{
progress$entry <- length(data$grouped)
}
}
})
observeEvent(input$selected_none, {
label_exclude <- data$grouped[[progress$entry]]$label[2]
data$raw$matches[which(data$raw$label == label_exclude)] <- max(data$raw$matches)+1
data$grouped <- data$grouped[-progress$entry]
if(progress$entry > length(data$grouped)){
if(length(data$grouped) == 0){
progress$entry <- NULL
save_modal(
x = data$raw,
title = "Screening Complete: Save results?"
)
}else{
progress$entry <- length(data$grouped)
}
}
})
observeEvent(input$selected_previous, {
if(progress$entry > 1){
progress$entry <- progress$entry - 1
}
})
observeEvent(input$selected_next, {
if((progress$entry + 1) <= length(data$grouped)){
progress$entry <- progress$entry + 1
}
})
observeEvent(input$clear_data, {
clear_data_modal()
})
observeEvent(input$clear_data_confirmed, {
data$raw <- NULL
data$columns <- NULL
data$grouped <- NULL
progress$entry <- NULL
removeModal()
})
observeEvent(input$save_data, {
save_modal(data$raw)
})
observeEvent(input$save_data_execute, {
if(nchar(input$save_filename) == 0){
filename <- "revtools_data"
}else{
if(grepl("\\.[[:lower:]]{3}$", input$save_filename)){
filename <- substr(
input$save_filename, 1,
nchar(input$save_filename) - 4
)
}else{
filename <- input$save_filename
}
}
filename <- paste(filename, input$save_type , sep = ".")
switch(input$save_type,
"csv" = {
write.csv(data$raw,
file = filename,
row.names = FALSE
)
},
"rds" = {
saveRDS(
data$raw,
file = filename
)
}
)
removeModal()
})
observeEvent(input$exit_app, {
exit_modal()
})
observeEvent(input$exit_app_confirmed, {
stopApp(returnValue = invisible(data$raw))
})
}
print(shinyApp(ui, server))
}
|
Return.annualized.excess <-
function (Rp, Rb, scale = NA, geometric = TRUE )
{
Rp = checkData(Rp)
Rb = checkData(Rb)
Rp = na.omit(Rp)
Rb = na.omit(Rb)
n = nrow(Rp)
if(is.na(scale)) {
freq = periodicity(Rp)
switch(freq$scale,
minute = {stop("Data periodicity too high")},
hourly = {stop("Data periodicity too high")},
daily = {scale = 252},
weekly = {scale = 52},
monthly = {scale = 12},
quarterly = {scale = 4},
yearly = {scale = 1}
)
}
Rpa = apply(1 + Rp, 2, prod)^(scale/n) - 1
Rba = apply(1 + Rb, 2, prod)^(scale/n) - 1
if (geometric) {
result = (1 + Rpa) / (1 + Rba) - 1
} else {
result = Rpa - Rba
}
dim(result) = c(1,NCOL(Rp))
colnames(result) = colnames(Rp)
rownames(result) = "Annualized Return"
return(result)
}
|
byf.mshapiro <- function(formula,data) {
if (missing(formula)||(length(formula)!=3)) {stop("missing or incorrect formula")}
m <- match.call()
m[[1]] <- as.name("model.frame")
mf <- eval(m,parent.frame())
for (i in 1:ncol(mf)) {
if (all(is.na(suppressWarnings(as.numeric(as.character(mf[,i])))))) {
fact1 <- i
break
}
}
resp <- mf[,1:(fact1-1)]
fact <- interaction(mf[,fact1:ncol(mf)],sep=":")
dname <- paste(names(mf)[1]," by ",paste(names(mf)[fact1:ncol(mf)],collapse=":"),sep="")
nlev <- nlevels(fact)
tab <- data.frame(W=integer(nlev),"p-value"=integer(nlev),check.names=FALSE)
rownames(tab) <- levels(fact)
for (i in 1:nlev) {
test <- mshapiro.test(resp[as.numeric(fact)==i,])
tab[i,1] <- test$statistic
tab[i,2] <- test$p.value
}
result <- list(method="Multivariate Shapiro-Wilk normality tests",data.name=dname,tab=tab)
class(result) <- "byf.test"
return(result)
}
|
StatHalfPoint <- ggproto(
"StatHalfPoint", StatBoxplot,
required_aes = c("y"),
non_missing_aes = "weight",
setup_data = function(data, params) {
data$x <- data$x %||% 0
data <- remove_missing(
data,
na.rm = FALSE,
vars = "x",
name = "stat_boxplot"
)
data
},
compute_group = function(data, scales, width = NULL, na.rm = FALSE, coef = 1.5) {
df <- StatBoxplot$compute_group(data, scales, width, na.rm, coef)
df$point_y <- list(data$y)
df$point_colour <- list(data$colour)
df$point_shape <- list(data$shape)
df$point_size <- list(data$size)
df$point_fill <- list(data$fill)
df$point_alpha <- list(data$alpha)
df$point_stroke <- list(data$stroke)
df$y <- df$ymax
df
}
)
|
context("aovEffectSize")
test_that("aovEffectSize", {
set.seed(1)
dat <- createDF(nVP = 20, nTrl = 1,
design = list("Comp" = c("comp", "incomp")))
dat <- addDataDF(dat, RT = list("Comp comp" = c(500, 150, 100),
"Comp incomp" = c(550, 150, 100)))
aovRT <- aov(RT ~ Comp + Error(VP/(Comp)), dat)
testthat::expect_error(aovEffectSize(aovRT, effectSize = "pes"), NA)
testthat::expect_error(aovEffectSize(aovRT, effectSize = "ges"), NA)
aovRT <- ezANOVA(dat, dv = .(RT), wid = .(VP), within = .(Comp),
return_aov = TRUE, detailed = TRUE)
testthat::expect_error(aovEffectSize(aovRT, effectSize = "pes"), NA)
testthat::expect_error(aovEffectSize(aovRT, effectSize = "ges"), NA)
})
|
beach_tc <- generate_transitive_closure(beach_preferences)
beach_init_rank <- generate_initial_ranking(beach_tc)
constr <- generate_constraints(beach_tc, n_items = 15)
model_fit <- compute_mallows(rankings = beach_init_rank,
preferences = beach_tc, constraints = constr)
\dontrun{
library(parallel)
cl <- makeCluster(detectCores() - 1)
constr <- generate_constraints(beach_tc, n_items = 15, cl = cl)
stopCluster(cl)
}
|
knitr::opts_chunk$set(fig.width=6, fig.height=4.5)
options(width=800)
library(bayes4psy)
library(cowplot)
library(dplyr)
library(ggplot2)
data_all <- after_images
stimuli <- after_images_stimuli
data_red <- data_all %>% filter(stimuli == "red")
data_red <- data.frame(r=data_red$r,
g=data_red$g,
b=data_red$b)
fit_red <- b_color(colors=data_red, chains=1, iter=200, warmup=100)
plot_trace(fit_red)
plot_hsv(fit_red)
data_green <- data_all %>% filter(stimuli == "green")
data_green <- data.frame(r=data_green$r,
g=data_green$g,
b=data_green$b)
fit_green <- b_color(colors=data_green, chains=1, iter=200, warmup=100)
data_blue <- data_all %>% filter(stimuli == "blue")
data_blue <- data.frame(r=data_blue$r,
g=data_blue$g,
b=data_blue$b)
fit_blue <- b_color(colors=data_blue, chains=1, iter=200, warmup=100)
data_yellow <- data_all %>% filter(stimuli == "yellow")
data_yellow <- data.frame(r=data_yellow$r,
g=data_yellow$g,
b=data_yellow$b)
fit_yellow <- b_color(colors=data_yellow, chains=1, iter=200, warmup=100)
data_cyan <- data_all %>% filter(stimuli == "cyan")
data_cyan <- data.frame(r=data_cyan$r,
g=data_cyan$g,
b=data_cyan$b)
fit_cyan <- b_color(colors=data_cyan, chains=1, iter=200, warmup=100)
data_magenta <- data_all %>% filter(stimuli == "magenta")
data_magenta <- data.frame(r=data_magenta$r,
g=data_magenta$g,
b=data_magenta$b)
fit_magenta <- b_color(colors=data_magenta, chains=1, iter=200, warmup=100)
trichromatic <- after_images_trichromatic
opponent_process <- after_images_opponent_process
stimulus <- "red"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_red <- plot_distributions_hsv(fit_red, points=points,
lines=lines, hsv=TRUE)
plot_red <- plot_red + ggtitle("Red") +
theme(plot.title = element_text(hjust = 0.5))
stimulus <- "green"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_green <- plot_distributions_hsv(fit_green, points=points,
lines=lines, hsv=TRUE)
plot_green <- plot_green + ggtitle("Green") +
theme(plot.title = element_text(hjust = 0.5))
stimulus <- "blue"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_blue <- plot_distributions_hsv(fit_blue, points=points,
lines=lines, hsv=TRUE)
plot_blue <- plot_blue + ggtitle("Blue") +
theme(plot.title = element_text(hjust = 0.5))
stimulus <- "yellow"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_yellow <- plot_distributions_hsv(fit_yellow, points=points,
lines=lines, hsv=TRUE)
plot_yellow <- plot_yellow + ggtitle("Yellow") +
theme(plot.title = element_text(hjust = 0.5))
stimulus <- "cyan"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_cyan <- plot_distributions_hsv(fit_cyan, points=points,
lines=lines, hsv=TRUE)
plot_cyan <- plot_cyan + ggtitle("Cyan") +
theme(plot.title = element_text(hjust = 0.5))
stimulus <- "magenta"
lines <- list()
lines[[1]] <- c(trichromatic[trichromatic$stimuli == stimulus, ]$h,
trichromatic[trichromatic$stimuli == stimulus, ]$s,
trichromatic[trichromatic$stimuli == stimulus, ]$v)
lines[[2]] <- c(opponent_process[opponent_process$stimuli == stimulus, ]$h,
opponent_process[opponent_process$stimuli == stimulus, ]$s,
opponent_process[opponent_process$stimuli == stimulus, ]$v)
points <- list()
points[[1]] <- c(stimuli[stimuli$stimuli == stimulus, ]$h_s,
stimuli[stimuli$stimuli == stimulus, ]$s_s,
stimuli[stimuli$stimuli == stimulus, ]$v_s)
plot_magenta <- plot_distributions_hsv(fit_magenta, points=points,
lines=lines, hsv=TRUE)
plot_magenta <- plot_magenta + ggtitle("Magenta") +
theme(plot.title = element_text(hjust = 0.5))
plot_grid(plot_red, plot_green, plot_blue,
plot_yellow, plot_cyan, plot_magenta,
ncol=3, nrow=2, scale=0.9)
|
retrieve <- function(sso, what, ...) {
sso_check(sso)
.retrieve(sso, what, ...)
}
.retrieve <- function(sso, what, ...) {
if (what %in% c("rhat", "rhats", "Rhat", "Rhats", "r_hat", "R_hat"))
return(retrieve_rhat(sso, ...))
if (what %in% c("N_eff", "n_eff", "neff", "Neff", "ess", "ESS"))
return(retrieve_neff(sso, ...))
if (grepl_ic("mean", what))
return(retrieve_mean(sso, ...))
if (grepl_ic("sd", what))
return(retrieve_sd(sso, ...))
if (what %in% c("se_mean", "mcse"))
return(retrieve_mcse(sso, ...))
if (grepl_ic("quant", what))
return(retrieve_quant(sso, ...))
if (grepl_ic("median", what))
return(retrieve_median(sso, ...))
if (grepl_ic("tree", what) | grepl_ic("depth", what))
return(retrieve_max_treedepth(sso, ...))
if (grepl_ic("step", what))
return(retrieve_avg_stepsize(sso, ...))
if (grepl_ic("diverg", what))
return(retrieve_prop_divergent(sso, ...))
if (grepl_ic("accept", what))
return(retrieve_avg_accept(sso, ...))
}
retrieve_rhat <- function(sso, pars) {
if (missing(pars))
return(slot(sso, "summary")[, "Rhat"])
slot(sso, "summary")[pars, "Rhat"]
}
retrieve_neff <- function(sso, pars) {
if (missing(pars))
return(slot(sso, "summary")[, "n_eff"])
slot(sso, "summary")[pars, "n_eff"]
}
retrieve_mcse <- function(sso, pars) {
if (missing(pars))
return(slot(sso, "summary")[, "se_mean"])
slot(sso, "summary")[pars, "se_mean"]
}
retrieve_quant <- function(sso, pars) {
cols <- paste0(100 * c(0.025, 0.25, 0.5, 0.75, 0.975), "%")
if (missing(pars))
return(slot(sso, "summary")[, cols])
slot(sso, "summary")[pars, cols]
}
retrieve_median <- function(sso, pars) {
if (missing(pars))
return(retrieve_quant(sso)[, "50%"])
retrieve_quant(sso, pars)[, "50%"]
}
retrieve_mean <- function(sso, pars) {
if (missing(pars))
return(slot(sso, "summary")[, "mean"])
slot(sso, "summary")[pars, "mean"]
}
retrieve_sd <- function(sso, pars) {
if (missing(pars))
return(slot(sso, "summary")[, "sd"])
slot(sso, "summary")[pars, "sd"]
}
.sp_check <- function(sso) {
if (identical(slot(sso, "sampler_params"), list(NA)))
stop("No sampler parameters found", call. = FALSE)
}
.which_rows <- function(sso, inc_warmup) {
if (inc_warmup) {
seq_len(slot(sso, "n_iter"))
} else {
seq(from = 1 + slot(sso, "n_warmup"), to = slot(sso, "n_iter"))
}
}
retrieve_max_treedepth <- function(sso, inc_warmup = FALSE) {
.sp_check(sso)
rows <- .which_rows(sso, inc_warmup)
max_td <- sapply(slot(sso, "sampler_params"), function(x)
max(x[rows, "treedepth__"]))
names(max_td) <- paste0("chain", 1:length(max_td))
max_td
}
retrieve_prop_divergent <- function(sso, inc_warmup = FALSE) {
.sp_check(sso)
rows <- .which_rows(sso, inc_warmup)
prop_div <- sapply(slot(sso, "sampler_params"), function(x)
mean(x[rows, "divergent__"]))
names(prop_div) <- paste0("chain", 1:length(prop_div))
prop_div
}
retrieve_avg_stepsize <- function(sso, inc_warmup = FALSE) {
.sp_check(sso)
rows <- .which_rows(sso, inc_warmup)
avg_ss <- sapply(slot(sso, "sampler_params"), function(x)
mean(x[rows, "stepsize__"]))
names(avg_ss) <- paste0("chain", 1:length(avg_ss))
avg_ss
}
retrieve_avg_accept <- function(sso, inc_warmup = FALSE) {
.sp_check(sso)
rows <- .which_rows(sso, inc_warmup)
avg_accept <- sapply(slot(sso, "sampler_params"), function(x)
mean(x[rows, "accept_stat__"]))
names(avg_accept) <- paste0("chain", 1:length(avg_accept))
avg_accept
}
|
test_that("Test derivative checker.", {
f <- function(x, a) {
sum((x - a )^2)
}
f_grad <- function(x, a) {
2 * (x - a)
}
a <- c(0.754995959345251, 0.964991861954331, 0.0414307734463364, 0.42781219445169, 0.6517094373703,
0.838369226781651, 0.774285392835736, 0.531992698321119, 0.768715722020715, 0.785174649208784)
res <- suppressMessages(check.derivatives(
.x = 1:10,
func = f,
func_grad = f_grad,
check_derivatives_print = 'none',
a = a
))
expect_equal(sum(res$flag_derivative_warning), 0)
f_grad <- function(x, a) {
2 * (x - a) + c(0, .1, rep(0, 8))
}
res <- suppressMessages(check.derivatives(
.x = 1:10,
func = f,
func_grad = f_grad,
check_derivatives_print = 'none',
a = a
))
expect_equal(sum(res$flag_derivative_warning), 1)
g <- function(x, a) {
c(sum(x - a), sum((x - a)^2))
}
g_grad <- function(x, a) {
rbind(rep(1, length(x)) + c(0, .01, rep(0, 8)), 2 * (x - a) + c(0, .1, rep(0, 8)))
}
res <- suppressMessages(check.derivatives(
.x = 1:10,
func = g,
func_grad = g_grad,
check_derivatives_print = 'none',
a = a
))
expect_equal(sum(res$flag_derivative_warning), 2)
})
|
xwfGridsearch <-
function(y, xx, t, n.i, psi.list = default_psi(), F = NULL, z = NULL, iter = 3, w = function(t, i, b, left) ifelse(left, min(1, (1-F(xx[[i]](t)))/(1-b)), min(1, F(xx[[i]](t))/b)), rel.shift = .001, progressbar = TRUE) {
if(!is.function(psi.list[[1]])) stop("local feature 'psi.list' is not specified as a list of functions")
if(!is.function(xx[[1]])) stop("trajectories 'xx' is not specified as a list of functions")
n <- length(xx)
if(length(n.i) == 1) n.i <- rep(n.i, n)
t.min <- apply(X = t, MARGIN = 1, FUN = min, na.rm = T)
t.max <- apply(X = t, MARGIN = 1, FUN = max, na.rm = T)
t.range <- t.max-t.min
p <- length(psi.list)
XWFmatL <- matrix(data = NA_real_, nrow = p*2^(iter+1), ncol = n+2)
XWFmatR <- matrix(data = NA_real_, nrow = p*2^(iter+1), ncol = n+2)
countL <- 0
countR <- 0
findXWFl <- function(p, b) {
temp <- which(XWFmatL[ , 1] == p & XWFmatL[ , 2] == b)
if(length(temp) == 1) return(XWFmatL[temp, -(1:2)])
countL <<- countL+1
XWFmatL[countL, 1:2] <<- c(p, b)
XWFmatL[countL, -(1:2)] <<- xwf(xx = xx, t = t, n.i = n.i, psi = psi.list[[p]], w = function(t, i) w(t, i, b = b, left = TRUE), t.min = t.min, t.max = t.max, t.range = t.range)
return(XWFmatL[countL, -(1:2)])
}
findXWFr <- function(p, b) {
temp <- which(XWFmatR[ , 1] == p & XWFmatR[ , 2] == b)
if(length(temp) == 1) return(XWFmatR[temp, -(1:2)])
countR <<- countR+1
XWFmatR[countR, 1:2] <<- c(p, b)
XWFmatR[countR, -(1:2)] <<- xwf(xx = xx, t = t, n.i = n.i, psi = psi.list[[p]], w = function(t, i) w(t, i, b = b, left = FALSE), t.min = t.min, t.max = t.max, t.range = t.range)
return(XWFmatR[countR, -(1:2)])
}
wL <- matrix(nrow = n, ncol = p)
wR <- wL
for(pp in 1:p) {
wL[, pp] <- findXWFl(p = pp, b = .25)
wR[, pp] <- findXWFr(p = pp, b = .75)
}
modelfit <- xwfGAM(wL = wL, wR = wR, y = y, z = z)
score <- modelfit$gcv.ubre
left <- rep(.25, p)
right <- rep(.75, p)
if(progressbar) pb <- txtProgressBar(max = iter, style = 3)
for(s in 1:iter) {
grid.width <- .5/2^s
for(pp in 1:p) {
wLl <- wL
wLl[, pp] <- findXWFl(p = pp, b = left[pp] - grid.width)
modelfit.l <- tryCatch(
xwfGAM(wL = wLl, wR = wR, y = y, z = z),
error = function(e) {
cat("ERROR :",conditionMessage(e), "\n")
return(modelfit)
}
)
score.l <- modelfit.l$gcv.ubre
wLr <- wL
wLr[, pp] <- findXWFl(p = pp, b = left[pp] + grid.width)
modelfit.r <- tryCatch(
xwfGAM(wL = wLr, wR = wR, y = y, z = z),
error = function(e) {
cat("ERROR :",conditionMessage(e), "\n")
return(modelfit)
}
)
score.r <- modelfit.l$gcv.ubre
temp <- which.min(c(score.l, score.r, score))
if(temp == 1) {
left[pp] <- left[pp] - grid.width/2
wL <- wLl
score <- score.l
modelfit <- modelfit.l
} else if(temp == 2) {
left[pp] <- left[pp] + grid.width/2
wL <- wLr
score <- score.r
modelfit <- modelfit.r
}
wRl <- wR
wRl[, pp] <- findXWFr(p = pp, b = right[pp] - grid.width)
modelfit.l <- tryCatch(
xwfGAM(wL = wL, wR = wRl, y = y, z = z),
error = function(e) {
cat("ERROR :",conditionMessage(e), "\n")
return(modelfit)
}
)
score.l <- modelfit.l$gcv.ubre
wRr <- wR
wRr[, pp] <- findXWFr(p = pp, b = right[pp] + grid.width)
modelfit.r <- tryCatch(
xwfGAM(wL = wL, wR = wRr, y = y, z = z),
error = function(e) {
cat("ERROR :",conditionMessage(e), "\n")
return(modelfit)
}
)
score.r <- modelfit.r$gcv.ubre
temp <- which.min(c(score.l, score.r, score))
if(temp == 1) {
right[pp] <- right[pp] - grid.width/2
wR <- wRl
score <- score.l
modelfit <- modelfit.l
} else if(temp == 2) {
right[pp] <- right[pp] + grid.width/2
wR <- wRr
score <- score.r
modelfit <- modelfit.r
}
}
if(progressbar) setTxtProgressBar(pb, s)
}
if(progressbar) close(pb)
return(list(wL = wL, wR = wR, b.left = left, b.right = right, GAMobject = modelfit))
}
|
"orient.pdb" <-
function (pdb, atom.subset = NULL, verbose = TRUE ) {
if (missing(pdb)) {
stop("pdb.orient: must supply 'pdb' object, e.g. from 'read.pdb'")
}
if(is.list(pdb)) { xyz <- pdb$xyz
} else {
if (!is.vector(pdb)) {
stop("pdb.orient: input 'pdb' should NOT be a matrix")
}
xyz <- pdb
}
xyz <- matrix( xyz, ncol=3, byrow=TRUE )
if (is.null(atom.subset)) atom.subset <- c(1:nrow(xyz))
if (length(atom.subset) > nrow(xyz)) {
stop("pdb.orient: there are more 'atom.subset' inds than there atoms")
}
xyz.bar <- apply(xyz[atom.subset, ], 2, mean)
xyz <- sweep(xyz, 2, xyz.bar)
S <- var(xyz[atom.subset, ])
prj <- eigen(S, symmetric = TRUE)
A <- prj$vectors
b <- A[,1]; c <- A[,2]
A[1,3] <- (b[2] * c[3]) - (b[3] * c[2])
A[2,3] <- (b[3] * c[1]) - (b[1] * c[3])
A[3,3] <- (b[1] * c[2]) - (b[2] * c[1])
z <- xyz %*% (A)
if (verbose) {
cat("Dimensions:", "\n")
cat(" x min=", round(min(z[, 1]), 3),
" max=", round(max(z[, 1]), 3),
" range=", round(max(z[, 1]) - min(z[, 1]), 3), "\n")
cat(" y min=", round(min(z[, 2]), 3),
" max=", round(max(z[, 2]), 3),
" range=", round(max(z[, 2]) - min(z[, 2]), 3), "\n")
cat(" z min=", round(min(z[, 3]), 3),
" max=", round(max(z[, 3]), 3),
" range=", round(max(z[, 3]) - min(z[, 3]), 3), "\n")
}
z <- round(as.vector(t(z)),3)
z <- as.xyz(z)
invisible(z)
}
|
create_git_log_file <- function(
username = c("Dean Attali", "daattali"),
repos = c("daattali/beautiful-jekyll",
"daattali/shinyjs",
"daattali/timevis",
"jennybc/bingo"),
dir ="git_repos_vis",
logfile = "project-logs.csv") {
if (!requireNamespace("git2r", quietly = TRUE)) {
stop("You need to install the 'git2r' package", call. = FALSE)
}
if (!dir.exists(dir)) {
dir.create(dir, recursive = TRUE, showWarnings = FALSE)
}
dir <- normalizePath(dir)
logs <- lapply(repos, function(repo) {
if (!grepl("/", repo)) {
stop(repo, " is not a valid repo name (you forgot to specify the user)", call. = FALSE)
}
repo_name <- sub(".*/(.*)", replacement = "\\1", repo)
repo_dir <- file.path(dir, repo_name)
if (dir.exists(repo_dir)) {
message("Note: Not cloning ", repo, " because a folder with that name already exists")
} else {
message("Cloning ", repo)
repo_url <- paste0("https://github.com/", repo)
git2r::clone(url = repo_url, local_path = repo_dir,
progress = FALSE)
}
repo <- git2r::repository(repo_dir)
commits <- git2r::commits(repo)
dates <- unlist(lapply(commits, function(commit) {
if (commit$author$name %in% username) {
as.character(as.POSIXlt(commit$author$when$time, origin = "1970-01-01"))
} else {
NULL
}
}))
data.frame(project = rep(repo_name, length(dates)),
timestamp = dates,
stringsAsFactors = FALSE)
})
logs <- do.call(rbind, logs)
logfile <- file.path(dir, logfile)
write.csv(logs, logfile, quote = FALSE, row.names = FALSE)
if (file.exists(logfile)) {
message("Created logfile at ", normalizePath(logfile))
} else {
stop("The git log file could not get creatd for some reason", call. = FALSE)
}
return(logfile)
}
create_git_log_file(
username = c("Dean Attali", "daattali"),
repos = c("daattali/addinslist", "daattali/beautiful-jekyll", "jennybc/bingo", "daattali/colourpicker", "daattali/daattali.github.io", "daattali/ddpcr","daattali/ggExtra", "daattali/lightsout", "daattali/rsalad", "daattali/shinyjs", "daattali/statsTerrorismProject", "daattali/timevis", "daattali/shinyforms", "daattali/advanced-shiny", "daattali/shinyalert"),
logfile = "dean-projects.csv"
)
create_git_log_file(
username = c("Hadley Wickham", "hadley"),
repos = c("tidyverse/forcats", "r-lib/pkgdown", "tidyverse/haven", "hadley/adv-r", "tidyverse/purrr", "tidyverse/dplyr", "tidyverse/dbplyr","tidyverse/tidyr", "tidyverse/ggplot2", "tidyverse/stringr", "r-lib/fs", "r-lib/testthat", "r-lib/usethis", "r-lib/devtools", "rstudio/ggvis", "r-lib/httr", "tidyverse/tibble","hadley/lazyeval", "hadley/multidplyr", "tidyverse/readr", "hadley/plyr", "hadley/rvest", "r-lib/xml2"),
logfile = "hadley-projects.csv"
)
create_git_log_file(
username = c("Jenny Bryan", "jennybc"),
repos = c("jennybc/bingo", "rsheets/cellranger", "r-lib/devtools", "jennybc/gapminder", "jennybc/githug", "jennybc/googlesheets", "jennybc/jadd", "rsheets/jailbreakr", "rsheets/linen", "jennybc/r-graph-catalog", "rsheets/rexcel", "tidyverse/reprex", "r-lib/usethis", "tidyverse/googledrive"),
logfile = "jenny-projects.csv"
)
create_git_log_file(
username = c("Yihui Xie", "yihui"),
repos = c("rstudio/leaflet", "rstudio/bookdown", "yihui/formatR", "yihui/knitr", "yihui/knitr-examples", "yihui/r-ninja", "rstudio/rmarkdown", "rstudio/shiny", "rstudio/DT", "yihui/servr", "rstudio/bookdown"),
logfile = "yihui-projects.csv"
)
create_git_log_file(
username = c("Jim Hester", "jimhester"),
repos = c("r-lib/devtools", "r-lib/fs", "r-lib/covr", "tidyverse/glue", "jimhester/lintr", "jimhester/gmailr", "r-lib/xml2", "r-dbi/odbc", "tidyverse/readr", "jimhester/knitrBootstrap", "travis-ci/travis-build"),
logfile = "jim-projects.csv"
)
|
signature_xpath <- paste(
"(*|descendant-or-self::exprlist/*)[LEFT_ASSIGN/preceding-sibling::expr[count(*)=1]/SYMBOL[text() = '{token_quote}' and @line1 <= {row}]]/expr[FUNCTION|OP-LAMBDA]",
"(*|descendant-or-self::exprlist/*)[EQ_ASSIGN/preceding-sibling::expr[count(*)=1]/SYMBOL[text() = '{token_quote}' and @line1 <= {row}]]/expr[FUNCTION|OP-LAMBDA]",
sep = "|")
signature_reply <- function(id, uri, workspace, document, point) {
if (!check_scope(uri, document, point)) {
return(Response$new(id, list(signatures = NULL)))
}
result <- document$detect_call(point)
SignatureInformation <- list()
activeSignature <- -1
sig <- NULL
if (nzchar(result$token)) {
xdoc <- workspace$get_parse_data(uri)$xml_doc
if (result$accessor == "" && !is.null(xdoc)) {
row <- point$row + 1
col <- point$col + 1
enclosing_scopes <- xdoc_find_enclosing_scopes(xdoc,
row, col, top = TRUE)
xpath <- glue(signature_xpath, row = row,
token_quote = xml_single_quote(result$token))
all_defs <- xml_find_all(enclosing_scopes, xpath)
if (length(all_defs)) {
last_def <- all_defs[[length(all_defs)]]
func_line1 <- as.integer(xml_attr(last_def, "line1"))
func_col1 <- as.integer(xml_attr(last_def, "col1"))
func_line2 <- as.integer(xml_attr(last_def, "line2"))
func_col2 <- as.integer(xml_attr(last_def, "col2"))
func_text <- get_range_text(document$content,
line1 = func_line1,
col1 = func_col1,
line2 = func_line2,
col2 = func_col2
)
func_expr <- parse(text = func_text, keep.source = FALSE)
sig <- get_signature(result$token, func_expr[[1]])
documentation <- ""
doc_line1 <- detect_comments(document$content, func_line1 - 1) + 1
if (doc_line1 < func_line1) {
comment <- document$content[doc_line1:(func_line1 - 1)]
doc <- convert_comment_to_documentation(comment)
doc_string <- NULL
if (is.character(doc)) {
doc_string <- doc
} else if (is.list(doc)) {
if (is.null(doc$markdown)) {
doc_string <- doc$description
} else {
doc_string <- doc$markdown
}
}
if (is.null(doc_string)) {
doc_string <- ""
}
documentation <- list(kind = "markdown", value = doc_string)
}
SignatureInformation <- list(list(
label = sig,
documentation = documentation
))
activeSignature <- 0
}
}
if (is.null(sig)) {
sig <- workspace$get_signature(result$token, result$package,
exported_only = result$accessor != ":::")
logger$info("sig: ", sig)
if (!is.null(sig)) {
doc <- workspace$get_documentation(result$token, result$package, isf = TRUE)
doc_string <- NULL
if (is.character(doc)) {
doc_string <- doc
} else if (is.list(doc)) {
doc_string <- doc$description
}
if (is.null(doc_string)) {
doc_string <- ""
}
documentation <- list(kind = "markdown", value = doc_string)
SignatureInformation <- list(list(
label = sig,
documentation = documentation
))
activeSignature <- 0
}
}
}
Response$new(
id,
result = list(
signatures = SignatureInformation,
activeSignature = activeSignature
)
)
}
|
safetruncate <- function(flatfile, right, left){
sl <- unique(flatfile$Sample.Label)
find <- flatfile$distance <= right &
flatfile$distance >= left
find[is.na(find)] <- TRUE
fsl <- unique(flatfile$Sample.Label[find])
if(length(fsl) != length(sl)){
sl_diff <- setdiff(sl, fsl)
find[flatfile$Sample.Label %in% sl_diff] <- TRUE
flatfile[flatfile$Sample.Label %in% sl_diff, ]$distance <- NA
if(!is.null(flatfile$object)){
flatfile[flatfile$Sample.Label %in% sl_diff, ]$object <- NA
}
if(!is.null(flatfile$size)){
flatfile[flatfile$Sample.Label %in% sl_diff, ]$size <- NA
}
}
flatfile <- flatfile[find, , drop=FALSE]
return(flatfile)
}
|
gnedenko.exp.test<-function(x, R=length(x)/2, simulate.p.value=FALSE, nrepl=2000)
{
DNAME <- deparse(substitute(x))
R<-round(R)
n<-length(x)
x<-sort(x)
x<-c(0,x)
D<-(n:1)*(x[2:(n+1)]-x[1:n])
t<-(sum(D[1:R])/R)/(sum(D[(R+1):n])/(n-R))
l<-0
if(simulate.p.value)
{
for(i in 1:nrepl)
{
z<-rexp(n)
z<-sort(z)
z<-c(0,z)
D<-(n:1)*(z[2:(n+1)]-z[1:n])
T<-(sum(D[1:R])/R)/(sum(D[(R+1):n])/(n-R))
if(abs(T)>abs(t)) l=l+1
}
p.value<-l/nrepl
}
else
{
p.value<-2*min(pf(t,2*R,2*(n-R)),1-pf(t,2*R,2*(n-R)))
}
RVAL<-list(statistic=c(Q=t), p.value=p.value, method="Gnedenko's F-test of exponentiality",data.name = DNAME)
class(RVAL)<-"htest"
return(RVAL)
}
|
HWIlr <-function(X,zeroadj=0.5) {
X[X==0] <- zeroadj
if(is.matrix(X)) {
c1 <- (log(X[,1]/X[,3]))/sqrt(2)
c2 <- (log(X[,1]*X[,3]/(X[,2]^2)))/sqrt(6)
Y <- cbind(c1,c2)
}
if(is.vector(X)) {
c1 <- (log(X[1]/X[3]))/sqrt(2)
c2 <- (log(X[1]*X[3]/(X[2]^2)))/sqrt(6)
Y <- c(c1,c2)
}
return(Y)
}
|
mod_SSPD_ui <- function(id){
ns <- NS(id)
tagList(
sidebarLayout(
sidebarPanel(width = 4,
radioButtons(inputId = ns("owndataSSPD"), label = "Do you have your own data?", choices = c("Yes", "No"), selected = "No",
inline = TRUE, width = NULL, choiceNames = NULL, choiceValues = NULL),
selectInput(inputId = ns("kindSSPD"), label = "Select SSPD Type:",
choices = c("Split-Split Plot in a RCBD" = "SSPD_RCBD", "Split-Split Plot in a CRD" = "SSPD_CRD"),
multiple = FALSE),
conditionalPanel("input.owndataSSPD == 'Yes'", ns = ns,
fluidRow(
column(8, style=list("padding-right: 28px;"),
fileInput(ns("file.SSPD"), label = "Upload a csv File:", multiple = FALSE)),
column(4,style=list("padding-left: 5px;"),
radioButtons(ns("sep.sspd"), "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","))
)
),
conditionalPanel("input.owndataSPD != 'Yes'", ns = ns,
numericInput(ns("mp.sspd"), label = "Whole-plots:",
value = NULL, min = 2),
numericInput(ns("sp.sspd"), label = "Sub-plots Within Whole-plots:",
value = NULL, min = 2),
numericInput(ns("ssp.sspd"), label = "Sub-Sub-plots within Sub-plots:",
value = NULL, min = 2)
),
fluidRow(
column(6, style=list("padding-right: 28px;"),
numericInput(ns("reps.sspd"), label = "Input
value = 2, min = 2)
),
column(6, style=list("padding-left: 5px;"),
numericInput(ns("l.sspd"), label = "Input
value = 1, min = 1)
)
),
fluidRow(
column(6,style=list("padding-right: 28px;"),
textInput(ns("plot_start.sspd"), "Starting Plot Number:", value = 101)
),
column(6,style=list("padding-left: 5px;"),
textInput(ns("Location.sspd"), "Input Location:", value = "FARGO")
)
),
numericInput(inputId = ns("myseed.sspd"), label = "Seed Number:", value = 123, min = 1),
fluidRow(
column(6,
downloadButton(ns("downloadData.sspd"), "Save Experiment!", style = "width:100%")
),
column(6,
actionButton(ns("Simulate.sspd"), "Simulate!", icon = icon("cocktail"), width = '100%')
)
)
),
mainPanel(
width = 8,
tabsetPanel(
tabPanel("Field Book", DT::DTOutput(ns("SSPD.output")))
)
)
)
)
}
mod_SSPD_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
wp <- paste("IRR_", c("NO", "Yes"), sep = "")
sp <- c("NFung", paste("Fung", 1:4, sep = ""))
ssp <- paste("Beans", 1:10, sep = "")
entryListFormat_SSPD <- data.frame(list(WHOLPLOT = c(wp, rep("", 8)),
SUBPLOT = c(sp, rep("", 5)),
SUB_SUBPLOTS = ssp))
entriesInfoModal_SSPD <- function() {
modalDialog(
title = div(tags$h3("Important message", style = "color: red;")),
h4("Please, follow the format shown in the following example. Make sure to upload a CSV file!"),
renderTable(entryListFormat_SSPD,
bordered = TRUE,
align = 'c',
striped = TRUE),
easyClose = FALSE
)
}
toListen <- reactive({
list(input$owndataSSPD)
})
observeEvent(toListen(), {
if (input$owndataSSPD == "Yes") {
showModal(
shinyjqui::jqui_draggable(
entriesInfoModal_SSPD()
)
)
}
})
getData.sspd <- reactive({
req(input$file.SSPD)
inFile <- input$file.SSPD
dataUp.sspd <- load_file(name = inFile$name, path = inFile$datapat, sep = input$sep.sspd)
return(list(dataUp.sspd = dataUp.sspd))
})
sspd_reactive <- reactive({
req(input$plot_start.sspd)
req(input$Location.sspd)
req(input$myseed.sspd)
req(input$l.sspd)
l.sspd <- as.numeric(input$l.sspd)
seed.sspd <- as.numeric(input$myseed.sspd)
plot_start.sspd <- as.vector(unlist(strsplit(input$plot_start.sspd, ",")))
plot_start.sspd <- as.numeric(plot_start.sspd)
loc.sspd <- as.vector(unlist(strsplit(input$Location.sspd, ",")))
req(input$reps.sspd)
reps.sspd <- as.numeric(input$reps.sspd)
if (input$kindSSPD == "SSPD_RCBD") {
if (input$owndataSSPD == "Yes") {
wp.sspd <- NULL
sp.sspd <- NULL
ssp.sspd <- NULL
data.sspd <- getData.sspd()$dataUp.sspd
}else {
req(input$mp.sspd, input$sp.sspd)
req(input$ssp.sspd)
wp.sspd <- as.numeric(input$mp.sspd)
sp.sspd <- as.numeric(input$sp.sspd)
ssp.sspd <- as.numeric(input$ssp.sspd)
data.sspd <- NULL
}
type <- 2
}else {
if (input$owndataSSPD == "Yes") {
wp.sspd <- NULL
sp.sspd <- NULL
ssp.sspd <- NULL
data.sspd <- getData.sspd()$dataUp.sspdd
}else {
req(input$mp.sspd, input$sp.sspd)
req(input$ssp.sspd)
wp.sspd <- as.numeric(input$mp.sspd)
sp.sspd <- as.numeric(input$sp.sspd)
ssp.sspd <- as.numeric(input$ssp.sspd)
data.sspd <- NULL
}
type <- 1
}
SSPD <- split_split_plot(wp = wp.sspd, sp = sp.sspd, ssp = ssp.sspd, reps = reps.sspd, l = l.sspd,
plotNumber = plot_start.sspd, seed = seed.sspd, type = type,
locationNames = loc.sspd, data = data.sspd)
})
valsspd <- reactiveValues(maxV.sspd = NULL, minV.sspd = NULL, Trial.sspd = NULL)
simuModal.sspd <- function(failed = FALSE) {
modalDialog(
selectInput(inputId = ns("TrialsRowCol"), label = "Select One:", choices = c("YIELD", "MOISTURE", "HEIGHT", "Other")),
conditionalPanel("input.TrialsRowCol == 'Other'", ns = ns,
textInput(inputId = ns("Otherspd"), label = "Input Trial Name:", value = NULL)
),
fluidRow(
column(6,
numericInput(ns("min.sspd"), "Input the min value", value = NULL)
),
column(6,
numericInput(ns("max.sspd"), "Input the max value", value = NULL)
)
),
if (failed)
div(tags$b("Invalid input of data max and min", style = "color: red;")),
footer = tagList(
modalButton("Cancel"),
actionButton(ns("ok.sspd"), "GO")
)
)
}
observeEvent(input$Simulate.sspd, {
req(sspd_reactive()$fieldBook)
showModal(
shinyjqui::jqui_draggable(
simuModal.sspd()
)
)
})
observeEvent(input$ok.sspd, {
req(input$max.sspd, input$min.sspd)
if (input$max.sspd > input$min.sspd && input$min.sspd != input$max.sspd) {
valsspd$maxV.sspd <- input$max.sspd
valsspd$minV.sspd <- input$min.sspd
if(input$TrialsRowCol == "Other") {
req(input$Otherspd)
if(!is.null(input$Otherspd)) {
valsspd$Trial.sspd <- input$Otherspd
}else showModal(simuModal.sspd(failed = TRUE))
}else {
valsspd$Trial.sspd <- as.character(input$TrialsRowCol)
}
removeModal()
}else {
showModal(
shinyjqui::jqui_draggable(
simuModal.sspd(failed = TRUE)
)
)
}
})
simuData_sspd <- reactive({
req(sspd_reactive()$fieldBook)
if(!is.null(valsspd$maxV.sspd) && !is.null(valsspd$minV.sspd) && !is.null(valsspd$Trial.sspd)) {
max <- as.numeric(valsspd$maxV.sspd)
min <- as.numeric(valsspd$minV.sspd)
df.sspd <- sspd_reactive()$fieldBook
cnamesdf.sspd <- colnames(df.sspd)
df.sspd <- norm_trunc(a = min, b = max, data = df.sspd)
colnames(df.sspd) <- c(cnamesdf.sspd[1:(ncol(df.sspd) - 1)], valsspd$Trial.sspd)
df.sspd <- df.sspd[order(df.sspd$ID),]
}else {
df.sspd <- sspd_reactive()$fieldBook
}
return(list(df = df.sspd, a = a))
})
output$SSPD.output <- DT::renderDataTable({
df <- simuData_sspd()$df
options(DT.options = list(pageLength = nrow(df), autoWidth = FALSE,
scrollX = TRUE, scrollY = "500px"))
DT::datatable(df, rownames = FALSE, options = list(
columnDefs = list(list(className = 'dt-center', targets = "_all"))))
})
output$downloadData.sspd <- downloadHandler(
filename = function() {
loc <- paste("Split-Split-Plot_", sep = "")
paste(loc, Sys.Date(), ".csv", sep = "")
},
content = function(file) {
df <- as.data.frame(simuData_sspd()$df)
write.csv(df, file, row.names = FALSE)
}
)
})
}
|
context("Workspace")
source("utils.R")
subscription_id <- Sys.getenv("TEST_SUBSCRIPTION_ID")
resource_group <- Sys.getenv("TEST_RESOURCE_GROUP")
location <- Sys.getenv("TEST_LOCATION")
test_that("create, get, save, load and delete workspace", {
skip('skip')
workspace_name <- paste0("test_ws", build_num)
existing_ws <- create_workspace(workspace_name,
subscription_id = subscription_id,
resource_group = resource_group,
location = location)
ws <- get_workspace(workspace_name,
subscription_id = subscription_id,
resource_group = resource_group)
expect_equal(ws$name, existing_ws$name)
get_workspace_details(ws)
kv <- get_default_keyvault(ws)
expect_equal(length(kv$list_secrets()), 0)
write_workspace_config(existing_ws)
loaded_ws <- load_workspace_from_config(".")
expect_equal(loaded_ws$name, workspace_name)
delete_workspace(existing_ws)
ws <- get_workspace("random", subscription_id = subscription_id)
expect_equal(ws, NULL)
})
|
if (requiet("testthat") && requiet("insight") && requiet("lme4")) {
data(mtcars)
data(sleepstudy)
data(iris)
m1 <- lm(mpg ~ 0 + gear, data = mtcars)
m2 <- lm(mpg ~ gear, data = mtcars)
m3 <- suppressWarnings(lmer(Reaction ~ 0 + Days + (Days | Subject), data = sleepstudy))
m4 <- lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy)
m5 <- suppressWarnings(lmer(Reaction ~ 0 + (Days | Subject), data = sleepstudy))
m6 <- lm(Sepal.Length ~ 0 + Petal.Width + Species, data = iris)
m7 <- lm(Sepal.Length ~ -1 + Petal.Width + Species, data = iris)
m8 <- lm(Sepal.Length ~ Petal.Width + Species, data = iris)
m9 <- lm(Sepal.Length ~ Petal.Width + Species + 1, data = iris)
test_that("has_intercept", {
expect_true(has_intercept(m2))
expect_false(has_intercept(m1))
expect_true(has_intercept(m4))
expect_false(has_intercept(m3))
expect_false(has_intercept(m5))
expect_false(has_intercept(m6))
expect_false(has_intercept(m7))
expect_true(has_intercept(m8))
expect_true(has_intercept(m9))
})
}
|
plot.gconsensus <- function(x, ...) {
display.order <- getOption("display.order")
display.shownames <- getOption("display.shownames")
display.orientation <- getOption("display.orientation")
display.length.out <- getOption("display.length.out")
display.tab.size <- getOption("display.tab.size")
display.signif.digits <- getOption("display.signif.digits")
if (is.null(display.order)) display.order <- "location"
if (is.null(display.shownames)) display.shownames <- FALSE
if (is.null(display.orientation)) display.orientation <- "horizontal"
if (is.null(display.length.out)) display.length.out <- 101
if (is.null(display.tab.size)) display.tab.size <- 12
if (is.null(display.signif.digits)) display.signif.digits <- 2
mss <- rep(TRUE, length(x$ilab$data$mean))
n <- length(x$ilab$data$mean[mss])
subset <- x$ilab$data$included[mss] == 1
if (display.order == "location") {
os <- order(x$ilab$data$mean[mss])
} else if (display.order == "dispersion") {
os <- order(x$ilab$data$sd[mss])
} else {
os <- order(x$ilab$data$participant[mss])
}
if (display.shownames) {
xlab <- x$ilab$data$participant[mss]
} else {
xlab <- x$ilab$data$code[mss]
}
my.pch <- x$ilab$data$symbol[mss]
my.color <- x$ilab$data$symbol.fillcolor[mss]
p <- length(x$ilab$data$mean[mss])
ss <- x$ilab$data$included[mss] == 1
mm <- sum(ss)
k <- 2
if (x$config$expansion.factor.type == "naive") {
k <- 2
} else {
if (x$config$expansion.factor.type == "large sample") {
k <- qnorm(1 - x$config$alpha / 2)
} else {
k <- qt(1 - x$config$alpha / 2, mm - 1)
}
}
tau2 <- 0
if (x$method == "DL1" | x$method == "DL2" | x$method == "PM" |
x$method == "MPM") {
tau2 <- x$sb2
} else if (x$method == "VRMLE" | x$method == "MCM.median" |
x$method == "HB" | x$method == "MPM.LP") {
tau2 <- x$var.b
} else {
tau2 <- 0
}
sxlab <- c(xlab)
for (i in 1:p) if (!subset[i]) {
sxlab[i] <- paste0("<", xlab[i], ">")
} else sxlab[i] <- paste(xlab[i])
wlim <- c(0, p+3)
zlim <- range(c(x$ilab$data$mean - x$ilab$data$k * sqrt(x$ilab$data$sd^2 + (x$fit$tau)^2),
x$fit$value - x$fit$U),
c(x$ilab$data$mean + x$ilab$data$k * sqrt(x$ilab$data$sd^2 + (x$fit$tau)^2),
x$fit$value + x$fit$U),
na.rm = TRUE)
wlab <- ""
zlab <- x$ilab$info$value[x$ilab$info$variable == "Units"]
if (display.orientation == "horizontal") {
xx <- c(1:p)
yy <- x$ilab$data$mean[mss][os]
xlim <- wlim
ylim <- zlim
xlab <- wlab
ylab <- zlab
xaxis <- 1
yaxis <- 2
x.separator <- c(p+1, p+1)
y.separator <- c(-1, 1)*10*max(abs(x$ilab$data$mean), na.rm = TRUE)
} else {
xx <- x$ilab$data$mean[mss][os]
yy <- c(1:p)
xlim <- zlim
ylim <- wlim
xlab <- zlab
ylab <- wlab
xaxis <- 2
yaxis <- 1
x.separator <- c(-1, 1)*10*max(abs(x$ilab$data$mean), na.rm = TRUE)
y.separator <- c(p+1, p+1)
}
plot(xx, yy,
xlim = xlim,
ylim = ylim,
axes = FALSE,
xlab = xlab,
ylab = ylab,
main = paste0(x$study, " - ", x$measurand),
cex = 1.5,
pch = 20,
...
)
axis(yaxis)
axis(xaxis, at = 1:p, labels = sxlab[os], las = 2)
for (i in 1:p) if (!subset[os][i]) {
axis(xaxis, at = i, labels = sxlab[os][i], las = 2, col.axis = 2)
}
box()
lines(x.separator, y.separator)
xx.pdf <- seq(min(zlim), max(zlim), length.out = display.length.out)
yy.mat <- matrix(NA, display.length.out, p)
for (i in (c(1:p)[ss]))
yy.mat[,i] <- dnorm(xx.pdf, x$ilab$data$mean[i], x$ilab$data$sd[i])
yy.pdf <- apply(yy.mat, 1, mean, na.rm = TRUE)
mu.pdf <- sum(xx.pdf * yy.pdf) / sum(yy.pdf)
u.pdf <- sqrt(sum((xx.pdf - mu.pdf) ^ 2 * yy.pdf)/sum(yy.pdf))
yy.eq <- dnorm(xx.pdf, x$fit$value, x$fit$U*sqrt(p)/x$fit$k)
if (display.orientation == "horizontal") {
tcol<- rgb(118, 238, 0, maxColorValue = 255, alpha=127)
polygon(c(1, p, p, 1, 1), x$fit$value+c(-1, -1, 1, 1, -1)*x$fit$U,
border = NA, col = tcol)
lines(c(0, p+1), rep(x$fit$value, 2), col = "darkgreen")
lines(p + 1 + 2*yy.pdf/max(c(yy.eq,yy.pdf)), xx.pdf, lwd = 2)
lines(p + 1 + 2*yy.eq/max(c(yy.eq,yy.pdf)), xx.pdf, lwd = 2, col = 4)
for (i in 1:p) {
lines(rep(i, 2),
x$ilab$data$mean[mss][os][i] +
c(-1,1) * x$ilab$data$k[mss][os][i] *
x$ilab$data$sd[mss][os][i],
lwd = 3, col = 4)
lines(rep(i, 2),
x$ilab$data$mean[mss][os][i] +
c(-1,1) * x$ilab$data$k[mss][os][i] *
sqrt(x$ilab$data$sd[mss][os][i] ^ 2 + x$fit$tau^2),
lwd = 1, col = 4)
}
} else {
for (i in 1:p) {
lines(x$ilab$data$mean[os][i] + c(-1,1) * x$ilab$data$k[os][i] *
x$ilab$data$sd[os][i], rep(i, 2),
lwd = 3, col = 4)
lines(x$ilab$data$mean[os][i] + c(-1,1) * x$ilab$data$k[os][i] *
sqrt(x$ilab$data$sd[os][i] ^ 2 + x$fit$tau^2), rep(i, 2),
lwd = 1, col = 4)
}
tcol<- rgb(118, 238, 0, maxColorValue = 255, alpha=127)
polygon(x$fit$value+c(-1, -1, 1, 1, -1)*x$fit$U, c(1, p, p, 1, 1),
border = NA, col = tcol)
lines(rep(x$fit$value, 2), c(1, p), col = "darkgreen")
lines(xx.pdf, p + 1 + 2*yy.pdf/max(c(yy.eq,yy.pdf)), lwd = 2)
lines(xx.pdf, p + 1 + 2*yy.eq/max(c(yy.eq,yy.pdf)), lwd = 2, col = 4)
}
points(xx, yy, pch = 20, cex = 1, col = 2 )
}
|
context("Scenario of un wanted inputs")
test_that("NA values are avoided",{
expect_that(mazTRI(NA,0.1),
throws_error("NA or Infinite or NAN values in the Input"))
})
test_that("Infinite values are avoided",{
expect_that(mazTRI(Inf,0.1),
throws_error("NA or Infinite or NAN values in the Input"))
})
test_that("NAN values are avoided",{
expect_that(mazTRI(NaN,0.1),
throws_error("NA or Infinite or NAN values in the Input"))
})
context("Scenario of mode")
test_that("Mode out of range",{
expect_that(mazTRI(1,5),
throws_error("Mode cannot be less than zero or greater than one"))
})
test_that("Mode out of range",{
expect_that(mazTRI(1,-5),
throws_error("Mode cannot be less than zero or greater than one"))
})
context("Moments issues")
test_that("Moments being negative or zero",{
expect_that(mazTRI(-3,0.3),
throws_error("Moments cannot be less than or equal to zero"))
})
|
if (identical(Sys.getenv("NOT_CRAN"), "true")) {
ascot_vale <- search_stops("Ascot Vale")
test_that("search_stops result has class \"ptvapi\"", {
expect_s3_class(ascot_vale, "ptvapi")
})
test_that("results in search_stops can relate to stop name alone", {
expect_gte(
nrow(
dplyr::filter(
ascot_vale,
grepl("Ascot Vale", stop_name, ignore.case = TRUE),
!grepl("Ascot Vale", stop_suburb, ignore.case = TRUE)
)
),
1
)
})
test_that("results in search_stops can relate to stop suburb alone", {
expect_gte(
nrow(
dplyr::filter(
ascot_vale,
!grepl("Ascot Vale", stop_name, ignore.case = TRUE),
grepl("Ascot Vale", stop_suburb, ignore.case = TRUE)
)
),
1
)
})
test_that("all results in search_stops relate to search term somehow", {
expect_equal(
nrow(
dplyr::filter(
ascot_vale,
!grepl("Ascot Vale", stop_name
, ignore.case = TRUE),
!grepl("Ascot Vale", stop_suburb, ignore.case = TRUE)
)
),
0
)
})
test_that("search_stops can be filtered with multiple route types", {
expect_equal(
search_stops("South Yarra", route_types = c(0, 1)) %>%
pull(route_type) %>%
unique %>%
sort,
c(0, 1)
)
expect_equal(
search_stops("South Yarra", route_types = c(0, 2)) %>%
pull(route_type) %>%
unique %>%
sort,
c(0, 2)
)
})
}
|
dens <- function(dist){
fun <- get(paste0("d", dist))
return(fun)
}
quant <- function(dist){
fun <- get(paste0("q", dist))
return(fun)
}
p <- function(dist){
fun <- get(paste0("p", dist))
return(fun)
}
rand <- function(dist){
fun <- get(paste0("r", dist))
return(fun)
}
slope <- function(rho, costs=matrix(c(0,0,1,(1-rho)/rho), 2, 2, byrow=TRUE)){
c.t.pos <- costs[1, 1]
c.t.neg <- costs[1, 2]
c.f.pos <- costs[2, 1]
c.f.neg <- costs[2, 2]
beta <- ((1 - rho)/rho) * ((c.t.neg - c.f.pos)/(c.t.pos - c.f.neg))
return(beta)
}
sqroot <- function(k1, k2, rho, costs){
ctrl <- (mean(k2) - mean(k1))^2 + 2*log((sd(k2)/sd(k1))*slope(rho,costs))*(var(k2) - var(k1))
return(ctrl)
}
DensRatio2 <- function(p, dist1, dist2, par1.1, par1.2, par2.1, par2.2, rho, costs) {
ratio <- (dens(dist2)(p,par2.1,par2.2)/dens(dist1)(p,par1.1,par1.2)) - slope(rho,costs)
return(ratio)
}
thresTH2 <- function(dist1, dist2, par1.1, par1.2, par2.1, par2.2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), R=NULL, q1=0.05, q2=0.95, tol=10^(-8)){
if (!(rho > 0 & rho < 1)){
stop("The disease prevalence rho must be a number in (0,1)")
}
if (is.null(costs) & is.null(R)){
stop("Both 'costs' and 'R' are NULL. Please specify one of them.")
}else if (!is.null(costs) & !is.null(R)){
stop("Either 'costs' or 'R' must be NULL")
}else if (is.null(costs) & !is.null(R)){
if (!is.numeric(R) | length(R)!=1){
stop("R must be a single number")
}
costs <- matrix(c(0, 0, 1, (1-rho)/(R*rho)), 2, 2, byrow=TRUE)
}else if (!is.null(costs) & is.null(R)){
if (!is.matrix(costs)){
stop("'costs' must be a matrix")
}
if (dim(costs)[1] != 2 | dim(costs)[2] != 2){
stop("'costs' must be a 2x2 matrix")
}
}
costs.origin <- costs
rho.origin <- rho
median1 <- quant(dist1)(0.5, par1.1, par1.2)
median2 <- quant(dist2)(0.5, par2.1, par2.2)
if(median1 > median2){
rho <- 1-rho
costs <- costs[, 2:1]
g <- par2.1; par2.1 <- par1.1; par1.1 <- g
f <- par2.2; par2.2 <- par1.2; par1.2 <- f
auxdist <- dist2; dist2 <- dist1; dist1 <- auxdist
}
p1 <- quant(dist1)(q1, par1.1, par1.2)
p2 <- quant(dist2)(q2, par2.1, par2.2)
cut.t <- uniroot(DensRatio2,c(p1,p2),tol=tol,dist1,dist2,par1.1,par1.2,par2.1,par2.2,rho,costs,extendInt="yes")$root
beta <- slope(rho, costs)
if (dist1=="norm" & dist2=="norm" & par1.2!=par2.2){
LL <- par1.2/par2.2*exp(-(par2.1-par1.1)^2/(2*par2.2^2))
UL <- par1.2/par2.2*exp((par2.1-par1.1)^2/(2*par1.2^2))
if (!(LL<=beta & beta<=UL)) warning("The choice of costs/R leads to a cut-off that is not between the means of the two distributions")
}
re <- list(thres=cut.t, prev=rho.origin, costs=costs.origin, R=beta, method="theoretical")
class(re) <- "thresTH2"
return(re)
}
print.thresTH2 <- function(x, ...){
cat("\nThreshold:", x$thres)
cat("\n")
cat("\nParameters used")
cat("\n Disease prevalence:", x$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$costs)
cat("\n R:", x$R)
cat("\n")
}
secondDer2 <- function(x){
if (class(x) != "thres2"){
stop("'x' must be of class 'thres2'")
}
if (x$T$method=="empirical"){
stop("'x' has been computed with method='empirical', cannot compute the second derivative of the cost function")
}else if (x$T$method=="equal" | x$T$method=="unequal"){
k1 <- x$T$k1
k2 <- x$T$k2
rho <- x$T$prev
costs <- x$T$costs
Thr <- x$T$thres
par1.1 <- mean(k1)
par2.1 <- mean(k2)
par1.2 <- sd(k1)
par2.2 <- sd(k2)
n1 <- length(k1)
n2 <- length(k2)
beta <- slope(rho,costs)
de <- (n1+n2)*rho*(costs[1,1]-costs[2,2])
der <- de/sqrt(2*pi)*(((Thr-par2.1)/par2.2^3)*exp(-(Thr-par2.1)^2/(2*par2.2^2))-beta*((Thr-par1.1)/par1.2^3)*exp(-(Thr-par1.1)^2/(2*par1.2^2)))
}else if (x$T$method=="parametric"){
dist1 <- x$T$dist1
dist2 <- x$T$dist2
pars1 <- x$T$pars1
pars2 <- x$T$pars2
densratio <- function(y){
DR <- dens(dist2)(y, pars2[1], pars2[2])/dens(dist1)(y, pars1[1], pars1[2])-x$T$R
return(DR)
}
der <- grad(densratio, x$T$thres)
}
return(der)
}
varPooled <- function(k1, k2){
n1 <- length(k1)
n2 <- length(k2)
pool <- ((n1 - 1)*var(k1) + (n2 - 1)*var(k2))/(n1 + n2 - 2)
return(pool)
}
thresEq2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE)){
costs.origin <- costs
k1.origin <- k1
k2.origin <- k2
rho.origin <- rho
if(mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
beta <- slope(rho, costs)
cut <- (2*varPooled(k1,k2)*log(beta) - (mean(k1)^2 - mean(k2)^2))/(2*(mean(k2) - mean(k1)))
re <- list(thres=cut, prev=rho.origin, costs=costs.origin, R=beta, method="equal", k1=k1.origin, k2=k2.origin)
return(re)
}
thresUn2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE)){
costs.origin <- costs
k1.origin <- k1
k2.origin <- k2
rho.origin <- rho
if(mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
ctrl <- sqroot(k1, k2, rho, costs)
if (ctrl>=0){
cut <- (var(k2)*mean(k1) - var(k1)*mean(k2) + sd(k1)*sd(k2)*sqrt(ctrl))/(var(k2) - var(k1))}
else{
cut <- NA
warning("Negative discriminant; cannot solve the second-degree equation")
}
beta <- slope(rho, costs)
LL <- sd(k1)/sd(k2)*exp(-(mean(k2)-mean(k1))^2/(2*sd(k2)^2))
UL <- sd(k1)/sd(k2)*exp((mean(k2)-mean(k1))^2/(2*sd(k1)^2))
if (!(LL<=beta & beta<=UL)) warning("The choice of costs/R leads to a cut-off that is not between the means of the two distributions")
re <- list(thres=cut, prev=rho.origin, costs=costs.origin, R=beta, method="unequal", k1=k1.origin, k2=k2.origin)
return(re)
}
thresEmp2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), extra.info=FALSE){
k1.origin <- k1
k2.origin <- k2
rho.origin <- rho
costs.origin <- costs
if (mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
c.t.pos <- costs[1,1]
c.t.neg <- costs[1,2]
c.f.pos <- costs[2,1]
c.f.neg <- costs[2,2]
n1 <- length(k1)
n2 <- length(k2)
n <- n1+n2
v <- c(k1, k2)
ind.origin <- c(rep(0, n1), rep(1, n2))
vi <- cbind(v, ind.origin)
ord.v <- vi[order(vi[, 1], vi[, 2]), ]
sens <- rep(NA, n)
spec <- rep(NA, n)
for (j in 1:n){
cut <- ord.v[j, 1]
sens[j] <- sum(ord.v[, 1]>=cut & ord.v[, 2]==1)/n2
spec[j] <- sum(ord.v[, 1]<cut & ord.v[, 2]==0)/n1
}
D <- n*rho*(c.t.pos-c.f.neg)
R <- ((1-rho)/rho)*((c.t.neg-c.f.pos)/(c.t.pos-c.f.neg))
G <- (rho*c.f.neg+(1-rho)*c.f.pos)/(rho*(c.t.pos-c.f.neg))
cost.non.par <- D*(sens+spec*R+G)
total <- data.frame(ord.v, cost.non.par, sens, spec)
ind.min.cost <- which(total[, "cost.non.par"]==min(total[, "cost.non.par"]))
sens.min <- total[ind.min.cost, "sens"]
spec.min <- total[ind.min.cost, "spec"]
cut.min <- total[ind.min.cost, "v"]
cost.min <- total[ind.min.cost, "cost.non.par"]
howmany <- length(cut.min)
if (howmany>1){
interval <- subset(total, v >= cut.min[1] & v <= cut.min[length(cut.min)])
cut.min <- mean(interval$v)
sens.min <- sum(ord.v[, 1]>=cut.min & ord.v[, 2]==1)/n2
spec.min <- sum(ord.v[, 1]<cut.min & ord.v[, 2]==0)/n1
cost.min <- D*(sens.min+spec.min*R+G)
warning(paste(howmany, "observations lead to the minimum cost. The mean of the values between them is returned as threshold."), call.=FALSE)
}
beta <- slope(rho, costs)
re <- list(thres=cut.min, prev=rho.origin, costs=costs.origin, R=beta, method="empirical", k1=k1.origin, k2=k2.origin, sens=sens.min, spec=spec.min, cost=cost.min)
if (extra.info){
re$tot.thres <- total[, "v"]
re$tot.cost <- total[, "cost.non.par"]
re$tot.spec <- spec
re$tot.sens <- sens
}
return(re)
}
thresSmooth2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), extra.info=FALSE){
k1.origin <- k1
k2.origin <- k2
rho.origin <- rho
costs.origin <- costs
if (mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
c.t.pos <- costs[1,1]
c.t.neg <- costs[1,2]
c.f.pos <- costs[2,1]
c.f.neg <- costs[2,2]
dk1 <- kde(k1)
dk2 <- kde(k2)
lmin <- mean(k1)
lmax <- mean(k2)
beta <- slope(rho, costs)
fx <- function(x) predict(dk2, x=x)-beta*predict(dk1, x=x)
out <- uniroot(fx, c(lmin, lmax))
re <- list(thres=out$root, prev=rho.origin, costs=costs.origin, R=beta, method="smooth", k1=k1.origin, k2=k2.origin)
return(re)
}
print.thres2 <- function(x, ...){
if (x$T$method == "parametric"){
cat("\nEstimate:")
cat("\n Threshold: ", x$T$thres)
if (!is.null(x$CI)){
cat("\n")
cat("\nConfidence intervals (parametric bootstrap):")
cat("\n CI based on normal distribution:", x$CI$low.norm, " - ", x$CI$up.norm)
cat("\n CI based on percentiles:", x$CI$low.perc, " - ", x$CI$up.perc)
cat("\n Bootstrap resamples:", x$CI$B)
}
cat("\n")
cat("\nParameters used:")
cat("\n Disease prevalence:", x$T$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$T$costs)
cat("\n R:", x$T$R)
if (!is.null(x$CI)){
cat("\n Significance Level: ", x$CI$alpha)
}
cat("\n Method:", x$T$method)
cat("\n Distribution assumed for the healthy sample: ", x$T$dist1, "(", round(x$T$pars1[1], 2), ", ", round(x$T$pars1[2], 2), ")", sep="")
cat("\n Distribution assumed for the diseased sample: ", x$T$dist2, "(", round(x$T$pars2[1], 2), ", ", round(x$T$pars2[2], 2), ")", sep="")
cat("\n")
}
if (x$T$method == "empirical"){
cat("\nEstimate:")
cat("\n Threshold: ", x$T$thres)
cat("\n Minimum Cost: ", x$T$cost)
if (!is.null(x$CI)){
cat("\n")
cat("\nConfidence intervals (bootstrap):")
cat("\n CI based on normal distribution:", x$CI$low.norm, " - ", x$CI$up.norm)
cat("\n CI based on percentiles:", x$CI$low.perc, " - ", x$CI$up.perc)
cat("\n Bootstrap resamples:", x$CI$B)
}
cat("\n")
cat("\nParameters used:")
cat("\n Disease prevalence:", x$T$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$T$costs)
cat("\n R:", x$T$R)
cat("\n Method:", x$T$method)
if (!is.null(x$CI)){
cat("\n Significance Level:", x$CI$alpha)
}
cat("\n")
}
if (x$T$method == "smooth"){
cat("\nEstimate:")
cat("\n Threshold: ", x$T$thres)
if (!is.null(x$CI)){
cat("\n")
cat("\nConfidence intervals (bootstrap):")
cat("\n CI based on normal distribution:", x$CI$low.norm, " - ", x$CI$up.norm)
cat("\n CI based on percentiles:", x$CI$low.perc, " - ", x$CI$up.perc)
cat("\n Bootstrap resamples:", x$CI$B)
}
cat("\n")
cat("\nParameters used:")
cat("\n Disease prevalence:", x$T$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$T$costs)
cat("\n R:", x$T$R)
cat("\n Method:", x$T$method)
if (!is.null(x$CI)){
cat("\n Significance Level:", x$CI$alpha)
}
cat("\n")
}
if (x$T$method == "equal" | x$T$method == "unequal"){
cat("\nEstimate:")
cat("\n Threshold: ", x$T$thres)
cat("\n")
if (!is.null(x$CI)){
if(x$CI$ci.method == "delta"){
cat("\nConfidence interval (delta method):")
cat("\n Lower Limit:", x$CI$lower)
cat("\n Upper Limit:", x$CI$upper)
cat("\n")
}
if(x$CI$ci.method == "boot"){
cat("\nConfidence intervals (bootstrap):")
cat("\n CI based on normal distribution: ", x$CI$low.norm, " - ", x$CI$up.norm)
cat("\n CI based on percentiles: ", x$CI$low.perc, " - ", x$CI$up.perc)
cat("\n Bootstrap resamples: ", x$CI$B)
cat("\n")
}
}
cat("\nParameters used:")
cat("\n Disease prevalence:", x$T$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$T$costs)
cat("\n R:", x$T$R)
cat("\n Method:", x$T$method)
if (!is.null(x$CI)){
cat("\n Significance Level: ", x$CI$alpha)
}
cat("\n")
}
}
getParams <- function(k, dist){
if (dist %in% c("cauchy", "gamma", "weibull")){
pars <- fitdistr(k, dist)$estimate
}else if(dist=="beta"){
sigma2 <- var(k)
mu <- mean(k)
shape1.start <- ((1-mu)/sigma2-1/mu)*mu^2
shape2.start <- shape1.start*(1/mu-1)
pars <- fitdistr(k, "beta", start=list(shape1=shape1.start, shape2=shape2.start))$estimate
}else if(dist=="chisq"){
sigma2 <- var(k)
mu <- mean(k)
ncp.start <- sigma2/2-mu
df.start <- mu-ncp.start
pars <- fitdistr(k, "chi-squared", start=list(df=df.start, ncp=ncp.start))$estimate
}else if(dist=="lnorm"){
pars <- fitdistr(k, "lognormal")$estimate
}else if(dist=="logis"){
pars <- fitdistr(k, "logistic")$estimate
}else if(dist=="norm"){
pars <- fitdistr(k, "normal")$estimate
}
out <- pars
return(out)
}
thres2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), R=NULL, method=c("equal", "unequal", "empirical", "smooth", "parametric"), dist1=NULL, dist2=NULL, ci=TRUE, ci.method=c("delta", "boot"), B=1000, alpha=0.05, extra.info=FALSE, na.rm=FALSE, q1=0.05, q2=0.95){
if (!(rho > 0 & rho < 1)){
stop("The disease prevalence 'rho' must be a number in (0,1)")
}
if (!is.numeric(k1) | !is.numeric(k2)){
stop("'k1' and 'k2' must be numeric vectors")
}
if (!is.logical(ci) | is.na(ci)){
stop("'ci' must be TRUE or FALSE")
}
if (is.null(costs) & is.null(R)){
stop("Both 'costs' and 'R' are NULL. Please specify one of them.")
}else if (!is.null(costs) & !is.null(R)){
stop("Either 'costs' or 'R' must be NULL")
}else if (is.null(costs) & !is.null(R)){
if (!is.numeric(R) | length(R)!=1){
stop("R must be a single number")
}
costs <- matrix(c(0, 0, 1, (1-rho)/(R*rho)), 2, 2, byrow=TRUE)
}else if (!is.null(costs) & is.null(R)){
if (!is.matrix(costs)){
stop("'costs' must be a matrix")
}
if (dim(costs)[1] != 2 | dim(costs)[2] != 2){
stop("'costs' must be a 2x2 matrix")
}
}
if (na.rm){
k1 <- k1[!is.na(k1)]
k2 <- k2[!is.na(k2)]
}
method <- match.arg(method)
ci.method <- match.arg(ci.method)
if (method=="equal"){
T <- thresEq2(k1, k2, rho, costs)
if (ci){
if (ci.method=="delta"){
CI <- icDeltaEq2(k1, k2, rho, costs, T$thres, a=alpha)
}
if (ci.method=="boot"){
CI <- icBootEq2(k1, k2, rho, costs, T$thres, B=B, a=alpha)
}
}else{
CI <- NULL
}
}
if (method=="unequal"){
T <- thresUn2(k1, k2, rho, costs)
if (ci){
if (ci.method=="delta"){
CI <- icDeltaUn2(k1, k2, rho, costs, T$thres, a=alpha)
}
if (ci.method=="boot"){
CI <- icBootUn2(k1, k2, rho, costs, T$thres, B=B, a=alpha)
}
}else{
CI <- NULL
}
}
if (method=="empirical"){
if (ci.method=="delta" & ci){
stop("When method='empirical', CIs cannot be computed based on delta method (choose ci.method='boot')")
}
T <- thresEmp2(k1, k2, rho, costs, extra.info)
if (ci){
CI <- icEmp2(k1, k2, rho, costs, T$thres, B=B, a=alpha)
}else{
CI <- NULL
}
}
if (method=="smooth"){
if (ci.method=="delta" & ci){
stop("When method='smooth', CIs cannot be computed based on delta method (choose ci.method='boot')")
}
T <- thresSmooth2(k1, k2, rho, costs)
if (ci){
CI <- icSmooth2(k1, k2, rho, costs, T$thres, B=B, a=alpha)
}else{
CI <- NULL
}
}
if (method=="parametric"){
if (ci.method=="delta" & ci){
stop("When method='parametric', CIs cannot be computed based on delta method (choose ci.method='boot')")
}
if (is.null(dist1) | is.null(dist2)){
stop("When method='parametric', 'dist1' and 'dist2' must be specified")
}
if (dist1=="norm" & dist2=="norm"){
stop("When assuming a binormal distribution, choose method='equal' or 'unequal'")
}
if (!(dist1 %in% c("beta", "cauchy", "chisq", "gamma", "lnorm", "logis", "nbinom", "norm", "weibull"))){
stop("Unsupported distribution for 'dist1'")
}
if (!(dist2 %in% c("beta", "cauchy", "chisq", "gamma", "lnorm", "logis", "nbinom", "norm", "weibull"))){
stop("Unsupported distribution for 'dist2'")
}
pars1 <- getParams(k1, dist1)
pars2 <- getParams(k2, dist2)
T <- thresTH2(dist1, dist2, pars1[1], pars1[2], pars2[1], pars2[2], rho, costs, q1=q1, q2=q2)
T <- unclass(T)
T$method <- "parametric"
T$k1 <- k1
T$k2 <- k2
T$dist1 <- dist1
T$dist2 <- dist2
T$pars1 <- pars1
T$pars2 <- pars2
if (ci){
CI <- icBootTH(dist1, dist2, pars1[1], pars1[2], pars2[1], pars2[2], length(k1), length(k2), rho, costs, T$thres, B=B, a=alpha)
}else{
CI <- NULL
}
}
out <- list(T=T, CI=CI)
class(out) <- "thres2"
return(out)
}
varVarEq <- function(k1, k2){
n1 <- length(k1)
n2 <- length(k2)
est <- 2*(varPooled(k1,k2))^2/(n1 + n2 - 1)
return(est)
}
varMeanEq <- function(k1, k2, t){
est <- varPooled(k1, k2)/t
return(est)
}
derVarEq <- function(k1, k2, rho, costs){
est <- log(slope(rho,costs))/(mean(k2) - mean(k1))
return(est)
}
derMeanDisEq <- function(k1, k2, rho, costs){
est <- 1/2 - (varPooled(k1,k2)*log(slope(rho,costs)))/((mean(k2) - mean(k1))^2)
return(est)
}
derMeanNDisEq <- function(k1, k2, rho, costs){
est <- 1/2 + (varPooled(k1,k2)*log(slope(rho,costs)))/((mean(k2) - mean(k1))^2)
return(est)
}
varDeltaEq2 <- function(k1, k2, rho, costs){
if(mean(k1) > mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
n1 <- length(k1)
n2 <- length(k2)
d <- matrix(c(derMeanNDisEq(k1, k2, rho, costs), derMeanDisEq(k1, k2, rho, costs), derVarEq(k1, k2, rho, costs)), byrow=T, ncol=3, nrow=1)
sigma <- matrix(c(varMeanEq(k1, k2, n2), 0, 0, 0, varMeanEq(k1, k2, n1), 0, 0, 0, varVarEq(k1, k2)), byrow=T, ncol=3, nrow=3)
est <- d%*%sigma%*%t(d)
return(est)
}
icDeltaEq2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), Thres, a=0.05){
stdev <- sqrt(varDeltaEq2(k1, k2, rho, costs))
ic1 <- Thres + qnorm(a/2)*stdev
ic2 <- Thres + qnorm(1-a/2)*stdev
ic <- list(lower=ic1, upper=ic2, se=stdev, alpha=a, ci.method="delta")
return(ic)
}
varVarUn <- function(k, t){
est <- 2*(var(k))^2/(t - 1)
return(est)
}
varMeanUn <- function(k, t){
est <- var(k)/t
return(est)
}
derMeanDisUn <- function(k1, k2, rho, costs){
est <- (sd(k2)*sd(k1)*(mean(k2) - mean(k1))/sqrt((mean(k2) - mean(k1))^2+2*(var(k2) - var(k1))*log(sd(k2)*slope(rho,costs)/sd(k1))) - var(k1))/(var(k2) - var(k1))
return(est)
}
derMeanNDisUn <- function(k1, k2, rho, costs){
est <- (var(k2) - sd(k2)*sd(k1)*(mean(k2) - mean(k1))/sqrt((mean(k2) - mean(k1))^2+2*(var(k2) - var(k1))*log(sd(k2)*slope(rho,costs)/sd(k1))))/(var(k2) - var(k1))
return(est)
}
derVarDisUn <- function(k1, k2, rho, costs){
beta <- slope(rho,costs)
est <- (sd(k1)*sd(k2)*((var(k2) - var(k1))/var(k2) + 2*log(beta*sd(k2)/sd(k1)))/(2*sqrt(2*log(beta*sd(k2)/sd(k1))*(var(k2) - var(k1))+(mean(k2) - mean(k1))^2)) + sd(k1)*sqrt(2*log(beta*sd(k2)/sd(k1))*(var(k2) - var(k1)) + (mean(k2) - mean(k1))^2)/(2*sd(k2)) + mean(k1)) /(var(k2) - var(k1)) - (sd(k1)*sd(k2)*sqrt(2*log(beta*sd(k2)/sd(k1))*(var(k2) - var(k1))+(mean(k2)-mean(k1))^2)+mean(k1)*var(k2)-mean(k2)*var(k1))/(var(k2)-var(k1))^2
return(est)
}
derVarNDisUn <- function(k1, k2, rho, costs){
beta <- slope(rho, costs)
est <- (-mean(k2)*var(k1)+sd(k2)*sqrt(2*log(sd(k2)*beta/sd(k1))*(var(k2)-var(k1))+(mean(k2)-mean(k1))^2)*sd(k1)+mean(k1)*var(k2)) /(var(k2)-var(k1))^2 +(sd(k2)*(-(var(k2)-var(k1))/var(k1)-2*log(sd(k2)*beta/sd(k1)))*sd(k1) /(2*sqrt(2*log(sd(k2)*beta/sd(k1))*(var(k2)-var(k1))+(mean(k2)-mean(k1))^2)) +sd(k2)*sqrt(2*log(sd(k2)*beta/sd(k1))*(var(k2)-var(k1))+(mean(k2)-mean(k1))^2)/(2*sd(k1))-mean(k2)) /(var(k2)-var(k1))
return(est)
}
varDeltaUn2 <- function(k1, k2, rho, costs){
if(mean(k1) > mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
n1 <- length(k1)
n2 <- length(k2)
ctrl <- sqroot(k1,k2,rho,costs)
if(ctrl < 0){
est <- NA
warning("Negative discriminant; cannot solve the second-degree equation")
}else{
d <- matrix(c(derMeanNDisUn(k1, k2, rho, costs), derMeanDisUn(k1, k2, rho, costs), derVarNDisUn(k1, k2, rho, costs), derVarDisUn(k1, k2, rho, costs)), byrow=T, ncol=4, nrow=1)
sigma <- matrix(c(varMeanUn(k1, n1), 0, 0, 0, 0, varMeanUn(k2, n2), 0, 0, 0, 0, varVarUn(k1, n1), 0, 0, 0, 0, varVarUn(k2, n2)), byrow=T, ncol=4, nrow=4)
est <- d%*%sigma%*%t(d)
}
return(est)
}
icDeltaUn2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), Thres, a=0.05){
stdev <- sqrt(varDeltaUn2(k1, k2, rho, costs))
ic1 <- Thres + qnorm(a/2)*stdev
ic2 <- Thres + qnorm(1-a/2)*stdev
ic <- list(lower=ic1, upper=ic2, se=stdev, alpha=a, ci.method="delta")
return(ic)
}
resample2 <- function(k1, k2, B){
n1 <- length(k1)
n2 <- length(k2)
t0 <- matrix(sample(k1, n1*B, replace=TRUE), nrow=n1)
t1 <- matrix(sample(k2, n2*B, replace=TRUE), nrow=n2)
t <- list(t0, t1)
return(t)
}
icBootEq2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), Thres, B, a=0.05){
if(mean(k1) > mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
t <- resample2(k1, k2, B)
t0 <- t[[1]]
t1 <- t[[2]]
cut <- sapply(1:B,function(i){thresEq2(t0[,i],t1[,i],rho,costs)[[1]]})
est.se <- sd(cut)
norm.bootSE <- c(Thres + qnorm(a/2)*est.se, Thres + qnorm(1-a/2)*est.se)
percentil <- (c(quantile(cut,a/2), quantile(cut,1-a/2)))
re <- list(low.norm=norm.bootSE[1], up.norm=norm.bootSE[2], se=est.se, low.perc=percentil[1], up.perc=percentil[2], alpha=a, B=B, ci.method="boot")
return(re)
}
icBootUn2 <- function(k1, k2, rho, costs=matrix(c(0, 0, 1, (1-rho)/rho), 2, 2, byrow=TRUE), Thres, B, a=0.05){
if(mean(k1) > mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
t <- resample2(k1, k2, B)
t0 <- t[[1]]
t1 <- t[[2]]
cut <- sapply(1:B,function(i){thresUn2(t0[,i],t1[,i],rho,costs)[[1]]})
est.se <- sd(na.omit(cut))
norm.bootSE <- c(Thres + qnorm(a/2)*est.se, Thres + qnorm(1-a/2)*est.se)
percentil <- (c(quantile(na.omit(cut),a/2), quantile(na.omit(cut),1-a/2)))
re <- list(low.norm=norm.bootSE[1], up.norm=norm.bootSE[2], se=est.se, low.perc=percentil[1], up.perc=percentil[2], alpha=a, B=B, ci.method="boot")
return(re)
}
icEmp2 <- function(k1,k2,rho,costs=matrix(c(0,0,1,(1-rho)/rho),2,2, byrow=TRUE),Thres,B=500,a=0.05){
if(mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
t <- resample2(k1, k2, B)
t0 <- t[[1]]
t1 <- t[[2]]
cut <- rep(NA,B)
cut <- suppressWarnings(sapply(1:B,function(j){thresEmp2(t0[,j],t1[,j],rho,costs)[[1]]}))
est.se <- sd(cut)
norm <- c(Thres+qnorm(a/2)*est.se, Thres+qnorm(1-a/2)*est.se)
percentil <- (c(quantile(cut,a/2), quantile(cut,1-a/2)))
re <- list(low.norm=norm[1], up.norm=norm[2], se=est.se, low.perc=percentil[1], up.perc=percentil[2], alpha=a, B=B, ci.method="boot")
return(re)
}
icSmooth2 <- function(k1,k2,rho,costs=matrix(c(0,0,1,(1-rho)/rho),2,2, byrow=TRUE),Thres,B=500,a=0.05){
if(mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
}
t <- resample2(k1, k2, B)
t0 <- t[[1]]
t1 <- t[[2]]
cut <- rep(NA,B)
cut <- suppressWarnings(sapply(1:B,function(j){thresSmooth2(t0[,j],t1[,j],rho,costs)[[1]]}))
est.se <- sd(cut)
norm <- c(Thres+qnorm(a/2)*est.se, Thres+qnorm(1-a/2)*est.se)
percentil <- (c(quantile(cut,a/2), quantile(cut,1-a/2)))
re <- list(low.norm=norm[1], up.norm=norm[2], se=est.se, low.perc=percentil[1], up.perc=percentil[2], alpha=a, B=B, ci.method="boot")
return(re)
}
aux.par.boot <- function(dist1, dist2, par1.1, par1.2, par2.1, par2.2, n1, n2, B){
t0 <- matrix(rand(dist1)(n1*B, par1.1, par1.2), nrow=n1)
t1 <- matrix(rand(dist2)(n2*B, par2.1, par2.2), nrow=n2)
t <- list(t0,t1)
return(t)
}
icBootTH <- function(dist1, dist2, par1.1, par1.2, par2.1, par2.2, n1, n2, rho, costs=matrix(c(0,0,1,(1-rho)/rho), 2, 2, byrow=TRUE), Thres, B=500, a=0.05){
median1 <- quant(dist1)(0.5, par1.1, par1.2)
median2 <- quant(dist2)(0.5, par2.1, par2.2)
if(median1 > median2){
rho <- 1-rho
costs <- costs[, 2:1]
g <- par2.1; par2.1 <- par1.1; par1.1 <- g
f <- par2.2; par2.2 <- par1.2; par1.2 <- f
auxdist <- dist2; dist2 <- dist1; dist1 <- auxdist
}
t <- aux.par.boot(dist1, dist2, par1.1, par1.2, par2.1, par2.2, n1, n2, B)
t0 <- t[[1]]
t1 <- t[[2]]
pars1 <- sapply(1:B, function(i){getParams(t0[, i], dist1)})
pars2 <- sapply(1:B, function(i){getParams(t1[, i], dist2)})
cut <- sapply(1:B,function(i){thresTH2(dist1, dist2, pars1[1, i], pars1[2, i], pars2[1, i], pars2[2, i], rho, costs)[[1]]})
est.se <- sd(na.omit(cut))
norm.bootSE <- c(Thres + qnorm(a/2)*est.se, Thres + qnorm(1-a/2)*est.se)
percentil <- (c(quantile(na.omit(cut),a/2), quantile(na.omit(cut),1-a/2)))
re <- list(low.norm=norm.bootSE[1], up.norm=norm.bootSE[2], se=est.se, low.perc=percentil[1], up.perc=percentil[2], alpha=a, B=B, ci.method="boot")
return(re)
}
plotCostROC <- function(x, type="l", ...){
if (!(class(x) %in% c("thres2", "thres3"))){
stop("'x' must be a 'thres2' or 'thres3' object")
}
if (class(x)=="thres2"){
if (x$T$method == "smooth"){
k1 <- x$T$k1; k2 <- x$T$k2; rho <- x$T$prev; costs <- x$T$costs
changed <- FALSE
if (mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
changed <- TRUE
}
k <- c(x$T$k1, x$T$k2)
rangex <- range(k)
xlim <- c(floor(rangex[1]), ceiling(rangex[2]))
y <- thres2(x$T$k1, x$T$k2, x$T$prev, x$T$costs, method="empirical", extra.info=TRUE, ci=FALSE)
xx <- y$T$tot.thres
yy <- y$T$tot.cost
lo <- loess(yy~xx)
pred <- predict(lo)
plot(xx, yy, xlim=xlim, ylim=c(min(pred), max(pred)), type="n", xlab="t", ylab="cost(t)")
lines(xx, pred, ...)
par(ask=T)
CUT <- x$T$thres
if (!changed){
resp.CUT <- ifelse(k<CUT, 0, 1)
}else{
resp.CUT <- ifelse(k>CUT, 0, 1)
}
resp <- c(rep(0, length(x$T$k1)), rep(1, length(x$T$k2)))
resp.CUT <- factor(resp.CUT, c("0", "1"))
roc <- roc(response=resp, predictor=k, quiet=TRUE)
plot(smooth(roc))
par(ask=F)
}
if (x$T$method == "empirical"){
if (length(x$T) != 14){
stop("use argument 'extra.info = TRUE' in 'thres2()'")
}
plot(x$T$tot.thres, x$T$tot.cost, xlab="Threshold", ylab="Cost", main="Empirical Cost function", type=type, ...)
points(x$T$thres, x$T$cost, col=2, pch=19)
par(ask=T)
plot(1-x$T$tot.spec,x$T$tot.sens, main="Empirical ROC curve", xlab="1-Specificity", ylab="Sensitivity", type=type, ...)
points(1-x$T$spec, x$T$sens, col=2, pch=19)
par(ask=F)
}
if (x$T$method =="equal"){
k1 <- x$T$k1; k2 <- x$T$k2; rho <- x$T$prev; costs <- x$T$costs
changed <- FALSE
if (mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
changed <- TRUE
}
k <- c(x$T$k1, x$T$k2)
rangex <- range(k)
xlim <- c(floor(rangex[1]), ceiling(rangex[2]))
cost <- function(t){
sd <- sqrt(varPooled(k1, k2))
TP <- (1-pnorm(t, mean(k2), sd))*rho
FN <- (pnorm(t, mean(k2), sd))*rho
FP <- (1-pnorm(t, mean(k1), sd))*(1-rho)
TN <- (pnorm(t, mean(k1), sd))*(1-rho)
n <- length(k1)+length(k2)
C <- n*(TP*costs[1,1]+FN*costs[2, 2]+FP*costs[2, 1]+TN*costs[1, 2])
return(as.numeric(C))
}
plot(cost, xlim=xlim, type=type, xlab="t", ylab="cost(t)", ...)
points(x$T$thres, cost(x$T$thres), col=2, pch=19)
par(ask=T)
CUT <- x$T$thres
if (!changed){
resp.CUT <- ifelse(k<CUT, 0, 1)
}else{
resp.CUT <- ifelse(k>CUT, 0, 1)
}
resp <- c(rep(0, length(x$T$k1)), rep(1, length(x$T$k2)))
resp.CUT <- factor(resp.CUT, c("0", "1"))
roc <- roc(response=resp, predictor=k, quiet=TRUE)
plot(roc)
tab <- table(resp.CUT, resp)[2:1, 2:1]
SENS <- tab[1, 1]/(tab[1, 1]+tab[2, 1])
SPEC <- tab[2, 2]/(tab[2, 2]+tab[1, 2])
points(SPEC, SENS, col=2, pch=19)
par(ask=F)
}
if (x$T$method=="unequal"){
k1 <- x$T$k1; k2 <- x$T$k2; rho <- x$T$prev; costs <- x$T$costs
changed <- FALSE
if (mean(k1)>mean(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
changed <- TRUE
}
k <- c(x$T$k1, x$T$k2)
rangex <- range(k)
xlim <- c(floor(rangex[1]), ceiling(rangex[2]))
cost <- function(t){
sd1 <- sd(k1)
sd2 <- sd(k2)
TP <- (1-pnorm(t, mean(k2), sd2))*rho
FN <- (pnorm(t, mean(k2), sd2))*rho
FP <- (1-pnorm(t, mean(k1), sd1))*(1-rho)
TN <- (pnorm(t, mean(k1), sd1))*(1-rho)
n <- length(k1)+length(k2)
C <- n*(TP*costs[1,1]+FN*costs[2, 2]+FP*costs[2, 1]+TN*costs[1, 2])
return(as.numeric(C))
}
plot(cost, xlim=xlim, type=type, xlab="t", ylab="cost(t)", ...)
points(x$T$thres, cost(x$T$thres), col=2, pch=19)
par(ask=T)
CUT <- x$T$thres
if (!changed){
resp.CUT <- ifelse(k<CUT, 0, 1)
}else{
resp.CUT <- ifelse(k>CUT, 0, 1)
}
resp <- c(rep(0, length(x$T$k1)), rep(1, length(x$T$k2)))
resp.CUT <- factor(resp.CUT, c("0", "1"))
roc <- roc(response=resp, predictor=k, quiet=TRUE)
plot(roc)
tab <- table(resp.CUT, resp)[2:1, 2:1]
SENS <- tab[1, 1]/(tab[1, 1]+tab[2, 1])
SPEC <- tab[2, 2]/(tab[2, 2]+tab[1, 2])
points(SPEC, SENS, col=2, pch=19)
par(ask=F)
}
if (x$T$method=="parametric"){
k1 <- x$T$k1; k2 <- x$T$k2; rho <- x$T$prev; costs <- x$T$costs
dist1 <- x$T$dist1; dist2 <- x$T$dist2
par1.1 <- x$T$pars1[1]; par1.2 <- x$T$pars1[2]; par2.1 <- x$T$pars2[1]; par2.2 <- x$T$pars2[2]
changed <- FALSE
if (median(k1)>median(k2)){
rho <- 1-rho
costs <- costs[, 2:1]
g <- k1; k1 <- k2; k2 <- g
changed <- TRUE
g <- par2.1; par2.1 <- par1.1; par1.1 <- g
f <- par2.2; par2.2 <- par1.2; par1.2 <- f
auxdist <- dist2; dist2 <- dist1; dist1 <- auxdist
}
k <- c(x$T$k1, x$T$k2)
rangex <- range(k)
xlim <- c(floor(rangex[1]), ceiling(rangex[2]))
cost <- function(t){
TP <- (1-p(dist2)(t, par2.1, par2.2))*rho
FN <- (p(dist2)(t, par2.1, par2.2))*rho
FP <- (1-p(dist1)(t, par1.1, par1.2))*(1-rho)
TN <- (p(dist1)(t, par1.1, par1.2))*(1-rho)
n <- length(k1)+length(k2)
C <- n*(TP*costs[1,1]+FN*costs[2, 2]+FP*costs[2, 1]+TN*costs[1, 2])
return(as.numeric(C))
}
plot(cost, xlim=xlim, type=type, xlab="t", ylab="cost(t)", ...)
points(x$T$thres, cost(x$T$thres), col=2, pch=19)
par(ask=T)
CUT <- x$T$thres
if (!changed){
resp.CUT <- ifelse(k<CUT, 0, 1)
}else{
resp.CUT <- ifelse(k>CUT, 0, 1)
}
resp <- c(rep(0, length(x$T$k1)), rep(1, length(x$T$k2)))
resp.CUT <- factor(resp.CUT, c("0", "1"))
roc <- roc(response=resp, predictor=k, quiet=TRUE)
plot(roc)
tab <- table(resp.CUT, resp)[2:1, 2:1]
SENS <- tab[1, 1]/(tab[1, 1]+tab[2, 1])
SPEC <- tab[2, 2]/(tab[2, 2]+tab[1, 2])
points(SPEC, SENS, col=2, pch=19)
par(ask=F)
}
}else{
k <- c(x$T$k1, x$T$k2, x$T$k3)
rangex <- range(k)
xlim <- c(floor(rangex[1]), ceiling(rangex[2]))
dist1 <- x$T$dist1; dist2 <- x$T$dist2; dist3 <- x$T$dist3
rho <- x$T$prev; costs <- x$T$costs
if (dist1 =="norm" & dist2=="norm" & dist3=="norm"){
par1.1 <- mean(x$T$k1); par1.2 <- sd(x$T$k1)
par2.1 <- mean(x$T$k2); par2.2 <- sd(x$T$k2)
par3.1 <- mean(x$T$k3); par3.2 <- sd(x$T$k3)
}else{
par1.1 <- x$T$pars1[1]; par1.2 <- x$T$pars1[2]
par2.1 <- x$T$pars2[1]; par2.2 <- x$T$pars2[2]
par3.1 <- x$T$pars3[1]; par3.2 <- x$T$pars3[2]
}
cost.t1 <- function(t){
aux1 <- rho[1]*p(dist1)(t, par1.1, par1.2)*(costs[1, 1]-costs[1, 2])
aux2 <- rho[2]*p(dist2)(t, par2.1, par2.2)*(costs[2, 1]-costs[2, 2])
aux3 <- rho[3]*p(dist3)(t, par3.1, par3.2)*(costs[3, 1]-costs[3, 2])
C <- aux1+aux2+aux3
return(as.numeric(C))
}
cost.t2 <- function(t){
aux1 <- rho[1]*p(dist1)(t, par1.1, par1.2)*(costs[1, 2]-costs[1, 3])
aux2 <- rho[2]*p(dist2)(t, par2.1, par2.2)*(costs[2, 2]-costs[2, 3])
aux3 <- rho[3]*p(dist3)(t, par3.1, par3.2)*(costs[3, 2]-costs[3, 3])
C <- aux1+aux2+aux3
return(as.numeric(C))
}
plot(cost.t1, xlim=xlim, type=type, ylab="Cost(thres1)", xlab="thres1", ...)
points(x$T$thres1, cost.t1(x$T$thres1), col=2, pch=19)
par(ask=T)
plot(cost.t2, xlim=xlim, type=type, ylab="Cost(thres2)", xlab="thres2", ...)
points(x$T$thres2, cost.t2(x$T$thres2), col=2, pch=19)
par(ask=F)
}
}
plot.thres2 <- function(x, bw=c("nrd0", "nrd0"), ci=TRUE, which.boot=c("norm", "perc"), col=c(1, 2, 3), lty=c(1, 1, 1, 2), lwd=c(1, 1, 1), legend=TRUE, leg.pos="topleft", leg.cex=1, xlim=NULL, ylim=NULL, main=paste0("Threshold estimate ", ifelse(ci, "and CI ", ""), "(method ", x$T$method, ")"), xlab="", ...){
if (!is.logical(ci) | is.na(ci)){
stop("'ci' must be TRUE or FALSE")
}
if (!is.logical(legend) | is.na(legend)){
stop("'legend' must be TRUE or FALSE")
}
if (!is.null(xlim)){
if (any(is.na(xlim)) | length(xlim)!=2){
stop("'xlim' must be NULL or a 2-dimensional vector containing no NAs")
}
}
if (!is.null(ylim)){
if (any(is.na(ylim)) | length(ylim)!=2){
stop("'ylim' must be NULL or a 2-dimensional vector containing no NAs")
}
}
if (length(col)!=3){
col <- rep_len(col, 3)
}
if (length(lty)!=4){
lty <- rep_len(lty, 4)
}
if (length(lwd)!=3){
lwd <- rep_len(lwd, 3)
}
which.boot <- match.arg(which.boot)
k1 <- x$T$k1
k2 <- x$T$k2
dens.k1 <- density(k1, bw=bw[1])
dens.k2 <- density(k2, bw=bw[2])
if (is.null(xlim)){
min.x <- min(min(dens.k1$x), min(dens.k2$x))
max.x <- max(max(dens.k1$x), max(dens.k2$x))
}else{
min.x <- xlim[1]
max.x <- xlim[2]
}
if (is.null(ylim)){
min.y <- 0
max.y <- max(max(dens.k1$y), max(dens.k2$y))
}else{
min.y <- ylim[1]
max.y <- ylim[2]
}
plot(dens.k1, xlim=c(min.x, max.x), ylim=c(min.y, max.y), col=col[1], lty=lty[1], lwd=lwd[1], main=main, xlab=xlab, ...)
lines(dens.k2, col=col[2], lty=lty[2], lwd=lwd[2])
abline(v=x$T$thres, col=col[3], lty=lty[3], lwd=lwd[3])
if(ci & !is.null(x$CI)){
if (x$CI$ci.method != "boot"){
abline(v=c(x$CI$lower, x$CI$upper), col=col[3], lty=lty[4], lwd=lwd[3])
}else{
abline(v=c(x$CI[paste0("low.", which.boot)], x$CI[paste0("up.", which.boot)]), col=col[3], lty=lty[4], lwd=lwd[3])
}
}
if (legend){
legend(leg.pos, c(expression(bar(D)), "D", ifelse(ci & !is.null(x$CI), "Thres+CI", "Thres")), col=col, lty=lty, lwd=lwd, cex=leg.cex)
}
}
lines.thres2 <- function(x, ci=TRUE, which.boot=c("norm", "perc"), col=1, lty=c(1, 2), lwd=1, ...){
if (!is.logical(ci) | is.na(ci)){
stop("'ci' must be TRUE or FALSE")
}
if (length(lty)!=2){
lty <- rep_len(lty, 2)
}
which.boot <- match.arg(which.boot)
abline(v=x$T$thres, col=col, lty=lty[1], lwd=lwd)
if(ci & !is.null(x$CI)){
if (x$CI$ci.method != "boot"){
abline(v=c(x$CI$lower, x$CI$upper), col=col, lty=lty[2], lwd=lwd, ...)
}else{
abline(v=c(x$CI[paste0("low.", which.boot)], x$CI[paste0("up.", which.boot)]), col=col, lty=lty[2], lwd=lwd, ...)
}
}
}
control <- function(par1.1,par1.2,par2.1,par2.2,rho,costs){
ctrl <- (par2.1-par1.1)^2+2*log((par2.2/par1.2)*slope(rho,costs))*(par2.2^2-par1.2^2)
return(ctrl)
}
parVarUn <- function(sdev, t){
est <- 2*sdev^4/(t-1)
return(est)
}
parMeanUn <- function(sdev,t){
est <- sdev^2/t
return(est)
}
parDerMeanDisUn <- function(par1.1,par1.2,par2.1,par2.2,rho,costs){
est <- (par2.2*par1.2*(par2.1-par1.1)/sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs) )-par1.2^2)/(par2.2^2-par1.2^2)
return(est)
}
parDerMeanNonDisUn <- function(par1.1,par1.2,par2.1,par2.2,rho,costs){
est <- (par2.2^2-par2.2*par2.1*(par1.2-par1.1)/sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs)))/(par2.2^2-par2.1^2)
return(est)
}
parDerVarDisUn <- function(par1.1,par1.2,par2.1,par2.2,rho,costs){
est <- ((par1.2*par2.2*((par2.2^2-par1.2^2)/par2.2^2+2*log(slope(rho,costs)*par2.2/par1.2)))/(2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs)))+par1.2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs))/(2*par2.2)+par1.1)/(par2.2^2-par1.2^2)-(par1.2*par2.2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs))+par1.1*par2.2^2-par2.1*par1.2^2)/(par2.2^2-par1.2^2)^2
return(est)
}
parDerVarNonDisUn <- function(par1.1,par1.2,par2.1,par2.2,rho,costs){
est <- ((par1.2*par2.2*((par1.2^2-par2.2^2)/par2.2^2-2*log(slope(rho,costs)*par2.2/par1.2)))/(2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs)))+par2.2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs))/(2*par1.2)-par2.1)/(par2.2^2-par1.2^2)+(par1.2*par2.2*sqrt(control(par1.1,par1.2,par2.1,par2.2,rho,costs))+par1.1*par2.2^2-par2.1*par1.2^2)/(par2.2^2-par1.2^2)^2
return(est)
}
SS <- function(par1.1, par1.2, par2.1, par2.2=NULL, rho, width, costs=matrix(c(0,0,1,(1-rho)/rho),2,2, byrow=TRUE), R=NULL, var.equal=FALSE, alpha=0.05){
if (!(rho > 0 & rho < 1)){
stop("The disease prevalence rho must be a number in (0,1)")
}
if (width<=0){
stop("'width' must be a positive number")
}
if (!is.logical(var.equal) | is.na(var.equal)){
stop("'var.equal' must be TRUE or FALSE")
}
if (var.equal){
if (!is.null(par2.2)){
if (par1.2 != par2.2){
stop("'var.equal' is set to TRUE, but 'par1.2' and 'par2.2' are different")
}
}else{
par2.2 <- par1.2
}
}else{
if (is.null(par2.2)){
stop("When 'var.equal' is set to FALSE, a value for 'par2.2' must be given")
}
if (par1.2==par2.2){
stop("'var.equal' is set to FALSE, but par1.2==par2.2")
}
}
if (is.null(costs) & is.null(R)){
stop("Both 'costs' and 'R' are NULL. Please specify one of them.")
}else if (!is.null(costs) & !is.null(R)){
stop("Either 'costs' or 'R' must be NULL")
}else if (is.null(costs) & !is.null(R)){
if (!is.numeric(R) | length(R)!=1){
stop("R must be a single number")
}
costs <- matrix(c(0, 0, 1, (1-rho)/(R*rho)), 2, 2, byrow=TRUE)
}else if (!is.null(costs) & is.null(R)){
if (!is.matrix(costs)){
stop("'costs' must be a matrix")
}
if (dim(costs)[1] != 2 | dim(costs)[2] != 2){
stop("'costs' must be a 2x2 matrix")
}
}
costs.origin <- costs
rho.origin <- rho
par1.1.origin <- par1.1
par2.1.origin <- par2.1
L <- width/2
if (par1.1 > par2.1){
rho <- 1 - rho
costs <- costs[, 2:1]
g <- par1.1; par1.1 <- par2.1; par2.1 <- g
f <- par1.2; par1.2 <- par2.2; par2.2 <- f
}
R <- slope(rho, costs)
if(var.equal){
num <- 1/2-par1.2^2*log(R)/(par2.1-par1.1)^2
den <- 1/2+par1.2^2*log(R)/(par2.1-par1.1)^2
epsilon <- abs(num/den)
est.non.dis <- (qnorm(1-alpha/2)/L)^2*((log(R)/(par2.1-par1.1))^2*2*par1.2^4/(1+epsilon)
+(1/2-par1.2^2*log(R)/(par2.1-par1.1)^2)^2*par1.2^2/epsilon
+(1/2+par1.2^2*log(R)/(par2.1-par1.1)^2)^2*par1.2^2)
}else{
threshold <- expression((sigma2D*muND-sigma2ND*muD+sqrt(sigma2ND*sigma2D)*sqrt((muD-muND)^2+2*log(R*sqrt(sigma2D/sigma2ND))*(sigma2D-sigma2ND)))/(sigma2D-sigma2ND))
where <- list(muND=par1.1, sigma2ND=par1.2^2, muD=par2.1, sigma2D=par2.2^2, R=R)
a <- (as.numeric(attributes(eval(deriv(threshold, "muD"), where))$gradient))^2
b <- (as.numeric(attributes(eval(deriv(threshold, "muND"), where))$gradient))^2
c <- (as.numeric(attributes(eval(deriv(threshold, "sigma2D"), where))$gradient))^2
d <- (as.numeric(attributes(eval(deriv(threshold, "sigma2ND"), where))$gradient))^2
epsilon <- sqrt((a*par2.2^2+2*c*par2.2^4)/(b*par1.2^2+2*d*par1.2^4))
est.non.dis <- (qnorm(1-alpha/2)/L)^2*(a*par2.2^2/epsilon+b*par1.2^2+2*c*par2.2^4/epsilon+2*d*par1.2^4)
}
est.dis <- epsilon*est.non.dis
if (par1.1.origin > par2.1.origin){
auxiliar <- est.non.dis
est.non.dis <- est.dis
est.dis <- auxiliar
epsilon <- 1/epsilon
}
re <- list(ss2=est.dis, ss1=est.non.dis, epsilon=epsilon, width=width, alpha=alpha, costs=costs.origin, R=R, prev=rho.origin)
class(re) <- "SS"
return(re)
}
print.SS <- function(x, ...){
cat("Optimum SS Ratio: ", x$epsilon)
cat("\n\nSample size for")
cat("\n Diseased: ", x$ss2)
cat("\n Non-diseased: ", x$ss1)
cat("\n")
cat("\nParameters used")
cat("\n Significance Level: ", x$alpha)
cat("\n CI width: ", x$width)
cat("\n Disease prevalence:", x$prev)
cat("\n Costs (Ctp, Cfp, Ctn, Cfn):", x$costs)
cat("\n R:", x$R)
cat("\n")
}
|
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(scales)
library(readxl)
library(lubridate)
library(ggrepel)
library(gganimate)
library(tidyverse)
folder_name <- "0158_fwd_ret_visual"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
animate <- 0
raw <- read.csv(paste0(importdir, "0158_dfa_sp500/DFA_PeriodicReturns_20191223103141.csv"), skip = 7,
col.names = c("date", "ret_sp500", "blank_col")) %>%
select(-blank_col) %>%
filter(!is.na(ret_sp500)) %>%
mutate(date = as.Date(date, format = "%m/%d/%Y")) %>%
select(date, ret_sp500)
df <- raw
for(i in 1:nrow(df)){
ret <- df[i, "ret_sp500"]
if(i == 1){
df[i, "index"] <- 1
} else{
df[i, "index"] <- df[(i-1), "index"] * (1 + ret)
}
}
lag_years <- c(1, 5, 10, 15, 20)
years_seq <- seq(1, 10, 1)
for(l in lag_years){
lag_months <- l * 12
for(y in years_seq){
fwd_months <- y * 12
tmp <- df %>%
mutate(lag_ret = (index/lag(index, lag_months))^(1/l) - 1,
lead_ret = (lead(index, fwd_months)/index),
n_years_ret = y) %>%
filter(!is.na(lag_ret), !is.na(lead_ret))
if(y == min(years_seq)){
final_results <- tmp
} else{
final_results <- bind_rows(final_results, tmp)
}
}
to_plot <- final_results %>%
select(lag_ret, lead_ret, n_years_ret)
source_string <- str_wrap(paste0("Source: Returns 2.0 (OfDollarsAndData.com)"),
width = 80)
note_string <- str_wrap(paste0("Note: Performance shown includes dividends, but is not adjusted for inflation."),
width = 80)
plot <- ggplot(to_plot, aes(x=lag_ret, y=lead_ret)) +
geom_point() +
geom_hline(yintercept = 1, linetype = "dashed") +
scale_x_continuous(label = percent) +
scale_y_continuous(label = dollar, breaks = seq(0, 8, 1), limits = c(0, 8)) +
of_dollars_and_data_theme +
ggtitle(paste0("S&P 500\n{closest_state}-Year Future Growth\nBased on ", l, "-Year Prior Return")) +
labs(x= paste0(l, "-Year Annualized Prior Return"), y = "Growth of $1",
caption = paste0(source_string, "\n", note_string)) +
transition_states(n_years_ret) +
ease_aes('linear')
if(animate == 1){
anim <- animate(plot, fps = 7)
anim_save(filename = paste0("annual_fwd_ret_lag_", l, "_scatter.gif"), animation = anim, path = out_path)
}
if(l == 10 | l == 20){
n_future <- 10
if(l == 10){
upper_flag <- 0.135
lower_flag <- 0.13
} else if (l == 20){
upper_flag <- 0.065
lower_flag <- 0.06
}
to_plot <- final_results %>%
filter(n_years_ret == n_future) %>%
mutate(flagged = ifelse(lag_ret > lower_flag & lag_ret < upper_flag, 1, 0)) %>%
select(date, lag_ret, lead_ret, n_years_ret, flagged)
print(paste0("N year lookback = ", l))
print(paste0("The correlation is: ", cor(to_plot$lag_ret, to_plot$lead_ret)))
flagged_points <- to_plot %>%
filter(flagged == 1) %>%
arrange(date)
print(flagged_points)
source_string <- str_wrap(paste0("Source: Returns 2.0 (OfDollarsAndData.com)"),
width = 80)
note_string <- str_wrap(paste0("Note: Performance shown includes dividends, but is not adjusted for inflation."),
width = 80)
file_path <- paste0(out_path, "/10_fwd_growth_", l, "_prior_plot.jpeg")
plot <- ggplot(to_plot, aes(x=lag_ret, y=lead_ret, col = as.factor(flagged))) +
geom_point() +
scale_color_manual(values = c("black", "black"), guide = FALSE) +
geom_hline(yintercept = 1, linetype = "dashed") +
scale_x_continuous(label = percent) +
scale_y_continuous(label = dollar, breaks = seq(0, 8, 1), limits = c(0, 8)) +
of_dollars_and_data_theme +
ggtitle(paste0("S&P 500\n", n_future, "-Year Future Growth\nBased on ", l, "-Year Prior Return")) +
labs(x= paste0(l, "-Year Annualized Prior Return"), y = "Growth of $1\nOver Next Decade",
caption = paste0(source_string, "\n", note_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
}
}
|
morphomapRaster<-function(cp,mp,pixel=1,filename,save=FALSE){
XX <- extendrange(cp[, 1])
YY <- extendrange(cp[, 2])
maxx <- max(XX)
minx <- min(XX)
maxy <- max(YY)
miny <- min(YY)
X <- seq(minx + pixel/2, maxx - pixel/2, pixel)
Y <- seq(miny + pixel/2, maxy - pixel/2, pixel)
M <- matrix(0, length(X), length(Y))
grid_sect <- as.matrix(expand.grid(X, Y))
A <- point.in.polygon(grid_sect[, 1], grid_sect[, 2], cp[,
1], cp[, 2], mode.checked = FALSE)
B <- point.in.polygon(grid_sect[, 1], grid_sect[, 2], mp[,
1], mp[, 2], mode.checked = FALSE)
sel <- which(A == 1 & B == 0)
selt <- rep(0, length(X) * length(Y))
selt[sel] <- 1
img <- list()
img$x <- (X)
img$y <- (Y)
img$z <- (matrix(t(selt), length(X), length(Y), byrow = F))
check_dx<-dim(img$z)[1]
check_dy<-dim(img$z)[2]
if(check_dx != check_dy){
if(check_dx>check_dy){
diff<-check_dx-check_dy
for(i in 1:diff){
img$z<-cbind(img$z,0)
}
if(check_dx<check_dy){
diff<-check_dy-check_dx
for(i in 1:diff){
img$z<-rbind(img$z,0)
}
}
}
}
r <- raster(t(img$z), xmn = 0, xmx = dim(img$z)[2],
ymn = 0, ymx = dim(img$z)[1], crs = CRS("+proj=utm +zone=11 +datum=NAD83"))
rimg <- flip(r, 2)
if (save == TRUE) {
writeRaster(rimg, filename, "GTiff",overwrite=TRUE)
}
return(rimg)
}
|
EotCycle <- function(x,
y,
n = 1,
standardised,
orig.var,
write.out,
path.out,
prefix,
type,
verbose,
...) {
x.vals <- raster::getValues(x)
y.vals <- raster::getValues(y)
type <- type[1]
if (verbose) {
cat("\nCalculating linear model ...", "\n")
}
type <- type[1]
if (type == "rsq") {
a <- predRsquaredSum(pred_vals = x.vals, resp_vals = y.vals,
standardised = standardised)
} else {
a <- iodaSumC(pred_vals = x.vals, resp_vals = y.vals)
}
if (verbose) {
cat("Locating ", n, ". EOT ...", "\n", sep = "")
}
maxxy.all <- which(a == max(a, na.rm = TRUE))
maxxy <- maxxy.all[1]
if (length(maxxy.all) != 1) {
if (verbose) {
cat("WARNING:", "\n",
"LOCATION OF EOT AMBIGUOUS!", "\n",
"MULTIPLE POSSIBLE LOCATIONS DETECTED, USING ONLY THE FIRST!\n\n")
}
}
if (verbose) {
cat("Location:", raster::xyFromCell(x, maxxy), "\n", sep = " ")
}
y.lm.param.t <- respLmParam(x.vals, y.vals, maxxy - 1)
y.lm.param.p <- lapply(y.lm.param.t, function(i) {
tmp <- i
tmp[[5]] <- 2 * pt(-abs(tmp[[5]]), df = tmp[[6]])
return(tmp)
})
rst.y.template <- raster::raster(nrows = raster::nrow(y),
ncols = raster::ncol(y),
xmn = raster::xmin(y),
xmx = raster::xmax(y),
ymn = raster::ymin(y),
ymx = raster::ymax(y))
rst.y.r <- rst.y.rsq <- rst.y.intercept <-
rst.y.slp <- rst.y.p <- rst.y.template
brck.y.resids <- raster::brick(nrows = raster::nrow(y),
ncols = raster::ncol(y),
xmn = raster::xmin(y),
xmx = raster::xmax(y),
ymn = raster::ymin(y),
ymx = raster::ymax(y),
nl = raster::nlayers(y))
rst.y.r[] <- sapply(y.lm.param.p, "[[", 1)
rst.y.rsq[] <- sapply(y.lm.param.p, "[[", 1) ^ 2
rst.y.intercept[] <- sapply(y.lm.param.p, "[[", 2)
rst.y.slp[] <- sapply(y.lm.param.p, "[[", 3)
rst.y.p[] <- sapply(y.lm.param.p, "[[", 5)
brck.y.resids[] <- matrix(sapply(y.lm.param.p, "[[", 4),
ncol = raster::nlayers(x), byrow = TRUE)
eot.ts <- as.numeric(raster::extract(x, maxxy)[1, ])
x.lm.param.t <- respLmParam(x.vals, x.vals, maxxy - 1)
x.lm.param.p <- lapply(x.lm.param.t, function(i) {
tmp <- i
tmp[[5]] <- 2 * pt(-abs(tmp[[5]]), df = tmp[[6]])
return(tmp)
})
rst.x.template <- raster::raster(nrows = raster::nrow(x),
ncols = raster::ncol(x),
xmn = raster::xmin(x),
xmx = raster::xmax(x),
ymn = raster::ymin(x),
ymx = raster::ymax(x))
rst.x.r <- rst.x.rsq <- rst.x.rsq.sums <- rst.x.intercept <-
rst.x.slp <- rst.x.p <- rst.x.template
brck.x.resids <- raster::brick(nrows = raster::nrow(x),
ncols = raster::ncol(x),
xmn = raster::xmin(x),
xmx = raster::xmax(x),
ymn = raster::ymin(x),
ymx = raster::ymax(x),
nl = raster::nlayers(x))
rst.x.r[] <- sapply(x.lm.param.p, "[[", 1)
rst.x.rsq[] <- sapply(x.lm.param.p, "[[", 1) ^ 2
rst.x.rsq.sums[] <- a
rst.x.intercept[] <- sapply(x.lm.param.p, "[[", 2)
rst.x.slp[] <- sapply(x.lm.param.p, "[[", 3)
rst.x.p[] <- sapply(x.lm.param.p, "[[", 5)
brck.x.resids[] <- matrix(sapply(x.lm.param.p, "[[", 4),
ncol = raster::nlayers(x), byrow = TRUE)
resid.var <- calcVar(brck.y.resids, standardised = standardised)
cum.expl.var <- (orig.var - resid.var) / orig.var
if (verbose) {
cat("Cum. expl. variance (%):", cum.expl.var * 100, "\n", sep = " ")
}
xy <- raster::xyFromCell(x, maxxy)
location.df <- as.data.frame(cbind(xy, paste("mode",
sprintf("%02.f", n),
sep = "_"),
cum.expl.var,
if (length(maxxy.all) != 1)
"ambiguous" else "ok"),
stringsAsFactors = FALSE)
names(location.df) <- c("x", "y", "mode", "cum_expl_var", "comment")
mode(location.df$x) <- "numeric"
mode(location.df$y) <- "numeric"
mode(location.df$cum_expl_var) <- "numeric"
out <- new('EotMode',
mode = n,
name = paste("mode", sprintf("%02.f", n), sep = "_"),
eot = eot.ts,
coords_bp = xy,
cell_bp = maxxy,
cum_exp_var = cum.expl.var,
r_predictor = rst.x.r,
rsq_predictor = rst.x.rsq,
rsq_sums_predictor = rst.x.rsq.sums,
int_predictor = rst.x.intercept,
slp_predictor = rst.x.slp,
p_predictor = rst.x.p,
resid_predictor = brck.x.resids,
r_response = rst.y.r,
rsq_response = rst.y.rsq,
int_response = rst.y.intercept,
slp_response = rst.y.slp,
p_response = rst.y.p,
resid_response = brck.y.resids)
if (write.out) {
writeEot(out, path.out = path.out, prefix = prefix, ...)
df.name <- paste(prefix, "eot_locations.csv", sep = "_")
if (n == 1) {
write.table(location.df, col.names = TRUE,
paste(path.out, df.name, sep = "/"),
row.names = FALSE, append = FALSE, sep = ",")
} else {
write.table(location.df, col.names = FALSE,
paste(path.out, df.name, sep = "/"),
row.names = FALSE, append = TRUE, sep = ",")
}
rm(list = c("eot.ts",
"maxxy",
"location.df",
"expl.var",
"rst.x.r",
"rst.x.rsq",
"rst.x.rsq.sums",
"rst.x.intercept",
"rst.x.slp",
"rst.x.p",
"brck.x.resids",
"rst.y.r",
"rst.y.rsq",
"rst.y.intercept",
"rst.y.slp",
"rst.y.p",
"brck.y.resids"))
gc()
}
return(out)
}
|
freqpolygon( ~ Exercise, data = StudentSurvey, breaks = seq(0, 45, by = 4), lwd = 3,
par.settings = col.whitebg(),
panel = function(x, ...) {
panel.xhistogram(x, ...);
panel.freqpolygon(x, ...)}
)
|
transform_to_min_spanning_tree <- function(graph) {
fcn_name <- get_calling_fcn()
if (graph_object_valid(graph) == FALSE) {
emit_error(
fcn_name = fcn_name,
reasons = "The graph object is not valid")
}
igraph <- to_igraph(graph)
igraph_mst <- igraph::mst(igraph)
from_igraph(igraph_mst)
}
|
initStrategy <- function(strategy,
portfolio,
symbols,
parameters = NULL,
get.Symbols = FALSE,
init.Portf = TRUE,
init.Acct = TRUE,
init.Orders = TRUE,
unique = TRUE,
...) {
if (!is.strategy(strategy)) {
strategy<-try(getStrategy(strategy))
if(inherits(strategy,"try-error"))
stop ("You must supply an object or the name of an object of type 'strategy'.")
store=TRUE
}
if(!hasArg(currency)){
if(!is.null(strategy$currency)) currency <- strategy$currency
else currency<-'USD'
}
if(isTRUE(get.Symbols)){
getsyms <- NULL
for (sym in symbols) {
if(!is.instrument(getInstrument(sym,silent=TRUE))) {
instrument.auto(sym, currency=currency)
}
tmp <- try(get(sym,pos=env),silent=TRUE)
if (inherits(tmp, 'try-error')) getsyms <- c(getsyms, sym)
}
if (!is.null(getsyms)) getSymbols(getsyms,from=initDate, ...=...)
}
if(isTRUE(init.Portf) & !isTRUE(is.portfolio(portfolio))){
if(hasArg(portfolio)) portfolio<-portfolio else portfolio<-strategy$name
initPortf(name=portfolio, symbols=symbols, currency=currency, ...=...)
}
if(isTRUE(init.Acct)){
if(hasArg(account)) account<-account else account<-portfolio
if(!isTRUE(is.account(account))) initAcct(name=account, portfolios=portfolio, currency=currency, ...=...)
}
if(isTRUE(init.Orders)){
initOrders(portfolio=portfolio, symbols=symbols, ...=...)
}
for (init_o in strategy$init){
if(is.function(init_o$name)) {
init_oFun <- init_o$name
} else {
if(exists(init_o$name, mode="function")) {
init_oFun <- get(init_o$name, mode="function")
} else {
message("Skipping initialization function ", init_o$name,
" because there is no function by that name to call.")
}
}
if(!isTRUE(init_o$enabled)) next()
.formals <- formals(init_o$name)
.formals <- modify.args(.formals, init_o$arguments, dots=TRUE)
.formals <- modify.args(.formals, parameters, dots=TRUE)
.formals <- modify.args(.formals, NULL, ..., dots=TRUE)
.formals$`...` <- NULL
do.call(init_oFun, .formals)
}
}
add.init <- function(strategy, name, arguments, parameters=NULL, label=NULL, ..., enabled=TRUE, indexnum=NULL, store=FALSE) {
if (!is.strategy(strategy)) {
strategy<-try(getStrategy(strategy))
if(inherits(strategy,"try-error"))
stop ("You must supply an object or the name of an object of type 'strategy'.")
store=TRUE
}
tmp_init<-list()
tmp_init$name<-name
if(is.null(label)) label = paste(name,"ind",sep='.')
tmp_init$label<-label
tmp_init$enabled=enabled
if (!is.list(arguments)) stop("arguments must be passed as a named list")
tmp_init$arguments<-arguments
if(!is.null(parameters)) tmp_init$parameters = parameters
if(length(list(...))) tmp_init<-c(tmp_init,list(...))
if(!hasArg(indexnum) | (hasArg(indexnum) & is.null(indexnum))) indexnum = length(strategy$inits)+1
tmp_init$call<-match.call()
class(tmp_init)<-'strat_init'
strategy$init[[indexnum]]<-tmp_init
if (store) assign(strategy$name,strategy,envir=as.environment(.strategy))
else return(strategy)
}
initSymbol <- function(strategy, symbol, ...){
getSymbols(symbol, env = .GlobalEnv)
init_s <- strategy$init_symbol
if(is.function(init_s$name)) {
init_sFun <- init_s$name
} else {
if(exists(init_s$name, mode="function")) {
init_sFun <- get(init_s$name, mode="function")
} else {
message("Initialization function ", init_s$name, " not found. Skipping")
return()
}
}
if(!isTRUE(init_s$enabled)) return()
.formals <- formals(init_s$name)
.formals <- modify.args(.formals, init_s$arguments, dots=TRUE)
.formals <- modify.args(.formals, NULL, ..., dots=TRUE)
.formals$`...` <- NULL
do.call(init_sFun, .formals)
}
|
expected <- eval(parse(text="structure(numeric(0), .Dim = c(0L, 0L))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(numeric(0), .Dim = c(0L, 0L)))"));
do.call(`cosh`, argv);
}, o=expected);
|
bar2.plot<-function(x, y, file, var.label.x, var.label.y, perc, byrow, ...)
{
kk<-!is.na(x) & !is.na(y)
x<-x[kk]
y<-y[kk]
dots.args <- eval(substitute(alist(...)))
onefile <- FALSE
if (!is.null(dots.args$onefile))
onefile<- dots.args$onefile
if (is.null(file))
{}
else {
if (length(grep("bmp$",file)))
bmp(file,...)
if (length(grep("png$",file)))
png(file,...)
if (length(grep("tif$",file)))
tiff(file,...)
if (length(grep("jpg$",file)))
jpeg(file,...)
if (length(grep("pdf$",file)))
if (!onefile)
pdf(file,...)
}
pp <- table(x, y)
ylab <- "Freq (n)"
main <- paste("Barplot of '",var.label.x,"' by '",var.label.y,"'", sep="")
if (!is.na(byrow) & byrow) {
main <- paste("Barplot of '",var.label.y,"' by '",var.label.x,"'", sep="")
pp <- table(y, x)
}
if (perc){
if (!is.na(byrow))
pp <- prop.table(pp, margin=2)*100
else
pp <- prop.table(pp, margin=NULL)*100
ylab <- "Freq (%)"
}
if (!is.na(byrow) & byrow){
barplot(pp, beside=TRUE, main=main, ylim=c(0,max(pp)*1.3),ylab=ylab,col=rainbow(nlevels(y)))
legend("topleft",levels(y),fill=rainbow(nlevels(y)),bty="n")
}else{
barplot(pp, beside=TRUE, main=main, ylim=c(0,max(pp)*1.3),ylab=ylab,col=rainbow(nlevels(x)))
legend("topleft",levels(x),fill=rainbow(nlevels(x)),bty="n")
}
if (!is.null(file) && (length(grep("pdf$",file))==0 || !onefile))
dev.off()
}
|
plotCoef.enetLTS <- function(object,vers=c("reweighted","raw"),
colors=NULL,...){
nam <- NULL
if(is.null(colors)){
colors <- list(bars="
background="
scores="
badouts="darkred", modouts="black")
}
family <- object$inputs$family
vers <- match.arg(vers)
if (isTRUE(object$inputs$intercept)){
coefficients <- c(object$a0,object$coefficients)
raw.coefficients <- c(object$a00,object$raw.coefficients)
} else {
coefficients <- object$coefficients
raw.coefficients <- object$raw.coefficients
}
if (vers=="reweighted"){
plotcoefs <- data.frame(coefficients=coefficients,nam=names(coefficients),
llim=coefficients,ulim=coefficients)
plotcoefs$nam <- factor(plotcoefs$nam, levels=names(coefficients))
if (family=="binomial"){
plot <- ggplot(plotcoefs,aes(nam,coefficients))+geom_bar(stat="identity",size=3,fill=colors$bars,position="identity")+
labs(title=paste(names(object$inputs$yy),"enetLTS coefficients for logistic regression"))
} else if (family=="gaussian"){
plot <- ggplot(plotcoefs,aes(nam,coefficients))+geom_bar(stat="identity",size=3,fill=colors$bars,position="identity")+
labs(title=paste(names(object$inputs$yy),"enetLTS coefficients for regression"))
}
plot <- plot + theme(panel.background=element_rect(fill=colors$background),
plot.title=element_text(size=rel(1),face="bold"),
axis.text.x=element_text(angle=-90),axis.title.x=element_blank(),
axis.title.y=element_blank())
print(plot)
} else if (vers=="raw"){
raw.plotcoefs <- data.frame(raw.coefficients=raw.coefficients,nam=names(raw.coefficients),
llim=raw.coefficients,ulim=raw.coefficients)
raw.plotcoefs$nam <- factor(raw.plotcoefs$nam, levels=names(raw.coefficients))
if (family=="binomial"){
raw.plot <- ggplot(raw.plotcoefs,aes(nam,raw.coefficients))+geom_bar(stat="identity",size=3,fill=colors$bars,position="identity")+
labs(title=paste(names(object$inputs$yy),"enetLTS raw coefficients for logistic regression"))
} else if (family=="gaussian"){
raw.plot <- ggplot(raw.plotcoefs,aes(nam,raw.coefficients))+geom_bar(stat="identity",size=3,fill=colors$bars,position="identity")+
labs(title=paste(names(object$inputs$yy),"enetLTS raw coefficients for regression"))
}
raw.plot <- raw.plot + theme(panel.background=element_rect(fill=colors$background),
plot.title=element_text(size=rel(1),face="bold"),
axis.text.x=element_text(angle=-90),axis.title.x=element_blank(),
axis.title.y=element_blank())
print(raw.plot)
}
}
|
sqndwdecomp <-
function (x, J, filter.number, family)
{
lx <- length(x)
ans <- matrix(0, nrow = J, ncol = length(x))
dw <- hwwn.dw(J, filter.number, family)
longest.support <- length(dw[[J]])
scale.shift <- 0
for (j in 1:J) {
l <- length(dw[[j]])
init <- (filter.number - 1) * (lx - 2^j)
for (k in 1:lx) {
yix <- seq(from = k, by = 1, length = l)
yix <- ((yix - 1)%%lx) + 1
ans[j, k] <- sum(x[yix] * dw[[j]]^2)
}
if (filter.number == 1)
scale.shift <- 0
else {
scale.shift <- (filter.number - 1) * 2^j
}
ans[j, ] <- guyrot(ans[j, ], scale.shift)
}
return(ans)
}
|
EEw1s3 <- function(des='',randomize=FALSE) {
if (des=='') {
cat(" ", "\n")
cat("Catalog of D-efficient Estimation Equivalent RS","\n")
cat(" Designs for (1 wp factor and 3 sp factors) ","\n")
cat(" ", "\n")
cat(" Jones and Goos, JQT(2012) pp. 363-374","\n")
cat(" ", "\n")
cat(format("Design Name",width=11),format("whole plots",width=11),format("sub-plots/whole plot",width=21),"\n")
cat("----------------------------------------","\n")
cat(format("EE18R6WP", width=11),format(" 6",width=11),format(" 3",width=21),"\n")
cat(format("EE20R4WP", width=11),format(" 4",width=11),format(" 5",width=21),"\n")
cat(format("EE20R5WP", width=11),format(" 5",width=11),format(" 4",width=21),"\n")
cat(format("EE24R4WP", width=11),format(" 4",width=11),format(" 6",width=21),"\n")
cat(format("EE24R6WP", width=11),format(" 6",width=11),format(" 4",width=21),"\n")
cat(format("EE30R6WP", width=11),format(" 6",width=11),format(" 5",width=21),"\n")
cat(format("EE36R6WP", width=11),format(" 6",width=11),format(" 6",width=21),"\n")
cat(" ","\n")
cat("==> to retrieve a design type EEw1s3('EE18R6WP') etc.","\n")
} else if (des=='EE15R5WP') {v <- c(241, 391, 121, 132, 42, 147, 218, 98, 293, 374, 74, 314, 320, 305, 5)
Full <-expand.grid(WP=c(1:5),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:15)
if (randomize==TRUE) {
o<-c(rep(sample(1:5),each=3))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:15)
s<-3
w<-5
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE16R4WP') { v <- c(17, 161, 209, 257, 74, 314, 26, 218, 243, 99, 291, 3, 312, 252, 120, 72)
Full <-expand.grid(WP=c(1:4),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:16)
if (randomize==TRUE) {
o<-c(rep(sample(1:4),each=4))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:16)
s<-4
w<-4
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE18R6WP') { v <- c(316, 106, 400, 205, 142, 37, 521, 185, 437, 445, 151, 235, 551, 5, 551, 55, 391, 286)
Full <-expand.grid(WP=c(1:7),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:18)
if (randomize==TRUE) {
o<-c(rep(sample(1:6),each=3))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:18)
s<-3
w<-6
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE20R4WP') {WP<-c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4)
w1<-c(-1.0000, -1.0000, -1.0000, -1.0000, -1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, -0.2478, -0.2478, -0.2478, -0.2478, -0.2478)
s1<-c(-1, -1, 1, 1, -1, 1, -1, 0, 1, -1, -1, 0, -1, 1, 1, -1, 1, -1, 1, 0)
s2<-c(0, 1, 1, -1, -1, 0, 1, -1, 1, -1, 0, 1, -1, 1, -1, -1, 1, 1, -1, 0)
s3<-c(-1, 1, -1, 1, 0, -1, 0, -1, 1, 1, 1, 1, -1, -1, 0, 1, 1, -1, -1, 0)
EE<-data.frame(WP,w1,s1,s2,s3)
if (randomize==TRUE) {
o<-c(rep(sample(1:4),each=5))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:20)
s<-5
w<-4
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE20R5WP') {v <- c(391, 91, 31, 271, 2, 362, 122, 302, 88, 238, 298, 13, 399, 204, 39, 279, 15, 330, 120, 180)
Full <-expand.grid(WP=c(1:5),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:20)
if (randomize==TRUE) {
o<-c(rep(sample(1:5),each=4))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:20)
s<-4
w<-5
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE24R4WP') {v <- c(221, 17, 77, 161, 317, 29, 290, 2, 254, 242, 206, 86, 315, 63, 231, 291, 75, 111, 228, 108, 288, 144, 300, 12)
Full <-expand.grid(WP=c(1:4),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:24)
if (randomize==TRUE) {
o<-c(rep(sample(1:4),each=6))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:24)
s<-6
w<-4
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE24R6WP') {v <- c(1, 145, 361, 433, 80, 404, 242, 242, 471, 39, 327, 111, 412, 412, 250, 88, 485, 53, 179, 125, 432, 396, 72, 270)
Full <-expand.grid(WP=c(1:6),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:24)
if (randomize==TRUE) {
o<-c(rep(sample(1:6),each=4))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:24)
s<-4
w<-6
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE25R5WP') {v <- c(136, 91, 376, 31, 346, 402, 282, 207, 42, 102, 233, 398, 278, 83, 113, 49, 364, 259, 19, 304, 210, 135,
375, 315, 15)
Full <-expand.grid(WP=c(1:5),w1=c(-1,0,1),s1=c(-1,0,1),s2=c(-1,0,1),s3=c(-1,0,1))
EE <- Full[v, ]
rownames(EE)<- c(1:25)
if (randomize==TRUE) {
o<-c(rep(sample(1:5),each=5))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:25)
s<-5
w<-5
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE30R6WP') {WP<-c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6 )
w1<-c(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, -1, -1, -1,
-1, -1, 1, 1, 1, 1, 1)
s1<-c(0.1467, 0.4372, -0.9533, 0.9523, -0.8610, 0.7324, 0.6926, -0.8613, 0.1524, -0.9942, -1.0000,
-0.1228, 0.5316, -0.6869, 1.0000, 0.8588, -0.9366, 1.0000, 0.8337, 0.9420, -0.8481, 0.6643,
-0.8878, 0.8998, -0.1064, 1.0000, 0.1705, -0.7848, 0.9997, -0.8476)
s2<-c(0.9970, 0.7162, 0.0875, -0.8638, -0.9352, 0.8870, -0.7992, 0.8500, 0.0558, -0.9919, 0.9949,
-1.0000, 0.5110, -0.8674, 0.3632, -0.6348, 1.0000, -0.8105, 0.9934, -0.8724, 0.8085, -0.8940,
-0.8715, 0.9606, -0.0019, 0.8828, 1.0000, 0.9896, -0.9783, 0.8635)
s3<-c(-0.9659, 0.7165, 1.0000, 0.2234, -0.8596, -0.8207, 0.9175, 0.9220, 0.0277, -0.9321, -0.0126,
-1.0000, -0.7197, 0.8467, 1.0000, -1.0000, -1.0000, 0.9976, 0.5478, -0.9948, -0.8287, -0.8866,
0.9148, 0.9609, -0.0459, -0.9117, 0.9884, -0.8769, 0.9997, -0.9999)
EE<-data.frame(WP,w1,s1,s2,s3)
if (randomize==TRUE) {
o<-c(rep(sample(1:6),each=5))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:30)
s<-5
w<-6
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else if(des=='EE36R6WP') {WP<-c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6 )
w1<-c(0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0,
0, -1, -1, -1, -1, -1, -1)
s1<-c(0.53908, 0.76183, 0.85120, -0.65988, -0.94260, 0.96642, 0.47852, 0.53728, 0.32607,
-0.81904, -1.00000, -0.92735, 0.50225, -0.19625, -0.60576, 1.00000, 1.00000, 0.08923,
-0.58067, -0.16993, -0.94720, -0.96033, 0.92974, 0.32387, 0.92279, -1.00000, 0.87572,
-0.45357, 0.17111, 1.00000, -0.40728, -0.82531, -1.00000, -0.57218, 0.70431, 0.69594)
s2<-c(-0.79936, 0.89476, 0.42489, 0.63926, 0.88700, -0.37711, 0.88231, -0.76266, 0.16716,
-0.74521, -0.50252, 0.90081, -0.11153, 0.46263, 0.85752, -0.02876, 0.00745, 0.35810,
-0.93614, 1.00000, -0.10915, -0.20044, -0.63579, 0.82141, 0.39575, 0.65611, -1.00000,
1.00000, 0.00885, 0.60873, 0.90481, 0.28202, -0.54116, -0.71167, -0.80632, 0.81221)
s3<-c(-0.92414, 0.88755, -0.57336, 0.66455, 0.25221, -0.03008, -0.24680, 0.10316, 0.80028,
-0.72825, 1.00000, -0.66508, -0.75278, 0.70306, -0.60648, 0.89481, 0.90464, 1.00000,
-0.39641, 0.12134, -0.61963, 0.98790, 0.83953, -0.66942, 0.20694, 0.35728, -0.50765,
1.00000, -1.00000, 0.22016, -0.02109, 0.76701, -0.79858, -0.00717, 1.00000, -0.67686)
EE<-data.frame(WP,w1,s1,s2,s3)
if (randomize==TRUE) {
o<-c(rep(sample(1:6),each=6))
EE<-EE[order(order(o)), ]
rownames(EE)<-c(1:36)
s<-6
w<-6
rowp<-c(sample(1:s))
for (i in 1:(w-1)) {rowp<-c(rowp,i*s+sample(1:s))}
EE<-EE[order(rowp), ]
}
return(EE)
} else cat(" Design name misspelled-Enter EEw1s3( ) to display list of names","\n")
}
|
print_parameters <- function(x,
...,
split_by = c("Effects", "Component", "Group", "Response"),
format = "text",
parameter_column = "Parameter",
keep_parameter_column = TRUE,
remove_empty_column = FALSE,
titles = NULL,
subtitles = NULL) {
obj <- list(...)
att <- do.call(c, .compact_list(lapply(obj, function(i) {
a <- attributes(i)
a$names <- a$class <- a$row.names <- NULL
a
})))
att <- att[!duplicated(names(att))]
cp <- if (!inherits(x, "clean_parameters")) {
clean_parameters(x)
} else {
x
}
obj <- Reduce(
function(x, y) {
if (parameter_column != "Parameter" && parameter_column %in% colnames(y) && !"Parameter" %in% colnames(y)) {
colnames(y)[colnames(y) == parameter_column] <- "Parameter"
}
merge_by <- unique(c("Parameter", intersect(colnames(y), intersect(c("Effects", "Component", "Group", "Response"), colnames(x)))))
merge(x, y, all.x = FALSE, by = merge_by, sort = FALSE)
},
c(list(cp), obj)
)
if (.is_empty_object(split_by)) {
return(obj)
}
split_by <- split_by[split_by %in% colnames(obj)]
f <- lapply(split_by, function(i) {
if (i %in% colnames(obj)) obj[[i]]
})
names(f) <- split_by
out <- split(obj, f)
out <- .compact_list(lapply(out, function(i) {
if (nrow(i) > 0) i
}))
names(out) <- list_names <- gsub("(.*)\\.$", "\\1", names(out))
has_zeroinf <- any(grepl("zero_inflated", names(out), fixed = TRUE))
out <- lapply(names(out), function(i) {
title1 <- title2 <- ""
element <- out[[i]]
parts <- unlist(strsplit(i, ".", fixed = TRUE))
for (j in 1:length(parts)) {
if (parts[j] %in% c("fixed", "random") || (has_zeroinf && parts[j] %in% c("conditional", "zero_inflated"))) {
tmp <- switch(parts[j],
"fixed" = "Fixed effects",
"random" = "Random effects",
"dispersion" = "Dispersion",
"conditional" = "(conditional)",
"zero_inflated" = "(zero-inflated)"
)
title1 <- paste0(title1, " ", tmp)
} else if (!parts[j] %in% c("conditional", "zero_inflated")) {
tmp <- switch(parts[j],
"simplex" = "(monotonic effects)",
parts[j]
)
title2 <- paste0(title2, " ", tmp)
}
}
.effects <- unique(element$Effects)
.component <- unique(element$Component)
.group <- unique(element$Group)
columns_to_remove <- c("Effects", "Component", "Cleaned_Parameter")
if (.n_unique(.group) == 1) {
columns_to_remove <- c(columns_to_remove, "Group")
} else {
.group <- NULL
}
keep <- setdiff(colnames(element), columns_to_remove)
element <- element[, c("Cleaned_Parameter", keep)]
if ("pretty_names" %in% names(att)) {
attr(element, "pretty_names") <- stats::setNames(att$pretty_names[element$Parameter], element$Cleaned_Parameter)
}
if (!isTRUE(keep_parameter_column)) {
element$Parameter <- NULL
colnames(element)[colnames(element) == "Cleaned_Parameter"] <- "Parameter"
}
if (isTRUE(remove_empty_column)) {
for (j in colnames(element)) {
if (all(is.na(element[[j]])) || (is.character(element[[j]]) && all(element[[j]] == ""))) {
element[[j]] <- NULL
}
}
}
if (is.null(format) || format == "text") {
title_prefix <- "
} else {
title_prefix <- ""
}
title1 <- .capitalize(title1)
title2 <- .capitalize(title2)
attr(element, "main_title") <- .trim(title1)
attr(element, "sub_title") <- .trim(title2)
if (is.null(format) || format == "text") {
attr(element, "table_caption") <- c(paste0(title_prefix, .trim(title1)), "blue")
attr(element, "table_subtitle") <- c(.trim(title2), "blue")
} else {
attr(element, "table_caption") <- .trim(title1)
attr(element, "table_subtitle") <- .trim(title2)
}
attr(element, "Effects") <- .effects
attr(element, "Component") <- .component
attr(element, "Group") <- .group
element
})
if (!is.null(titles) && length(titles) <= length(out)) {
for (i in 1:length(titles)) {
attr(out[[i]], "table_caption") <- c(titles[i], "blue")
}
}
if (!is.null(subtitles) && length(subtitles) <= length(out)) {
for (i in 1:length(subtitles)) {
attr(out[[i]], "table_subtitle") <- c(subtitles[i], "blue")
}
}
att$pretty_names <- NULL
attr(out, "additional_attributes") <- att
names(out) <- list_names
out
}
|
getFrequencyBasedPrior <- function(x, showplot=FALSE){
z <- fft(x)
zmod <- Mod(z)
zmodEffective <- zmod[-1]
zmodEffective <- zmodEffective[1:(length(zmodEffective)/2)]
if(showplot) {
plot(as.numeric(x), xlab="index", ylab="x")
names(zmod) <- NULL
plot(zmod, col=c(1,rep(2, (length(zmod)-1)/2),rep(1, (length(zmod)-1)/2)))
title("modulus of fft", line=7)
names(zmodEffective) <- 1:length(zmodEffective)
upperQuarter = sort(zmodEffective)[ceiling(length(zmodEffective) * 0.75)]
lowerQuarter = sort(zmodEffective)[floor(length(zmodEffective) * 0.25)]
iqr = upperQuarter - lowerQuarter
outliers = zmodEffective[zmodEffective > upperQuarter + 1.5 * iqr]
if (length(outliers) == 0) {
freq <- which.max(zmodEffective)
abline(v=1+freq, col=4)
} else {
outliers <- outliers[outliers > median(zmodEffective)]
whichOutliers <- which(zmodEffective %in% outliers)
abline(v=1+whichOutliers, col=4)
freq <- max(whichOutliers)
}
meanFactor <- 0.5/freq
legend("top", c("range of frequencies with large loadings",
"modulus of effective frequency loading"),
lty=c(1, NA), pch=c(NA, 1), col=c(4, 2))
msg <- paste0("WANT: frequency with largest loading = ", which.max(zmodEffective),
", corresponding prior factor = ", round(0.5/which.max(zmodEffective), digits = 4))
freq_wtd <- weighted.mean(whichOutliers, outliers^2)
msg <- paste0(msg, "\nWANT: mod^2 weighted average frequency with large loadings = ", freq_wtd, ", corresponding prior factor = ", round(0.5/freq_wtd, digits = 4))
freq_wtd <- weighted.mean(1:length(zmodEffective), zmodEffective^2)
msg <- paste0(msg, "\nWANT: mod^2 weighted average frequency among all = ", freq_wtd, ", corresponding prior factor = ", round(0.5/freq_wtd, digits = 4))
period_wtd <- weighted.mean(0.5/whichOutliers, outliers^2)
msg <- paste0(msg, "\nWANT: mod^2 weighted average half periodicity (i.e. prior factor) with large loadings = ", period_wtd)
period_wtd <- weighted.mean(0.5/(1:length(zmodEffective)), zmodEffective^2)
msg <- paste0(msg, "\nWANT: mod^2 weighted average half periodicity (i.e. prior factor) among all = ", period_wtd)
msg <- paste0(msg, "\nCURRENT: highest frequency with large loadings = ", freq, ", corresponding prior factor = ", round(0.5/freq, digits = 4))
mtext(msg)
}
freq <- weighted.mean(1:length(zmodEffective), zmodEffective^2)
meanFactor <- 0.5 / freq
sdFactor <- (1 - meanFactor) / 3
c(meanFactor=meanFactor, sdFactor=sdFactor)
}
|
SpaceFilling <-
function(asch){
fun1<-function() {
n<-readline("Number of lines of association schemes array :\n")
l<-readline("Number of columns of association schemes array :\n")
n<-as.integer(n);l<-as.integer(l)
return(c(n,l))}
fun2<-function() {
n<-readline("Number of lines of association schemes array :\n")
l<-readline("Number of columns of association schemes array :\n")
w<-readline("Number of the association scheme arrays :\n")
n<-as.integer(n);l<-as.integer(l);w<-as.integer(w)
return(c(n,l,w))}
if (asch == "Div"){
V<-fun1();n<-V[1];l<-V[2]
s<-n*l;A<-matrix(1:s, ncol = V[2], byrow=TRUE)
SF<-matrix(ncol=s,nrow=s)
for (d in 1:s) {
SF[d,d]<-1
for (dd in 1:s){
D<-which(A==d); d1<-D%%n ; if (d1==0){d1<-n};DD<-which(A==dd); d2<-DD%%n ; if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
else {SF[d,dd]<-2;SF[dd,d]<-2}}}}
if (asch == "Rect"){
V<-fun1();n<-V[1];l<-V[2];s<-n*l;A<-matrix(1:s, ncol =l, byrow=TRUE)
SF<-matrix(ncol=s,nrow=s)
for (d in 1:s) {
SF[d,d]<-1
for (dd in 1:s){
B<-t(A)
D<-which(A==d); d1<-D%%n ; if (d1==0){d1<-n};DD<-which(A==dd); d2<-DD%%n
if (d2==0){d2<-n}
D1<-which(B==d); d11<-D1%%l ; if (d11==0){d11<-l};DD1<-which(B==dd); d12<-DD1%%l
if (d12==0){d12<-l}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
if (is.na(SF[d,dd])==TRUE){
if (d11==d12) {SF[d,dd]<-2;SF[dd,d]<-2}}}}
for (d in 1:s) {
for (dd in 1:s){
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-3;SF[dd,d]<-3}}}}
if (asch == "Nestdiv"){
V<-fun2();n<-V[1];l<-V[2];w<-V[3]
s<-l*n;A<-NULL;S<-l*n*w
SF<-matrix(ncol=S,nrow=S)
for (i in 1:w){
A[[i]]<-matrix(1:s, ncol=l, byrow=TRUE)
z<-(i-1)*s
A[[i]]<-A[[i]]+z};B<-Reduce("rbind",A)
for (i in 1:w) {
a<-A[[i]];mi<-min(a);ma<-max(a)
for (d in mi:ma){
for (dd in mi:ma){
D<-which(a==d); d1<-D%%n ; if (d1==0){d1<-n}
DD<-which(a==dd); d2<-DD%%n ; if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
else {SF[d,dd]<-2;SF[dd,d]<-2}}}}
for (d in 1:S) {
for (dd in 1:S){
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-3;SF[dd,d]<-3}}}}
if (asch == "RightAng"){
V<-fun2();n<-V[1];l<-V[2];w<-V[3];s<-l*n;A<-NULL;S<-l*n*w
SF<-matrix(ncol=S,nrow=S)
for (i in 1:w){
A[[i]]<-matrix(1:s, ncol=l, byrow=TRUE)
z<-(i-1)*s
A[[i]]<-A[[i]]+z};B<-Reduce("rbind",A)
for (i in 1:w) {
a<-A[[i]];mi<-min(a);ma<-max(a)
for (d in mi:ma){
for (dd in mi:ma){
D<-which(a==d); d1<-D%%n ; if (d1==0){d1<-n}
DD<-which(a==dd); d2<-DD%%n ; if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
else {SF[d,dd]<-2;SF[dd,d]<-2}}
for (i in 1:w) {
if (i < w){
b<-A[[i+1]];mib<-min(b);mab<-max(b)
for (db in mib:mab){
DB<-which(b==db); db2<-DB%%n ; if (db2==0){db2<-n}
if (d1==db2) {if (is.na(SF[d,db])==TRUE){
SF[d,db]<-3;SF[db,d]<-3}}
else {if (is.na(SF[d,db])==TRUE){
SF[d,db]<-4;SF[db,d]<-4}}}}}}}}
if (asch == "GrectRightAng4"){
V<-fun2();n<-V[1];l<-V[2];w<-V[3];s<-l*n;A<-NULL;S<-l*n*w;SF<-matrix(ncol=S,nrow=S)
for (i in 1:w){
A[[i]]<-matrix(1:s, ncol=l, byrow=TRUE);z<-(i-1)*s
A[[i]]<-A[[i]]+z};B<-Reduce("rbind",A)
for (i in 1:w) {
a<-A[[i]];mi<-min(a);ma<-max(a)
B<-t(a)
for (d in mi:ma){
for (dd in mi:ma){
D<-which(a==d); d1<-D%%n ; if (d1==0){d1<-n}
DD<-which(a==dd); d2<-DD%%n ; if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
D1<-which(B==d); d11<-D1%%n ; if (d11==0){d11<-n}
DD1<-which(B==dd); d21<-DD1%%n ; if (d21==0){d21<-n}
if (d11==d21)
if (is.na(SF[d,dd])==TRUE){
{SF[d,dd]<-2;SF[dd,d]<-2}}
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-3;SF[dd,d]<-3}}}}
for (d in 1:S) {
for (dd in 1:S){
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-4;SF[dd,d]<-4}}}}
if (asch == "GrectRightAng5"){
V<-fun2();n<-V[1];l<-V[2];w<-V[3];s<-l*n;A<-NULL;S<-l*n*w;SF<-matrix(ncol=S,nrow=S)
for (i in 1:w){
A[[i]]<-matrix(1:s, ncol=l, byrow=TRUE);z<-(i-1)*s
A[[i]]<-A[[i]]+z};B<-Reduce("rbind",A);SF<-matrix(ncol=S,nrow=S)
for (i in 1:w) {
a<-A[[i]];mi<-min(a);ma<-max(a);B<-t(a)
for (d in mi:ma){
for (dd in mi:ma){
D<-which(a==d); d1<-D%%n ; if (d1==0){d1<-n}
DD<-which(a==dd); d2<-DD%%n ; if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
D1<-which(B==d); d11<-D1%%n ; if (d11==0){d11<-n}
DD1<-which(B==dd); d21<-DD1%%n ; if (d21==0){d21<-n}
if (d11==d21)
if (is.na(SF[d,dd])==TRUE){
{SF[d,dd]<-2;SF[dd,d]<-2}}
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-3;SF[dd,d]<-3}}
for (i in 1:w) {
if (i < w){
bb<-A[[i+1]];mib<-min(bb);mab<-max(bb)
for (db in mib:mab){
DB<-which(bb==db); db2<-DB%%n ; if (db2==0){db2<-n}
if (d1==db2) {if (is.na(SF[d,db])==TRUE){SF[d,db]<-4;SF[db,d]<-4}}
else {if (is.na(SF[d,db])==TRUE){SF[d,db]<-5;SF[db,d]<-5}}}}}}}}
if (asch == "GrectRightAng7"){
V<-fun2();n<-V[1];l<-V[2];w<-V[3];s<-l*n;S<-l*n*w;A<-NULL
for (i in 1:w){
A[[i]]<-matrix(1:s, ncol=l, byrow=TRUE);z<-(i-1)*s
A[[i]]<-A[[i]]+z};B<-Reduce("rbind",A);SF<-matrix(ncol=S,nrow=S)
for (i in 1:w) {
a<-A[[i]];mi<-min(a);ma<-max(a);B<-t(a)
for (d in mi:ma){
for (dd in mi:ma){
D<-which(a==d); d1<-D%%n ; if (d1==0){d1<-n};DD<-which(a==dd); d2<-DD%%n
if (d2==0){d2<-n}
if (d1==d2) {SF[d,dd]<-1;SF[dd,d]<-1}
D1<-which(B==d); d11<-D1%%n ; if (d11==0){d11<-n};DD1<-which(B==dd);d21<-DD1%%n
if (d21==0){d21<-n}
if (d11==d21)
if (is.na(SF[d,dd])==TRUE){
{SF[d,dd]<-2;SF[dd,d]<-2}}
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-3;SF[dd,d]<-3}}
for (i in 1:w) {
if (i < w){
bb<-A[[i+1]];mib<-min(bb);mab<-max(bb)
for (db in mib:mab){
B2<-t(bb);DB<-which(bb==db); db2<-DB%%n ; if (db2==0){db2<-n}
n1<-which(B2==db); n21<-n1%%n ; if (n21==0){n21<-n}
if (D==DB) {if (is.na(SF[d,db])==TRUE){SF[d,db]<-4;SF[db,d]<-4}}
if (d11==db2) {if (is.na(SF[d,db])==TRUE){SF[d,db]<-5;SF[db,d]<-5}}
if (d1==n21)
if (is.na(SF[d,db])==TRUE){
{SF[d,db]<-6;SF[db,d]<-6}}}}}}}
for (d in 1:S) {
for (dd in 1:S){
if (is.na(SF[d,dd])==TRUE){
SF[d,dd]<-7;SF[dd,d]<-7}}}}
NN<-max(SF)
RR<-dim(SF)[1]
return(list(SFDesign=SF,Runs=RR,Factors=RR,Levels=NN))}
|
plindleylogarithmic <- function(x , lambda , theta , log.p = FALSE)
{
stopifnot(theta < 1,theta > 0,lambda > 0,x > 0,is.logical(log.p))
phi = theta * (1 - (lambda + 1 + lambda * x) / (lambda + 1) * exp(-lambda * x))
aphi = -log(1 - phi)
atheta = -log(1 - theta)
cdf = aphi / atheta
if(log.p) return(log(cdf)) else return(cdf)
}
dlindleylogarithmic <- function(x, lambda, theta)
{
stopifnot(theta < 1,theta > 0,lambda > 0,x > 0)
phi = theta * (1 - (lambda + 1 + lambda * x) / (lambda + 1) * exp(-lambda * x))
adphi = 1 / (1 - phi)
atheta = -log(1 - theta)
rest = theta * lambda ** 2 / ((lambda + 1) * atheta) * (1 + x) * exp(-lambda * x)
pdf = rest * adphi
return(pdf)
}
hlindleylogarithmic <- function(x, lambda, theta)
{
stopifnot(theta < 1,theta > 0,lambda > 0,x > 0)
phi = theta * (1 - (lambda + 1 + lambda * x) / (lambda + 1) * exp(-lambda * x))
adphi = 1 / (1 - phi)
aphi = -log(1 - phi)
atheta = -log(1 - theta)
rest = theta * lambda ** 2 / (lambda + 1) * (1 + x) * exp(-lambda * x)
hazard = rest * adphi / (atheta - aphi)
return(hazard)
}
qlindleylogarithmic <- function(p, lambda, theta)
{
stopifnot(theta < 1,theta > 0,lambda > 0)
atheta = -log(1 - theta)
t0 = 1 - exp(-p * atheta)
t1 = t0 / theta - 1
t2 = (lambda + 1) / exp(lambda + 1) * t1
x = - lamW::lambertWm1(t2) / lambda - 1 / lambda -1
return(x)
}
rlindleylogarithmic <- function(n, lambda, theta)
{
stopifnot(theta < 1,theta > 0,lambda > 0,n %% 1==0)
y=stats::runif(n, min=0, max = 1)
randdata=qlindleylogarithmic(y, lambda, theta)
return(randdata)
}
|
isNonZeroNumberOrNaVector <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = NA, zeroAllowed = FALSE, negativeAllowed = TRUE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = TRUE, nanAllowed = FALSE, infAllowed = FALSE, message = message, argumentName = argumentName)
}
|
LKSN_test<-function(x,trend=c("none","linear"),tau=0.2,lmax=0,simu=0,M=10000)
{
trend<-match.arg(trend,c("none","linear"))
if(tau<=0 | tau>=0.5)
stop("It must hold that 0<tau<0.5")
if (any(is.na(x)))
stop("x contains missing values")
if (mode(x) %in% ("numeric") == FALSE | is.vector(x)==FALSE)
stop("x must be a univariate numeric vector")
T<-length(x)
if ((T*tau)<11)
stop("T*tau needs to be at least 11 to guarantee that the test statistic can be calculated")
if(tau!=0.2 & simu==0)
warning("Note that the critical values stated are not valid for a tau different from 0.2")
if(lmax>0 & simu==0)
warning("Note that the small sample critical values stated might be different for lmax different from 0")
stat<-LKSN(x=x,trend=trend,tau=tau,lmax=lmax)
t_stats<-c(min(stat$tstat1),min(stat$tstat2),min(stat$tstat1,stat$tstat2))
if(simu==1){Crit<-CV(x=x,trend=trend,type="LKSN",M=M,tau=tau,lmax=lmax)}
else{
if(trend=="none") Crit<-getCV()$cv_LKSN_test[1:3,]
if(trend=="linear") Crit<-getCV()$cv_LKSN_test[4:6,]
if(T<100) Crit<-Crit[,1:2]
if(T>1000) Crit<-Crit[,9:10]
if(T>99 & T<1001){
if(min(abs(as.numeric(colnames(Crit))-T))==0){Crit<-Crit[,rank(abs(as.numeric(colnames(Crit))-T))<2]}
else{
Tdif<-as.numeric(colnames(Crit))-T
if(Tdif[which.min(abs(Tdif))]<0){
Crit<-Crit[,(which.min(abs(Tdif))):(which.min(abs(Tdif))+3)]
Tdif<-Tdif[(which.min(abs(Tdif))):(which.min(abs(Tdif))+3)]
}
else{
Crit<-Crit[,(which.min(abs(Tdif))-2):(which.min(abs(Tdif))+1)]
Tdif<-Tdif[(which.min(abs(Tdif))-2):(which.min(abs(Tdif))+1)]
}
Tdif<-abs(Tdif)[c(1,3)]
Crit[,1:2]<-(sum(Tdif)-Tdif[1])/(sum(Tdif))*Crit[,1:2]+(sum(Tdif)-Tdif[2])/(sum(Tdif))*Crit[,3:4]
Crit<-Crit[,1:2]
}
}
}
result<-cbind(Crit,t_stats)
colnames(result)<-c("90%","95%","Teststatistic")
rownames(result)<-c("Against change from I(0) to I(1)","Against change from I(1) to I(0)","Against change in unknown direction")
return(result)
}
ers_test=function (y, trend, lag.max,T)
{
lag.max <- lag.max + 1
nobs <- length(y)
if (trend == "none") {
ahat <- 1 - 25/T
ya <- c(y[1], y[2:nobs] - ahat * y[1:(nobs - 1)])
za1 <- c(1, rep(1 - ahat, nobs - 1))
yd.reg <- summary(stats::lm(ya ~ -1 + za1))
yd <- y - stats::coef(yd.reg)[1]
}
else if (trend == "linear") {
ahat <- 1 - 25/T
ya <- c(y[1], y[2:nobs] - ahat * y[1:(nobs - 1)])
za1 <- c(1, rep(1 - ahat, nobs - 1))
trd <- 1:nobs
za2 <- c(1, trd[2:nobs] - ahat * trd[1:(nobs - 1)])
yd.reg <- summary(stats::lm(ya ~ -1 + za1 + za2))
yd <- y - stats::coef(yd.reg)[1] - stats::coef(yd.reg)[2] * trd
}
yd.l <- yd[1:(nobs - 1)]
yd.diff <- diff(yd)
if (lag.max > 1) {
yd.dlags <- stats::embed(diff(yd), lag.max)[, -1]
data.dfgls <- data.frame(cbind(yd.diff[-(1:(lag.max -
1))], yd.l[-(1:(lag.max - 1))], yd.dlags))
colnames(data.dfgls) <- c("yd.diff", "yd.lag", paste("yd.diff.lag",
1:(lag.max - 1), sep = ""))
dfgls.form <- stats::formula(paste("yd.diff ~ -1 + ", paste(colnames(data.dfgls)[-1],
collapse = " + ")))
}
else if (lag.max <= 1) {
data.dfgls <- data.frame(cbind(yd.diff, yd.l))
colnames(data.dfgls) <- c("yd.diff", "yd.lag")
dfgls.form <- stats::formula("yd.diff ~ -1 + yd.lag")
}
dfgls.reg <- summary(stats::lm(dfgls.form, data = data.dfgls))
teststat <- stats::coef(dfgls.reg)[1, 3]
return(teststat)
}
LKSN<-function(x,trend,tau,lmax)
{
T<-length(x)
Ttau<-(floor(T*tau)):(ceiling(T*(1-tau)))
T1<-rep(NA,length(Ttau))
T2<-rep(NA,length(Ttau))
q<-1
if(trend=="linear"){
for(i in Ttau)
{
T1[q]<-ers_test(x[1:i],trend="linear",T=T,lag.max=lmax)
T2[q]<-ers_test(rev(x)[1:i],trend="linear",T=T,lag.max=lmax)
q<-q+1
}
}
else{
for(i in Ttau)
{
T1[q]<-ers_test(x[1:i],trend="none",T=T,lag.max=lmax)
T2[q]<-ers_test(rev(x)[1:i],trend="none",T=T,lag.max=lmax)
q<-q+1
}
}
return(list(tstat1=T1,tstat2=T2))
}
|
test_that("NHL - Get NHL Teams Roster", {
skip_on_cran()
x <- nhl_teams_roster(team_id=14)
cols <- c("jersey_number",
"player_id",
"player_full_name",
"player_link",
"position_code",
"position_name",
"position_type",
"position_abbreviation",
"team_id",
"season")
expect_equal(colnames(x), cols)
expect_s3_class(x, 'data.frame')
})
|
print.ridgeLogistic <- function(x, all.coef = FALSE, ...)
{
cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
print(coef(x, all.coef = all.coef), ...)
cat("\n")
invisible(x)
}
|
read_soc <- function(path, use_names=TRUE, .verbose=FALSE) {
if (is_url(path)) {
tf <- tempfile()
httr::stop_for_status(GET(path, httr::write_disk(tf)))
path <- tf
}
path <- normalizePath(path.expand(path))
pal <- NULL
soc <- xml2::read_xml(path)
col_nodes <- xml2::xml_find_all(soc, "//draw:color", ns = xml2::xml_ns(soc))
x_names <- xml2::xml_attr(col_nodes, "draw:name", ns = xml2::xml_ns(soc))
x_names <- trimws(x_names)
pal <- xml2::xml_attr(col_nodes, "draw:color", ns = xml2::xml_ns(soc))
names(pal) <- x_names
n_colors <- length(pal)
if (.verbose) message("
if (!use_names) { pal <- unname(pal) }
gsub(" ", "0", pal)
}
|
test_that("link_network_map works without lookup table", {
net=network::network(matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), nrow=4, byrow=TRUE))
network::set.vertex.attribute(net, "name", value=c("a", "e", "c", "d"))
wkb = structure(list("01010000204071000000000000801A064100000000AC5C1641",
"01010000204071000000000000801A084100000000AC5C1441",
"01010000204071000000000000801A044100000000AC5C1241",
"01010000204071000000000000801A024100000000AC5C1841"), class = "WKB")
map=sf::st_sf(id=c("a", "b", "c", "e"), sf::st_as_sfc(wkb, EWKB=TRUE))
res=link_network_map(map, net, "id", "name")
expect_equal(res, list(m=c("a", "c", "e"), n=c("a", "e", "c")))
})
test_that("link_network_map works with a lookup table", {
net=network::network(matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), nrow=4, byrow=TRUE))
network::set.vertex.attribute(net, "name", value=c("a", "b", "c", "d"))
wkb = structure(list("01010000204071000000000000801A064100000000AC5C1641",
"01010000204071000000000000801A084100000000AC5C1441",
"01010000204071000000000000801A044100000000AC5C1241",
"01010000204071000000000000801A024100000000AC5C1841"), class = "WKB")
map=sf::st_sf(id=c("a1", "b2", "c3", "d4"), sf::st_as_sfc(wkb, EWKB=TRUE))
lkptbl=data.frame(id=c("a1", "b2", "c4", "d4"), name=c("a", "b", "c", "d"))
res=link_network_map2(map, net, lkptbl, "id", "name")
expect_equal(res, list(m=c("a1", "b2", "d4"), n=c("a", "b", "d")))
})
test_that("is_* functions recognize objects of the class they test for", {
expect_true(is_network(network::network(matrix(1))), TRUE)
wkb = structure(list("01010000204071000000000000801A064100000000AC5C1641",
"01010000204071000000000000801A084100000000AC5C1441",
"01010000204071000000000000801A044100000000AC5C1241",
"01010000204071000000000000801A024100000000AC5C1841"), class = "WKB")
map=sf::st_sf(id=c("a1", "b2", "c3", "d4"), sf::st_as_sfc(wkb, EWKB=TRUE))
expect_true(is_sf(map))
})
test_that("is_lookup recognizes a complete data frame with two columns", {
expect_equal(is_lookup_table(data.frame(id=c("a1", "b2", "c3", "d4"),
name=c("a", "b", "c", "d"))),
c("id", "name"))
})
test_that("is_lookup fails with duplicates or missing/empty values", {
expect_false(is_lookup_table(data.frame(id=c("a1", "b2", "c3", "d4"),
name=c("a", "b", "b", "d"))))
expect_false(is_lookup_table(data.frame(id=c("a1", "", "c3", "d4"),
name=c("a", "b", "c", "d"))))
expect_false(is_lookup_table(data.frame(id=c("a1", "b2", NA, "d4"),
name=c("a", "b", "b", "d"))))
})
test_that("is_lookup fails with column names not found in df", {
expect_false(is_lookup_table(data.frame(id=c("a1", "b2", "c3", "d4"),
name=c("a", "b", "c", "d")),
m_name="id",
n_name="vertex.names"))
})
|
gdm_create_delta_designmatrix <- function( delta.designmatrix,
TP, D, theta.k, skill.levels,G)
{
if ( is.null(delta.designmatrix) ){
delta.designmatrix <- rep(1,TP)
for (dd in 1:D){
for ( pp in 1:(min( skill.levels[dd]-1,3) ) ){
delta.designmatrix <- cbind( delta.designmatrix, theta.k[,dd]^pp )
}
}
if (D>1){
for (dd1 in 1:(D-1) ){
for (dd2 in (dd1+1):D) {
delta.designmatrix <- cbind( delta.designmatrix, theta.k[,dd1]*theta.k[,dd2] )
}
}
}
}
delta <- matrix(0,ncol(delta.designmatrix),G)
covdelta <- NULL
res <- list( delta=delta, covdelta=covdelta, delta.designmatrix=delta.designmatrix )
return(res)
}
|
senm <- function (y, z, mset, gamma = 1, inner = 0, trim = 3, lambda = 1/2,
tau = 0, alternative="greater", TonT = FALSE)
{
stopifnot((alternative=="greater")|(alternative=="less"))
stopifnot(gamma>=1)
stopifnot((inner>=0)&(inner<=trim))
stopifnot((lambda>0)&(lambda<1))
stopifnot(is.vector(y)&is.vector(z)&is.vector(mset))
stopifnot((length(z)==length(y)))
stopifnot((length(z)==length(mset)))
stopifnot(all(!is.na(y)))
stopifnot(all((z==0)|(z==1)))
tbcheck<-table(z,mset)
ck<-all(tbcheck[2,]==1)&all(tbcheck[1,]>=1)
if (!ck){
warning("Every matched set must contain one treated subject and at least one control.")
stopifnot(ck)
}
mset<-as.integer(mset)
o<-order(mset,1-z)
y<-y[o]
z<-z[o]
mset<-mset[o]
tb<-table(mset)
nset<-length(tb)
setsize<-max(tb)
makeymat<-function(yj){
ymat<-matrix(NA,nset,setsize)
m<-0
for (i in 1:nset){
ymat[i,1:tb[i]] <- yj[(m+1):(m+tb[i])]
m<-m+tb[i]
}
ymat
}
ymat<-makeymat(y)
if (alternative=="less"){
ymat<-(-ymat)
tau<-(-tau)
}
if (!(tau == 0)) ymat[, 1] <- ymat[, 1] - tau
ms <- mscorev(ymat, inner = inner, trim = trim, qu = lambda, TonT = TonT)
separable1v(ms, gamma = gamma)
}
|
library(checkmate)
library(testthat)
library(raster)
context("getFeatures")
test_that("getFeatures of a 'geom'", {
coords <- data.frame(x = c(40, 70, 70, 50),
y = c(40, 40, 60, 70),
fid = 1)
window <- data.frame(x = c(0, 80),
y = c(0, 80))
aGeom <- gs_polygon(anchor = coords, window = window)
output <- getFeatures(aGeom)
expect_data_frame(output, any.missing = FALSE, nrows = 1, ncols = 2)
expect_names(names(output), identical.to = c("fid", "gid"))
output <- getFeatures(gtGeoms$grid$categorical)
expect_data_frame(output, any.missing = FALSE, nrows = 3360)
expect_names(x = names(output), permutation.of = c("fid", "values"))
output <- getFeatures(gtGeoms$grid$continuous)
expect_data_frame(output, any.missing = FALSE, nrows = 3360)
expect_names(x = names(output), permutation.of = c("fid", "continuous"))
})
test_that("getFeatures of a Spatial* object", {
input <- gtSP$SpatialPolygons
output <- getFeatures(input)
expect_data_frame(output, any.missing = FALSE, nrows = 2, ncols = 2)
expect_names(names(output), identical.to = c("fid", "gid"))
})
test_that("getFeatures of a sf object", {
input <- gtSF$polygon
output <- getFeatures(input)
expect_data_frame(output, any.missing = FALSE, nrows = 2, ncols = 3)
expect_names(names(output), identical.to = c("fid", "gid", "a"))
})
test_that("getFeatures of any other object", {
output <- getFeatures("bla")
expect_null(object = output)
})
|
NP_it<-function(prev.results){
if (missing(prev.results)){
stop("No elementos para iteracion, No elements for iteration")
} else {
if(prev.results$bin[1]==0){
stop("El proceso ya esta bajo control, The process is already under control")
} else {
np.0<-prev.results$data.1
p.0<-prev.results$data.1/prev.results$data.n
m <-length(np.0)
n <-prev.results$data.n
LCS.np.0<-expression(n*mean(p.0)+3*sqrt(n*mean(p.0)*(1-mean(p.0))))
LCI.np.0<-expression(n*mean(p.0)-3*sqrt(n*mean(p.0)*(1-mean(p.0))))
LC.np.0<-expression(n*mean(p.0))
if (eval(LCI.np.0)>0){
LCI.p.0<-eval(LCI.np.0)
} else {
LCI.np.0 <- 0
}
np.pos<-which(np.0 >= eval(LCI.np.0) & np.0 < eval(LCS.np.0))
np.1<-np.0[np.pos]
np.fi.0<-which(np.0 < eval(LCI.np.0))
np.fs.0<-which(np.0 >= eval(LCS.np.0))
bin.np<-if(length(np.pos)< m){
bin.np<-1
} else {
bin.np<-0
}
plot.np<-function(NP=np.0,type="b",col="blue",pch =19){
plot(NP, xlab= "Numero de muestra", ylab="Numero de No conformes",
main="Grafica NP, Control Estadistico de la Calidad",type=type, col=col,
ylim=c(eval(LCI.np.0)-mean(np.0)*0.05, max(eval(LCS.np.0)*1.1, max(np.0)*1.1)),
xlim=c(-0.05*m, 1.05*m), pch = pch)
abline(h= c(eval(LCS.np.0), eval(LCI.np.0), eval(LC.np.0)),col="lightgray")
text(c(rep(1,3),rep(7,3)), rep(c(eval(LCS.np.0),eval(LC.np.0),eval(LCI.np.0)),2),
c(c("LCS = ","LC = ","LCI = "), c(round(eval(LCS.np.0),3), round(eval(LC.np.0),3),
round(eval(LCI.np.0),3))),
col="red") }
plot.np()
structure(list("in.control" = np.pos,
"out.control"= c(np.fi.0,np.fs.0),
"Iteraciones" = prev.results$Iteraciones + 1,
"data.n"= prev.results$data.n,
"data.0"= prev.results$data.0,
"data.1"= np.1,
"bin" = bin.np,
"Limites de Control Grafica np" = c("LCI.np"=eval(LCI.np.0),"LCS.np"=eval(LCS.np.0),
"LC.np"=eval(LC.np.0)),
"Conclusion del proceso"= c(if(length(np.pos)< m){
print("Proceso fuera de Control en Grafica np")
} else {
print("El proceso esta bajo control en Grafica np")
})))
}
}
}
|
nbn_search <- function(sci_com, fq = NULL, order = NULL, sort = NULL,
start = 0, rows = 25, facets = NULL, q = NULL, ...) {
pchk(q, "sci_com")
args <- tc(list(
q = sci_com, fq = fq, pageSize = rows, startIndex = start, sort = sort,
dir = order, facets = facets
))
nbn_GET(file.path(nbn_base(), "search"), args, ...)
}
nbn_GET <- function(url, args, ...){
cli <- crul::HttpClient$new(url = url, headers = tx_ual,)
tt <- cli$get(query = argsnull(args), ...)
tt$raise_for_status()
json <- jsonlite::fromJSON(tt$parse("UTF-8"))$searchResults
list(meta = pop(json, "results"), data = json$results)
}
nbn_base <- function() "https://species-ws.nbnatlas.org"
|
context("File-backed")
test_that("file-backed entries are discarded after the file is modified", {
file <- renv_scope_tempfile("renv-test-")
contents <- "Hello, world!"
writeLines(contents, con = file)
renv_filebacked_set("test", file, contents)
expect_equal(renv_filebacked_get("test", file), contents)
writeLines("Goodbye, world!", con = file)
expect_identical(renv_filebacked_get("test", file), NULL)
})
test_that("file-backed entries are discarded after the file is deleted", {
file <- renv_scope_tempfile("renv-test-")
contents <- "Hello, world!"
writeLines(contents, con = file)
renv_filebacked_set("test", file, contents)
expect_equal(renv_filebacked_get("test", file), contents)
unlink(file)
expect_identical(renv_filebacked_get("test", file), NULL)
})
|
snap_sites <- function(sites, flow_acc, max_move, out, overwrite = FALSE, max_memory = 300, use_sp = TRUE, ...){
if(!check_running()) stop("There is no valid GRASS session. Program halted.")
if(use_sp) rgrass7::use_sp() else rgrass7::use_sf()
flags <- "quiet"
if(overwrite) flags <- c(flags, "overwrite")
grass_out <- basename(out)
grass_out <- gsub(".shp", "", grass_out)
execGRASS(
"r.stream.snap",
flags = flags,
parameters = list(
input = sites,
output = grass_out,
accumulation = flow_acc,
radius = max_move,
memory = max_memory,
...
)
)
sites <- readVECT(sites)
grass_out <- readVECT(grass_out)
grass_out$SnapDist <- pointDistance(sites, grass_out)
raster::shapefile(x = grass_out, filename = out, overwrite = overwrite)
vector_to_mapset(out, overwrite = overwrite)
invisible()
}
|
pcaRobS <- SMPCA <-function(X, ncomp, desprop=0.9, deltasca=0.5, maxit=100) {
Wf <- function(r){ return((1-r)^2*(r<=1)) }
n=dim(X)[1]; p=dim(X)[2]
tol=1.e-4;
sp= rrcov::PcaLocantore(X, k=p)
mu0=sp@center; lamL=sp@eigenvalues
lamL=lamL/sum(lamL); propSPC=cumsum(lamL)
q1=sum(propSPC<desprop)+1
q=min(c(q1,ncomp))
QL=sp@loadings[,1:q]; Xcen=scale(X, center=mu0, scale=FALSE)
fitL=scale(Xcen%*%QL%*%t(QL), center=-mu0,scale=FALSE)
rr=colSums(t(Xcen)^2);
sigini=mscale(sqrt(rr), delta=deltasca, tuning.chi = 1, family='bisquare')^2
rr=colSums(t(X-fitL)^2);
sig0=mscale(sqrt(rr), delta=deltasca, tuning.chi = 1, family='bisquare')^2
ww=Wf(rr/sig0); B0=QL
iter=0; del=100;
while (iter<maxit & abs(del)>tol) {
iter=iter+1;
mu=colSums(X*ww)/sum(ww)
Xcen=scale(X, center=mu, scale=FALSE)
C=t(Xcen)%*%diag(ww)%*%Xcen
B <- svd(C, nu=q, nv=q)$u
fit=Xcen%*%B%*%t(B)
res=Xcen-fit
rr=colSums(t(res)^2)
sig=mscale(sqrt(rr),delta=deltasca, tuning.chi = 1, family='bisquare') ^2
del1=1-sig/sig0;
U=diag(q)-abs(t(B)%*%B0)
del2=mean(abs(U)); del=max(c(del1,del2))
sig0=sig; B0=B
ww=Wf(rr/sig);
repre=Xcen%*%B
}
propex=1-sig/sigini
fit=scale(fit, center=-mu, scale=FALSE)
resu=list(eigvec=B, fit=fit, repre=repre, propex=propex, propSPC=propSPC, mu=mu, q=q)
return(resu)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.