content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
is_collector <- function(x) {
if (!is.character(x)) {
return(FALSE)
}
grepl("^\\.\\.\\.", x)
}
has_collector <- function(x) {
any(vapply(x, is_collector, logical(1)))
}
collect <- function(names, values) {
if (!any(grepl("^\\.\\.\\.", names))) {
stop("no collector variable specified", call. = FALSE)
}
if (length(names) == length(values)) {
return(values)
}
if (length(names) == 1) {
# ...alone
return(list(values))
}
c_index <- which(grepl('^\\.\\.\\.', names))
if (length(c_index) != 1) {
stop(
"invalid `%<-%` left-hand side, multiple collector variables at the ",
"same depth",
call. = FALSE
)
}
if (c_index == 1) {
# ...firsts, a, b
post <- rev(
seq.int(
from = length(values),
length.out = length(names) - 1,
by = -1
)
)
c(list(values[-post]), values[post])
} else if (c_index == length(names)) {
# a, b, ...rest
pre <- seq.int(1, c_index - 1)
c(values[pre], list(values[-pre]))
} else {
# a, ...mid, b
pre <- seq.int(1, c_index - 1)
post <- rev(
seq.int(
from = length(values),
length.out = length(names) - length(pre) - 1,
by = -1
)
)
c(values[pre], list(values[-c(pre, post)]), values[post])
}
}
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/collect.R |
#' Destructure an object
#'
#' `destructure` is used during unpacking assignment to coerce an object
#' into a list. Individual elements of the list are assigned to names on the
#' left-hand side of the unpacking assignment expression.
#'
#' @param x An \R object.
#'
#' @details
#'
#' If `x` is atomic `destructure` expects `length(x)` to be 1. If a vector with
#' length greater than 1 is passed to `destructure` an error is raised.
#'
#' New implementations of `destructure` can be very simple. A new
#' `destructure` implementation might only strip away the class of a custom
#' object and return the underlying list structure. Alternatively, an object
#' might destructure into a nested set of values and may require a more
#' complicated implementation. In either case, new implementations must return a
#' list object so \code{\%<-\%} can handle the returned value(s).
#'
#' @seealso \code{\link{\%<-\%}}
#'
#' @export
#' @examples
#' # data frames become a list of columns
#' destructure(
#' data.frame(x = 0:4, y = 5:9)
#' )
#'
#' # strings are split into list of characters
#' destructure("abcdef")
#'
#' # dates become list of year, month, and day
#' destructure(Sys.Date())
#'
#' # create a new destructure implementation
#' shape <- function(sides = 4, color = "red") {
#' structure(
#' list(sides = sides, color = color),
#' class = "shape"
#' )
#' }
#'
#' \dontrun{
#' # cannot destructure the shape object yet
#' c(sides, color) %<-% shape()
#' }
#'
#' # implement `destructure` for shapes
#' destructure.shape <- function(x) {
#' list(x$sides, x$color)
#' }
#'
#' # now we can destructure shape objects
#' c(sides, color) %<-% destructure(shape())
#'
#' sides # 4
#' color # "red"
#'
#' c(sides, color) %<-% destructure(shape(3, "green"))
#'
#' sides # 3
#' color # 'green'
#'
destructure <- function(x) {
UseMethod("destructure")
}
#' Included Implementations of `destructure`
#'
#' zeallot includes `destructure` methods for the following classes:
#' `character`, `complex`, `Date`, `data.frame`, and
#' `summary.lm`. See details for how each object is transformed into a
#' list.
#'
#' @inheritParams destructure
#'
#' @details
#'
#' `character` values are split into a list of individual characters.
#'
#' `complex` values are split into a list of two values, the real and the
#' imaginary part.
#'
#' `Date` values are split into a list of three numeric values, the year,
#' month, and day.
#'
#' `data.frame` values are coerced into a list using `as.list`.
#'
#' `summary.lm` values are coerced into a list of values, one element for
#' each of the eleven values returned by `summary.lm`.
#'
#' @return
#'
#' A list of elements from `x`.
#'
#' @seealso [destructure]
#'
#' @keywords internal
#'
#' @name destructure-methods
#' @export
destructure.character <- function(x) {
assert_destruction(x)
as.list(strsplit(x, "")[[1]])
}
#' @rdname destructure-methods
#' @export
destructure.complex <- function(x) {
assert_destruction(x)
list(Re(x), Im(x))
}
#' @rdname destructure-methods
#' @export
destructure.Date <- function(x) {
assert_destruction(x)
as.list(as.numeric(strsplit(format(x, "%Y-%m-%d"), "-", fixed = TRUE)[[1]]))
}
#' @rdname destructure-methods
#' @export
destructure.data.frame <- function(x) {
as.list(x)
}
#' @rdname destructure-methods
#' @export
destructure.summary.lm <- function(x) {
lapply(x, identity)
}
#' @rdname destructure-methods
#' @export
destructure.default <- function(x) {
stop_invalid_rhs(incorrect_number_of_values())
}
assert_destruction <- function(x) {
if (length(x) > 1) {
stop(
"invalid `destructure` argument, cannot destructure ", class(x),
" vector of length greater than 1",
call. = FALSE
)
}
}
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/destructure.R |
#' Multiple assignment operators
#'
#' Assign values to name(s).
#'
#' @param x A name structure, see section below.
#'
#' @param value A list of values, vector of values, or \R object to assign.
#'
#' @section Name Structure:
#'
#' **the basics**
#'
#' At its simplest, the name structure may be a single variable name, in which
#' case \code{\%<-\%} and \code{\%->\%} perform regular assignment, \code{x
#' \%<-\% list(1, 2, 3)} or \code{list(1, 2, 3) \%->\% x}.
#'
#' To specify multiple variable names use a call to `c()`, for example
#' \code{c(x, y, z) \%<-\% c(1, 2, 3)}.
#'
#' When `value` is neither an atomic vector nor a list, \code{\%<-\%} and
#' \code{\%->\%} will try to destructure `value` into a list before assigning
#' variables, see [destructure()].
#'
#' **object parts**
#'
#' Like assigning a variable, one may also assign part of an object, \code{c(x,
#' x[[1]]) \%<-\% list(list(), 1)}.
#'
#' **nested names**
#'
#' One can also nest calls to `c()` when needed, `c(x, c(y, z))`. This nested
#' structure is used to unpack nested values,
#' \code{c(x, c(y, z)) \%<-\% list(1, list(2, 3))}.
#'
#' **collector variables**
#'
#' To gather extra values from the beginning, middle, or end of `value` use a
#' collector variable. Collector variables are indicated with a `...`
#' prefix, \code{c(...start, z) \%<-\% list(1, 2, 3, 4)}.
#'
#' **skipping values**
#'
#' Use `.` in place of a variable name to skip a value without raising an error
#' or assigning the value, \code{c(x, ., z) \%<-\% list(1, 2, 3)}.
#'
#' Use `...` to skip multiple values without raising an error or assigning the
#' values, \code{c(w, ..., z) \%<-\% list(1, NA, NA, 4)}.
#'
#' **default values**
#'
#' Use `=` to specify a default value for a variable, \code{c(x, y = NULL)
#' \%<-\% tail(1, 2)}.
#'
#' When assigning part of an object a default value may not be specified because
#' of the syntax enforced by \R. The following would raise an `"unexpected '='
#' ..."` error, \code{c(x, x[[1]] = 1) \%<-\% list(list())}.
#'
#' @return
#'
#' \code{\%<-\%} and \code{\%->\%} invisibly return `value`.
#'
#' These operators are used primarily for their assignment side-effect.
#' \code{\%<-\%} and \code{\%->\%} assign into the environment in which they
#' are evaluated.
#'
#' @seealso
#'
#' For more on unpacking custom objects please refer to
#' [destructure()].
#'
#' @name operator
#' @export
#' @examples
#' # basic usage
#' c(a, b) %<-% list(0, 1)
#'
#' a # 0
#' b # 1
#'
#' # unpack and assign nested values
#' c(c(e, f), c(g, h)) %<-% list(list(2, 3), list(3, 4))
#'
#' e # 2
#' f # 3
#' g # 4
#' h # 5
#'
#' # can assign more than 2 values at once
#' c(j, k, l) %<-% list(6, 7, 8)
#'
#' # assign columns of data frame
#' c(erupts, wait) %<-% faithful
#'
#' erupts # 3.600 1.800 3.333 ..
#' wait # 79 54 74 ..
#'
#' # assign only specific columns, skip
#' # other columns
#' c(mpg, cyl, disp, ...) %<-% mtcars
#'
#' mpg # 21.0 21.0 22.8 ..
#' cyl # 6 6 4 ..
#' disp # 160.0 160.0 108.0 ..
#'
#' # skip initial values, assign final value
#' TODOs <- list("make food", "pack lunch", "save world")
#'
#' c(..., task) %<-% TODOs
#'
#' task # "save world"
#'
#' # assign first name, skip middle initial,
#' # assign last name
#' c(first, ., last) %<-% c("Ursula", "K", "Le Guin")
#'
#' first # "Ursula"
#' last # "Le Guin"
#'
#' # simple model and summary
#' mod <- lm(hp ~ gear, data = mtcars)
#'
#' # extract call and fstatistic from
#' # the summary
#' c(modcall, ..., modstat, .) %<-% summary(mod)
#'
#' modcall
#' modstat
#'
#' # unpack nested values w/ nested names
#' fibs <- list(1, list(2, list(3, list(5))))
#'
#' c(f2, c(f3, c(f4, c(f5)))) %<-% fibs
#'
#' f2 # 1
#' f3 # 2
#' f4 # 3
#' f5 # 5
#'
#' # unpack first numeric, leave rest
#' c(f2, fibcdr) %<-% fibs
#'
#' f2 # 1
#' fibcdr # list(2, list(3, list(5)))
#'
#' # swap values without using temporary variables
#' c(a, b) %<-% c("eh", "bee")
#'
#' a # "eh"
#' b # "bee"
#'
#' c(a, b) %<-% c(b, a)
#'
#' a # "bee"
#' b # "eh"
#'
#' # unpack `strsplit` return value
#' names <- c("Nathan,Maria,Matt,Polly", "Smith,Peterson,Williams,Jones")
#'
#' c(firsts, lasts) %<-% strsplit(names, ",")
#'
#' firsts # c("Nathan", "Maria", ..
#' lasts # c("Smith", "Peterson", ..
#'
#' # handle missing values with default values
#' parse_time <- function(x) {
#' strsplit(x, " ")[[1]]
#' }
#'
#' c(hour, period = NA) %<-% parse_time("10:00 AM")
#'
#' hour # "10:00"
#' period # "AM"
#'
#' c(hour, period = NA) %<-% parse_time("15:00")
#'
#' hour # "15:00"
#' period # NA
#'
#' # right operator
#' list(1, 2, "a", "b", "c") %->% c(x, y, ...chars)
#'
#' x # 1
#' y # 2
#' chars # list("a", "b", "c")
#'
#' # magrittr chains, install.packages("magrittr") for this example
#' if (requireNamespace("magrittr", quietly = TRUE)) {
#' library(magrittr)
#'
#' c("hello", "world!") %>%
#' paste0("\n") %>%
#' lapply(toupper) %->%
#' c(greeting, subject)
#'
#' greeting # "HELLO\n"
#' subject # "WORLD!\n"
#' }
#'
`%<-%` <- function(x, value) {
tryCatch(
multi_assign(substitute(x), value, parent.frame()),
invalid_lhs = function(e) {
stop("invalid `%<-%` left-hand side, ", e$message, call. = FALSE)
},
invalid_rhs = function(e) {
stop("invalid `%<-%` right-hand side, ", e$message, call. = FALSE)
}
)
}
#' @rdname operator
#' @export
`%->%` <- function(value, x) {
tryCatch(
multi_assign(substitute(x), value, parent.frame()),
invalid_lhs = function(e) {
stop("invalid `%->%` right-hand side, ", e$message, call. = FALSE)
},
invalid_rhs = function(e) {
stop("invalid `%->%` left-hand side, ", e$message, call. = FALSE)
}
)
}
# The real power behind %->% and %<-%
#
# Within the function `lhs` and `rhs` refer to the left- and right-hand side of
# a call to %<-% operator. For %->% the lhs and rhs from the original call are
# swapped when passed to `multi_assign`.
#
# @param x A name structure, converted into a tree-like structure with `tree`.
#
# @param value The values to assign.
#
# @param env The environment where the variables will be assigned.
#
multi_assign <- function(x, value, env) {
ast <- tree(x)
internals <- calls(ast)
lhs <- variables(ast)
rhs <- value
#
# all lists or environemnts referenced in lhs must already exist
#
check_extract_calls(lhs, env)
#
# standard assignment
#
if (is.null(internals)) {
if (is.language(lhs)) {
assign_extract(lhs, value, envir = env)
} else {
assign(lhs, value, envir = env)
}
return(invisible(value))
}
#
# *error* multiple assignment, but sinle RHS value
#
if (length(value) == 0) {
stop_invalid_rhs(incorrect_number_of_values())
}
#
# edge cases when RHS is not a list
#
if (!is_list(value)) {
if (is.atomic(value)) {
rhs <- as.list(value)
} else {
rhs <- destructure(value)
}
}
#
# tuples in question are variable names and value to assign
#
tuples <- pair_off(lhs, rhs, env)
for (t in tuples) {
name <- t[["name"]]
val <- t[["value"]]
if (is.language(name)) {
assign_extract(name, val, envir = env)
next
}
if (is.atomic(value)) {
if (is.null(attr(val, "default", TRUE))) {
val <- unlist(val, recursive = FALSE)
} else if (attr(val, "default", TRUE) == TRUE) {
attr(val, "default") <- NULL
}
}
assign(name, val, envir = env)
}
invisible(value)
}
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/operator.R |
pair_off <- function(names, values, env) {
if (is.character(names) || is.language(names)) {
if (names == ".") {
return()
}
attributes(names) <- NULL
return(list(list(name = names, value = values)))
}
if (is_list(names) && length(names) == 0 &&
is_list(values) && length(values) == 0) {
return()
}
#
# mismatch between variables and values
#
if (length(names) != length(values)) {
if (any(has_default(names))) {
values <- add_defaults(names, values, env)
names <- lapply(names, `attributes<-`, value = NULL)
return(pair_off(names, values))
}
#
# mismatch could be resolved by destructuring the values, in this case
# values must be a single element list
#
if (is_list(values) && length(values) == 1) {
return(pair_off(names, destructure(car(values))))
}
#
# if there is no collector the mismatch is a problem *or* if collector,
# and still more variables than values the collector is useless and
# mismatch is a problem
#
if (!has_collector(names) || length(names) > length(values)) {
stop_invalid_rhs(incorrect_number_of_values())
}
}
if (is_collector(car(names))) {
collected <- collect(names, values)
name <- sub("^\\.\\.\\.", "", car(names))
#
# skip unnamed collector variable and corresponding values
#
if (name == "") {
return(pair_off(cdr(names), cdr(collected)))
}
return(
c(pair_off(name, car(collected)), pair_off(cdr(names), cdr(collected)))
)
}
#
# multiple nested variables and nested vector of values same length, but
# a nested vector is not unpacked, mismatch
#
if (is_list(names) && !is_list(values)) {
stop_invalid_rhs(incorrect_number_of_values())
}
if (length(names) == 1) {
return(pair_off(car(names), car(values)))
}
c(pair_off(car(names), car(values)), pair_off(cdr(names), cdr(values)))
}
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/pair-off.R |
is_list <- function(x) {
length(class(x)) == 1 && class(x) == 'list'
}
car <- function(cons) {
stopifnot(is.list(cons), length(cons) > 0)
cons[[1]]
}
cdr <- function(cons) {
stopifnot(is.list(cons), length(cons) > 0)
cons[-1]
}
names2 <- function(x) {
if (is.null(names(x))) rep.int("", length(x)) else names(x)
}
#
# the default attribute is used by `variables()` and `pair_off()` to know when
# to assign a variable its default value
#
get_default <- function(x) {
attr(x, "default", exact = TRUE)
}
has_default <- function(x) {
vapply(x, function(i) !is.null(get_default(i)), logical(1))
}
#
# append any default values onto the end of a list of values, used in
# `pair_off()` to extend the current set of values thereby avoiding an
# incorrect number of values error
#
add_defaults <- function(names, values, env) {
where <- which(has_default(names))
defaults <- lapply(names[where], get_default)[where > length(values)]
evaled <- lapply(
defaults,
function(d) {
deval <- eval(d, envir = env)
if (is.null(deval)) {
return(deval)
}
attr(deval, "default") <- TRUE
deval
}
)
append(values, evaled)
}
#
# traverse nested extract op calls to find the extractee, e.g. `x[[1]][[1]]`
#
traverse_to_extractee <- function(call) {
if (is.language(call) && is.symbol(call)) {
return(call)
}
traverse_to_extractee(call[[2]])
}
#
# used by multi_assign to confirm all extractees exist
#
check_extract_calls <- function(lhs, envir) {
if (is.character(lhs)) {
return()
}
if (is.language(lhs)) {
extractee <- traverse_to_extractee(lhs)
if (!exists(as.character(extractee), envir = envir, inherits = FALSE)) {
stop_invalid_lhs(object_does_not_exist(extractee))
} else {
return()
}
}
unlist(lapply(lhs, check_extract_calls, envir = envir))
}
is_extract_op <- function(x) {
if (length(x) < 1) {
return(FALSE)
}
(as.character(x) %in% c("[", "[[", "$"))
}
is_valid_call <- function(x) {
if (length(x) < 1) {
return(FALSE)
}
(x == "c" || x == "=" || is_extract_op(x))
}
#
# used by multi_assign to assign list elements in the calling environment
#
assign_extract <- function(call, value, envir = parent.frame()) {
replacee <- call("<-", call, value)
eval(replacee, envir = envir)
invisible(value)
}
#
# parses a substituted expression to create a tree-like list structure,
# perserves calls to extract ops instead of converting them to lists
#
tree <- function(x) {
if (length(x) == 1) {
return(x)
}
if (is_extract_op(x[[1]])) {
return(x)
}
lapply(
seq_along(as.list(x)),
function(i) {
if (names2(x[i]) != "") {
return(list(as.symbol("="), names2(x[i]), x[[i]]))
} else {
tree(x[[i]])
}
}
)
}
#
# given a tree-like list structure returns a character vector of the function
# calls, used by multi_assign to determine if performing standard assignment or
# multiple assignment
#
calls <- function(x) {
if (!is_list(x)) {
return(NULL)
}
this <- car(x)
if (!is_valid_call(this)) {
stop_invalid_lhs(unexpected_call(this))
}
c(as.character(this), unlist(lapply(cdr(x), calls)))
}
#
# given a tree-like list structure, returns a nested list of the variables
# in the tree, will also associated default values with variables
#
variables <- function(x) {
if (!is_list(x)) {
if (x == "") {
stop_invalid_lhs(empty_variable(x))
}
if (is.language(x) && length(x) > 1 && is_extract_op(x[[1]])) {
return(x)
}
if (!is.symbol(x)) {
stop_invalid_lhs(unexpected_variable(x))
}
return(as.character(x))
}
if (car(x) == "=") {
var <- as.character(car(cdr(x)))
default <- car(cdr(cdr(x)))
if (is.null(default)) {
default <- quote(pairlist())
}
attr(var, "default") <- default
return(var)
}
lapply(cdr(x), variables)
}
#
# error helpers below
#
incorrect_number_of_values <- function() {
"incorrect number of values"
}
object_does_not_exist <- function(obj) {
paste0("object `", obj, "` does not exist in calling environment")
}
empty_variable <- function(obj) {
paste("found empty variable, check for extraneous commas")
}
unexpected_variable <- function(obj) {
paste("expected symbol, but found", class(obj))
}
unexpected_call <- function(obj) {
paste0("unexpected call `", as.character(obj), "`")
}
# thank you Advanced R
condition <- function(subclass, message, call = sys.call(-1), ...) {
structure(
class = c(subclass, "condition"),
list(message = message, call = call),
...
)
}
stop_invalid_lhs <- function(message, call = sys.call(-1), ...) {
cond <- condition(c("invalid_lhs", "error"), message, call, ...)
stop(cond)
}
stop_invalid_rhs <- function(message, call = sys.call(-1), ...) {
cond <- condition(c("invalid_rhs", "error"), message, call, ...)
stop(cond)
}
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/utils.R |
#' Multiple, unpacking, and destructuring assignment in R
#'
#' zeallot provides a \code{\link{\%<-\%}} operator to perform multiple
#' assignment in R. To get started with zeallot be sure to read over the
#' introductory vignette on unpacking assignment,
#' \code{vignette('unpacking-assignment')}.
#'
#' @seealso \code{\link{\%<-\%}}
#'
#' @docType package
#' @name zeallot
"_PACKAGE"
| /scratch/gouwar.j/cran-all/cranData/zeallot/R/zeallot.R |
## ---- include = FALSE----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(zeallot)
## ------------------------------------------------------------------------
c(lat, lng) %<-% list(38.061944, -122.643889)
## ------------------------------------------------------------------------
lat
lng
## ------------------------------------------------------------------------
c(lat, lng) %<-% c(38.061944, -122.643889)
lat
lng
## ------------------------------------------------------------------------
c(min_wt, q1_wt, med_wt, mean_wt, q3_wt, max_wt) %<-% summary(mtcars$wt)
min_wt
q1_wt
med_wt
mean_wt
q3_wt
max_wt
## ---- error=TRUE---------------------------------------------------------
c(stg1, stg2, stg3) %<-% list("Moe", "Donald")
## ---- error=TRUE---------------------------------------------------------
c(stg1, stg2, stg3) %<-% list("Moe", "Larry", "Curley", "Donald")
## ------------------------------------------------------------------------
#
# A function which returns a list of 2 numeric values.
#
coords_list <- function() {
list(38.061944, -122.643889)
}
c(lat, lng) %<-% coords_list()
lat
lng
## ------------------------------------------------------------------------
#
# Convert cartesian coordinates to polar
#
to_polar = function(x, y) {
c(sqrt(x^2 + y^2), atan(y / x))
}
c(radius, angle) %<-% to_polar(12, 5)
radius
angle
## ------------------------------------------------------------------------
c(inter, slope) %<-% coef(lm(mpg ~ cyl, data = mtcars))
inter
slope
## ---- eval = require("purrr")--------------------------------------------
safe_log <- purrr::safely(log)
## ---- eval = require("purrr")--------------------------------------------
pair <- safe_log(10)
pair$result
pair$error
## ---- eval = require("purrr")--------------------------------------------
pair <- safe_log("donald")
pair$result
pair$error
## ---- eval = require("purrr")--------------------------------------------
c(res, err) %<-% safe_log(10)
res
err
## ------------------------------------------------------------------------
c(mpg, cyl, disp, hp) %<-% mtcars[, 1:4]
head(mpg)
head(cyl)
head(disp)
head(hp)
## ------------------------------------------------------------------------
quartet <- lapply(1:4, function(i) anscombe[, c(i, i + 4)])
c(an1, an2, an3, an4) %<-% lapply(quartet, head, n = 3)
an1
an2
an3
an4
## ------------------------------------------------------------------------
c(a, c(b, d), e) %<-% list("begin", list("middle1", "middle2"), "end")
a
b
d
e
## ---- error=TRUE---------------------------------------------------------
c(a, c(b, d, e), f) %<-% list("begin", list("middle1", "middle2"), "end")
## ------------------------------------------------------------------------
c(ch1, ch2, ch3) %<-% "abc"
ch1
ch2
ch3
## ------------------------------------------------------------------------
c(y, m, d) %<-% Sys.Date()
y
m
d
## ------------------------------------------------------------------------
f <- lm(mpg ~ cyl, data = mtcars)
c(fcall, fterms, resids, ...rest) %<-% summary(f)
fcall
fterms
head(resids)
## ------------------------------------------------------------------------
str(rest)
## ---- error = TRUE-------------------------------------------------------
c(fcall, fterms, resids, rest) %<-% summary(f)
## ------------------------------------------------------------------------
c(...skip, e, f) %<-% list(1, 2, 3, 4, 5)
skip
e
f
## ------------------------------------------------------------------------
c(begin, ...middle, end) %<-% list(1, 2, 3, 4, 5)
begin
middle
end
## ------------------------------------------------------------------------
c(min_wt, ., ., mean_wt, ., max_wt) %<-% summary(mtcars$wt)
min_wt
mean_wt
max_wt
## ------------------------------------------------------------------------
c(begin, ..., end) %<-% list("hello", "blah", list("blah"), "blah", "world!")
begin
end
## ------------------------------------------------------------------------
c(begin, ., ...middle, end) %<-% as.list(1:5)
begin
middle
end
## ------------------------------------------------------------------------
nums <- 1:2
c(x, y) %<-% tail(nums, 2)
x
y
## ---- error = TRUE-------------------------------------------------------
c(x, y, z) %<-% tail(nums, 3)
## ------------------------------------------------------------------------
c(x, y, z = NULL) %<-% tail(nums, 3)
x
y
z
## ------------------------------------------------------------------------
c(first, last) %<-% c("Ai", "Genly")
first
last
c(first, last) %<-% c(last, first)
first
last
## ------------------------------------------------------------------------
cat <- "meow"
dog <- "bark"
c(cat, dog, fish) %<-% c(dog, cat, dog)
cat
dog
fish
## ---- eval = require("magrittr")-----------------------------------------
library(magrittr)
mtcars %>%
subset(hp > 100) %>%
aggregate(. ~ cyl, data = ., FUN = . %>% mean() %>% round(2)) %>%
transform(kpl = mpg %>% multiply_by(0.4251)) %->%
c(cyl, mpg, ...rest)
cyl
mpg
rest
| /scratch/gouwar.j/cran-all/cranData/zeallot/inst/doc/unpacking-assignment.R |
---
title: "Unpacking Assignment"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Unpacking Assignment}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{R, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(zeallot)
```
## Getting Started
The *zeallot* package defines an operator for *unpacking assignment*, sometimes
called *parallel assignment* or *destructuring assignment* in other programming
languages. The operator is written as `%<-%` and used like this.
```{r}
c(lat, lng) %<-% list(38.061944, -122.643889)
```
The result is that the list is unpacked into its elements,
and the elements are assigned to `lat` and `lng`.
```{r}
lat
lng
```
You can also unpack the elements of a vector.
```{r}
c(lat, lng) %<-% c(38.061944, -122.643889)
lat
lng
```
You can unpack much longer structures, too, of course, such as the 6-part
summary of a vector.
```{r}
c(min_wt, q1_wt, med_wt, mean_wt, q3_wt, max_wt) %<-% summary(mtcars$wt)
min_wt
q1_wt
med_wt
mean_wt
q3_wt
max_wt
```
If the left-hand side and right-hand sides do not match, an error is raised.
This guards against missing or unexpected values.
```{r, error=TRUE}
c(stg1, stg2, stg3) %<-% list("Moe", "Donald")
```
```{r, error=TRUE}
c(stg1, stg2, stg3) %<-% list("Moe", "Larry", "Curley", "Donald")
```
### Unpacking a returned value
A common use-case is when a function returns a list of values
and you want to extract the individual values.
In this example, the list of values returned by `coords_list()` is unpacked
into the variables `lat` and `lng`.
```{r}
#
# A function which returns a list of 2 numeric values.
#
coords_list <- function() {
list(38.061944, -122.643889)
}
c(lat, lng) %<-% coords_list()
lat
lng
```
In this next example, we call a function that returns a vector.
```{r}
#
# Convert cartesian coordinates to polar
#
to_polar = function(x, y) {
c(sqrt(x^2 + y^2), atan(y / x))
}
c(radius, angle) %<-% to_polar(12, 5)
radius
angle
```
### Example: Intercept and slope of regression
You can directly unpack the coefficients of a simple linear regression
into the intercept and slope.
```{r}
c(inter, slope) %<-% coef(lm(mpg ~ cyl, data = mtcars))
inter
slope
```
### Example: Unpacking the result of `safely`
The *purrr* package includes the `safely` function.
It wraps a given function to create a new, "safe" version of the original function.
```{R, eval = require("purrr")}
safe_log <- purrr::safely(log)
```
The safe version returns a list of two items. The first item is the result of
calling the original function, assuming no error occurred; or `NULL` if an error
did occur. The second item is the error, if an error occurred; or `NULL` if no
error occurred. Whether or not the original function would have thrown an error,
the safe version will never throw an error.
```{r, eval = require("purrr")}
pair <- safe_log(10)
pair$result
pair$error
```
```{r, eval = require("purrr")}
pair <- safe_log("donald")
pair$result
pair$error
```
You can tighten and clarify calls to the safe function by using `%<-%`.
```{r, eval = require("purrr")}
c(res, err) %<-% safe_log(10)
res
err
```
## Unpacking a data frame
A data frame is simply a list of columns, so the *zeallot* assignment does
what you expect. It unpacks the data frame into individual columns.
```{r}
c(mpg, cyl, disp, hp) %<-% mtcars[, 1:4]
head(mpg)
head(cyl)
head(disp)
head(hp)
```
### Example: List of data frames
Bear in mind that a list of data frames is still just a list. The assignment
will extract the list elements (which are data frames) but not unpack the data
frames themselves.
```{R}
quartet <- lapply(1:4, function(i) anscombe[, c(i, i + 4)])
c(an1, an2, an3, an4) %<-% lapply(quartet, head, n = 3)
an1
an2
an3
an4
```
The `%<-%` operator assigned four data frames to four variables, leaving the
data frames intact.
## Unpacking nested values
In addition to unpacking flat lists, you can unpack lists of lists.
```{r}
c(a, c(b, d), e) %<-% list("begin", list("middle1", "middle2"), "end")
a
b
d
e
```
Not only does this simplify extracting individual elements, it also adds a level
of checking. If the described list structure does not match the actual list
structure, an error is raised.
```{r, error=TRUE}
c(a, c(b, d, e), f) %<-% list("begin", list("middle1", "middle2"), "end")
```
## Splitting a value into its parts
The previous examples dealt with unpacking a list or vector into its elements.
You can also split certain kinds of individual values into subvalues.
### Character vectors
You can assign individual characters of a string to variables.
```{r}
c(ch1, ch2, ch3) %<-% "abc"
ch1
ch2
ch3
```
### Dates
You can split a Date into its year, month, and day, and assign the parts to
variables.
```{r}
c(y, m, d) %<-% Sys.Date()
y
m
d
```
### Class objects
*zeallot* includes implementations of `destructure` for character strings,
complex numbers, data frames, date objects, and linear model summaries.
However, because `destructure` is a generic function, you can define new
implementations for custom classes. When defining a new implementation keep in
mind the implementation needs to return a list so that values are properly
unpacked.
## Trailing values: the "everything else" clause
In some cases, you want the first few elements of a list or vector but do not
care about the trailing elements. The `summary` function of `lm`, for example,
returns a list of 11 values, and you might want only the first few. Fortunately,
there is a way to capture those first few and say "don't worry about everything
else".
```{r}
f <- lm(mpg ~ cyl, data = mtcars)
c(fcall, fterms, resids, ...rest) %<-% summary(f)
fcall
fterms
head(resids)
```
Here, `rest` will capture everything else.
```{r}
str(rest)
```
The assignment operator noticed that `...rest` is prefixed with `...`, and it
created a variable called `rest` for the trailing values of the list. If you
omitted the "everything else" prefix, there would be an error because the
lengths of the left- and right-hand sides of the assignment would be mismatched.
```{r, error = TRUE}
c(fcall, fterms, resids, rest) %<-% summary(f)
```
If multiple collector variables are specified at a particular depth it is
ambiguous which values to assign to which collector and an error will be raised.
## Leading values and middle values
In addition to collecting trailing values, you can also collect initial values
and assign specific remaining values.
```{r}
c(...skip, e, f) %<-% list(1, 2, 3, 4, 5)
skip
e
f
```
Or you can assign the first value, skip values, and then assign the last value.
```{r}
c(begin, ...middle, end) %<-% list(1, 2, 3, 4, 5)
begin
middle
end
```
## Skipped values: anonymous elements
You can skip one or more values without raising an error by using a period (`.`)
instead of a variable name. For example, you might care only about the min,
mean, and max values of a vector's `summary`.
```{r}
c(min_wt, ., ., mean_wt, ., max_wt) %<-% summary(mtcars$wt)
min_wt
mean_wt
max_wt
```
By combining an anonymous element (`.`) with the collector prefix, (`...`), you
can ignore whole sublists.
```{r}
c(begin, ..., end) %<-% list("hello", "blah", list("blah"), "blah", "world!")
begin
end
```
You can mix periods and collectors together to selectively keep and discard
elements.
```{r}
c(begin, ., ...middle, end) %<-% as.list(1:5)
begin
middle
end
```
It is important to note that although value(s) are skipped they are still
expected. The next section touches on how to handle missing values.
## Default values: handle missing values
You can specify a default value for a left-hand side variable using `=`, similar
to specifying the default value of a function argument. This comes in handy when
the number of elements returned by a function cannot be guaranteed. `tail` for
example may return fewer elements than asked for.
```{r}
nums <- 1:2
c(x, y) %<-% tail(nums, 2)
x
y
```
However, if we tried to get 3 elements and assign them an error would be raised
because `tail(nums, 3)` still returns only 2 values.
```{r, error = TRUE}
c(x, y, z) %<-% tail(nums, 3)
```
We can fix the problem and resolve the error by specifying a default value for
`z`.
```{r}
c(x, y, z = NULL) %<-% tail(nums, 3)
x
y
z
```
## Swapping values
A handy trick is swapping values without the use of a temporary variable.
```{r}
c(first, last) %<-% c("Ai", "Genly")
first
last
c(first, last) %<-% c(last, first)
first
last
```
or
```{r}
cat <- "meow"
dog <- "bark"
c(cat, dog, fish) %<-% c(dog, cat, dog)
cat
dog
fish
```
## Right operator
The `magrittr` package provides a pipe operator `%>%` which allows functions
to be called in succession instead of nested. The left operator `%<-%`
does not work well with these function chains. Instead, the right operator
`%->%` is recommended. The below example is adapted from the `magrittr` readme.
```{r, eval = require("magrittr")}
library(magrittr)
mtcars %>%
subset(hp > 100) %>%
aggregate(. ~ cyl, data = ., FUN = . %>% mean() %>% round(2)) %>%
transform(kpl = mpg %>% multiply_by(0.4251)) %->%
c(cyl, mpg, ...rest)
cyl
mpg
rest
```
| /scratch/gouwar.j/cran-all/cranData/zeallot/inst/doc/unpacking-assignment.Rmd |
---
title: "Unpacking Assignment"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Unpacking Assignment}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{R, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(zeallot)
```
## Getting Started
The *zeallot* package defines an operator for *unpacking assignment*, sometimes
called *parallel assignment* or *destructuring assignment* in other programming
languages. The operator is written as `%<-%` and used like this.
```{r}
c(lat, lng) %<-% list(38.061944, -122.643889)
```
The result is that the list is unpacked into its elements,
and the elements are assigned to `lat` and `lng`.
```{r}
lat
lng
```
You can also unpack the elements of a vector.
```{r}
c(lat, lng) %<-% c(38.061944, -122.643889)
lat
lng
```
You can unpack much longer structures, too, of course, such as the 6-part
summary of a vector.
```{r}
c(min_wt, q1_wt, med_wt, mean_wt, q3_wt, max_wt) %<-% summary(mtcars$wt)
min_wt
q1_wt
med_wt
mean_wt
q3_wt
max_wt
```
If the left-hand side and right-hand sides do not match, an error is raised.
This guards against missing or unexpected values.
```{r, error=TRUE}
c(stg1, stg2, stg3) %<-% list("Moe", "Donald")
```
```{r, error=TRUE}
c(stg1, stg2, stg3) %<-% list("Moe", "Larry", "Curley", "Donald")
```
### Unpacking a returned value
A common use-case is when a function returns a list of values
and you want to extract the individual values.
In this example, the list of values returned by `coords_list()` is unpacked
into the variables `lat` and `lng`.
```{r}
#
# A function which returns a list of 2 numeric values.
#
coords_list <- function() {
list(38.061944, -122.643889)
}
c(lat, lng) %<-% coords_list()
lat
lng
```
In this next example, we call a function that returns a vector.
```{r}
#
# Convert cartesian coordinates to polar
#
to_polar = function(x, y) {
c(sqrt(x^2 + y^2), atan(y / x))
}
c(radius, angle) %<-% to_polar(12, 5)
radius
angle
```
### Example: Intercept and slope of regression
You can directly unpack the coefficients of a simple linear regression
into the intercept and slope.
```{r}
c(inter, slope) %<-% coef(lm(mpg ~ cyl, data = mtcars))
inter
slope
```
### Example: Unpacking the result of `safely`
The *purrr* package includes the `safely` function.
It wraps a given function to create a new, "safe" version of the original function.
```{R, eval = require("purrr")}
safe_log <- purrr::safely(log)
```
The safe version returns a list of two items. The first item is the result of
calling the original function, assuming no error occurred; or `NULL` if an error
did occur. The second item is the error, if an error occurred; or `NULL` if no
error occurred. Whether or not the original function would have thrown an error,
the safe version will never throw an error.
```{r, eval = require("purrr")}
pair <- safe_log(10)
pair$result
pair$error
```
```{r, eval = require("purrr")}
pair <- safe_log("donald")
pair$result
pair$error
```
You can tighten and clarify calls to the safe function by using `%<-%`.
```{r, eval = require("purrr")}
c(res, err) %<-% safe_log(10)
res
err
```
## Unpacking a data frame
A data frame is simply a list of columns, so the *zeallot* assignment does
what you expect. It unpacks the data frame into individual columns.
```{r}
c(mpg, cyl, disp, hp) %<-% mtcars[, 1:4]
head(mpg)
head(cyl)
head(disp)
head(hp)
```
### Example: List of data frames
Bear in mind that a list of data frames is still just a list. The assignment
will extract the list elements (which are data frames) but not unpack the data
frames themselves.
```{R}
quartet <- lapply(1:4, function(i) anscombe[, c(i, i + 4)])
c(an1, an2, an3, an4) %<-% lapply(quartet, head, n = 3)
an1
an2
an3
an4
```
The `%<-%` operator assigned four data frames to four variables, leaving the
data frames intact.
## Unpacking nested values
In addition to unpacking flat lists, you can unpack lists of lists.
```{r}
c(a, c(b, d), e) %<-% list("begin", list("middle1", "middle2"), "end")
a
b
d
e
```
Not only does this simplify extracting individual elements, it also adds a level
of checking. If the described list structure does not match the actual list
structure, an error is raised.
```{r, error=TRUE}
c(a, c(b, d, e), f) %<-% list("begin", list("middle1", "middle2"), "end")
```
## Splitting a value into its parts
The previous examples dealt with unpacking a list or vector into its elements.
You can also split certain kinds of individual values into subvalues.
### Character vectors
You can assign individual characters of a string to variables.
```{r}
c(ch1, ch2, ch3) %<-% "abc"
ch1
ch2
ch3
```
### Dates
You can split a Date into its year, month, and day, and assign the parts to
variables.
```{r}
c(y, m, d) %<-% Sys.Date()
y
m
d
```
### Class objects
*zeallot* includes implementations of `destructure` for character strings,
complex numbers, data frames, date objects, and linear model summaries.
However, because `destructure` is a generic function, you can define new
implementations for custom classes. When defining a new implementation keep in
mind the implementation needs to return a list so that values are properly
unpacked.
## Trailing values: the "everything else" clause
In some cases, you want the first few elements of a list or vector but do not
care about the trailing elements. The `summary` function of `lm`, for example,
returns a list of 11 values, and you might want only the first few. Fortunately,
there is a way to capture those first few and say "don't worry about everything
else".
```{r}
f <- lm(mpg ~ cyl, data = mtcars)
c(fcall, fterms, resids, ...rest) %<-% summary(f)
fcall
fterms
head(resids)
```
Here, `rest` will capture everything else.
```{r}
str(rest)
```
The assignment operator noticed that `...rest` is prefixed with `...`, and it
created a variable called `rest` for the trailing values of the list. If you
omitted the "everything else" prefix, there would be an error because the
lengths of the left- and right-hand sides of the assignment would be mismatched.
```{r, error = TRUE}
c(fcall, fterms, resids, rest) %<-% summary(f)
```
If multiple collector variables are specified at a particular depth it is
ambiguous which values to assign to which collector and an error will be raised.
## Leading values and middle values
In addition to collecting trailing values, you can also collect initial values
and assign specific remaining values.
```{r}
c(...skip, e, f) %<-% list(1, 2, 3, 4, 5)
skip
e
f
```
Or you can assign the first value, skip values, and then assign the last value.
```{r}
c(begin, ...middle, end) %<-% list(1, 2, 3, 4, 5)
begin
middle
end
```
## Skipped values: anonymous elements
You can skip one or more values without raising an error by using a period (`.`)
instead of a variable name. For example, you might care only about the min,
mean, and max values of a vector's `summary`.
```{r}
c(min_wt, ., ., mean_wt, ., max_wt) %<-% summary(mtcars$wt)
min_wt
mean_wt
max_wt
```
By combining an anonymous element (`.`) with the collector prefix, (`...`), you
can ignore whole sublists.
```{r}
c(begin, ..., end) %<-% list("hello", "blah", list("blah"), "blah", "world!")
begin
end
```
You can mix periods and collectors together to selectively keep and discard
elements.
```{r}
c(begin, ., ...middle, end) %<-% as.list(1:5)
begin
middle
end
```
It is important to note that although value(s) are skipped they are still
expected. The next section touches on how to handle missing values.
## Default values: handle missing values
You can specify a default value for a left-hand side variable using `=`, similar
to specifying the default value of a function argument. This comes in handy when
the number of elements returned by a function cannot be guaranteed. `tail` for
example may return fewer elements than asked for.
```{r}
nums <- 1:2
c(x, y) %<-% tail(nums, 2)
x
y
```
However, if we tried to get 3 elements and assign them an error would be raised
because `tail(nums, 3)` still returns only 2 values.
```{r, error = TRUE}
c(x, y, z) %<-% tail(nums, 3)
```
We can fix the problem and resolve the error by specifying a default value for
`z`.
```{r}
c(x, y, z = NULL) %<-% tail(nums, 3)
x
y
z
```
## Swapping values
A handy trick is swapping values without the use of a temporary variable.
```{r}
c(first, last) %<-% c("Ai", "Genly")
first
last
c(first, last) %<-% c(last, first)
first
last
```
or
```{r}
cat <- "meow"
dog <- "bark"
c(cat, dog, fish) %<-% c(dog, cat, dog)
cat
dog
fish
```
## Right operator
The `magrittr` package provides a pipe operator `%>%` which allows functions
to be called in succession instead of nested. The left operator `%<-%`
does not work well with these function chains. Instead, the right operator
`%->%` is recommended. The below example is adapted from the `magrittr` readme.
```{r, eval = require("magrittr")}
library(magrittr)
mtcars %>%
subset(hp > 100) %>%
aggregate(. ~ cyl, data = ., FUN = . %>% mean() %>% round(2)) %>%
transform(kpl = mpg %>% multiply_by(0.4251)) %->%
c(cyl, mpg, ...rest)
cyl
mpg
rest
```
| /scratch/gouwar.j/cran-all/cranData/zeallot/vignettes/unpacking-assignment.Rmd |
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
compute_observed_probability <- function(x, number_of_samples, number_of_dims, number_of_cells, number_of_levels) {
.Call('_zebu_compute_observed_probability', PACKAGE = 'zebu', x, number_of_samples, number_of_dims, number_of_cells, number_of_levels)
}
compute_expected_probability <- function(margins) {
.Call('_zebu_compute_expected_probability', PACKAGE = 'zebu', margins)
}
compute_marginal_probability <- function(x, number_of_samples, number_of_dims, number_of_cells, number_of_levels) {
.Call('_zebu_compute_marginal_probability', PACKAGE = 'zebu', x, number_of_samples, number_of_dims, number_of_cells, number_of_levels)
}
#' Estimate marginal and multivariate probabilities
#'
#' Maximum-likelihood estimation of marginal and multivariate observed and expected independence probabilities. Marginal probability refers to probability of each factor per individual column. Multivariate probability refer to cross-classifying factors for all columns.
#'
#' @param x data.frame or matrix.
#'
#' @return List containing the following values:
#' \itemize{
#' \item margins: a list of marginal probabilities. Names correspond to colnames(x).
#' \item observed: observed multivariate probability array.
#' \item expected: expected multivariate probability array
#' }
#'
#' @example /inst/examples/lassie.R
#'
#' @export
estimate_prob <- function(x) {
.Call('_zebu_estimate_prob', PACKAGE = 'zebu', x)
}
#' @title Local Association Measures
#'
#' @description Subroutines called by \code{\link[zebu]{lassie}} to compute
#' local and global association measures from a list of probabilities.
#'
#' @param x list of probabilities as outputted by \code{\link[zebu]{estimate_prob}}.
#' @param measure name of measure to be used:
#' \itemize{
#' \item'chisq': Chi-squared residuals.
#' \item'd': Lewontin's D.
#' \item'z': Ducher's 'z'.
#' \item'pmi': Pointwise mutual information (in bits).
#' \item'npmi': Normalized pointwise mutual information (Bouma).
#' \item'npmi2': Normalized pointwise mutual information (Multivariate).
#' }
#' @param nr number of rows/samples. Only used to estimate chi-squared residuals.
#'
#' @return List containing the following values:
#' \itemize{
#' \item local: local association array (may contain NA, NaN and Inf values).
#' \item global: global association numeric value.
#' }
#'
#'
#' @seealso \code{\link[zebu]{lassie}}
#'
#' @example /inst/examples/lassie.R
#'
#' @name local_association
#'
#' @export
local_association <- function(x, measure = "chisq", nr = 1) {
.Call('_zebu_local_association', PACKAGE = 'zebu', x, measure, nr)
}
#' @rdname local_association
#' @export
lewontin_d <- function(x) {
.Call('_zebu_lewontin_d', PACKAGE = 'zebu', x)
}
#' @rdname local_association
#' @export
duchers_z <- function(x) {
.Call('_zebu_duchers_z', PACKAGE = 'zebu', x)
}
#' @rdname local_association
#' @param normalize 0 for pmi, 1 for npmi, 2 for npmi2
#' @export
pmi <- function(x, normalize) {
.Call('_zebu_pmi', PACKAGE = 'zebu', x, normalize)
}
#' @rdname local_association
#' @export
chisq <- function(x, nr) {
.Call('_zebu_chisq', PACKAGE = 'zebu', x, nr)
}
permute_dataframe <- function(x, group) {
.Call('_zebu_permute_dataframe', PACKAGE = 'zebu', x, group)
}
permtest_rcpp <- function(x, nb, group) {
.Call('_zebu_permtest_rcpp', PACKAGE = 'zebu', x, nb, group)
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/RcppExports.R |
#' Chi-squared test
#'
#' Chi-squared test: statistical significance of (global) chi-squared statistic
#' and (local) chi-squared residuals
#'
#' @param x \code{\link[zebu]{lassie}} S3 object.
#'
#' @param p_adjust multiple testing correction method.
#' (see \code{\link[stats]{p.adjust.methods}} for a list of methods).
#'
#' @return \code{chisqtest} returns an S3 object of \link[base]{class}
#' \code{\link[zebu]{lassie}} and \code{\link[zebu]{chisqtest}}.
#' Adds the following to the lassie object \code{x}:
#' \itemize{
#' \item global_p: global association p-value.
#' \item local_p: array of local association p-values.
#' }
#'
#' @seealso \code{\link[zebu]{lassie}}
#'
#' @examples
#'
#' # Calling lassie on cars dataset
#' las <- lassie(cars, continuous = colnames(cars), measure = "chisq")
#'
#' # Permutation test using default settings
#' chisqtest(las)
#'
#' @export
#' @import data.table
#'
chisqtest <- function(x, p_adjust = "BH") {
# Check arguments ----
if (! "lassie" %in% class(x)) {
stop("Invalid 'x' argument: must be a 'lassie' object")
}
if (! p_adjust %in% stats::p.adjust.methods) {
stop(paste("Invalid 'p_adjust' argument: methods supported are", stats::p.adjust.methods))
}
# Compute general variables ----
dimensions <- dim(x$prob$observed) # Dimensions
dim_names <- dimnames(x$prob$observed) # Dimension names
measure <- x$lassie_params[["measure"]] # Get association measure used
if (measure != "chisq" | length(dimensions) != 2) {
stop(paste("This function is only valid for the chi-squared method and two dimensions."))
}
# Compute p-values ----
global_p <- stats::pchisq(x$global, df = prod(dimensions - 1), lower.tail = FALSE)
local_p <- 2 * (1 - stats::pnorm(abs(x$local)))
# Multiple test correction
local_p <- stats::p.adjust(local_p, method = p_adjust)
# Format to array
local_p <- array(local_p, dim = dimensions, dimnames = dim_names)
x[["global_p"]] <- global_p
x[["local_p"]] <- local_p
structure(x, class = c(class(x), "chisqtest"))
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/chisqtest.R |
#' @title Local Association Measures
#'
#' @description Estimates local (and global) association measures: Ducher's Z, Lewontin's D, pointwise mutual
#' information, normalized pointwise mutual information and chi-squared residuals.
#'
#' @inheritParams preprocess
#' @inheritParams local_association
#'
#' @return An instance of S3 \link[base]{class} \code{\link[zebu]{lassie}} with
#' the following objects:
#' \itemize{
#' \item data: raw and preprocessed data.frames (see \link[zebu]{preprocess}).
#' \item prob probability arrays (see \link[zebu]{estimate_prob}).
#' \item global global association (see \link[zebu]{local_association}).
#' \item local local association arrays (see \link[zebu]{local_association}).
#' \item lassie_params parameters used in lassie.
#' }
#'
#' @seealso Results can be visualized using \code{\link[zebu]{plot.lassie}} and
#' \code{\link[zebu]{print.lassie}}
#' methods. \code{\link[zebu]{plot.lassie}} is only available
#' in the bivariate case and returns
#' a tile plot representing the probability or local association measure matrix.
#' \code{\link[zebu]{print.lassie}} shows an array or a data.frame.
#'
#' Results can be saved using \code{\link[zebu]{write.lassie}}.
#'
#' The \code{\link[zebu]{permtest}} function accesses the significance of local and global
#'association values using p-values estimated by permutations.
#'
#' The \code{\link[zebu]{chisqtest}} function accesses the significance in the case
#' of two dimensional chi-squared analysis.
#'
#' @examples
#' # In this example, we will use the 'mtcars' dataset
#'
#' # Selecting a subset of mtcars.
#' # Takes column names or numbers.
#' # If nothing was specified, all variables would have been used.
#' select <- c('mpg', 'cyl') # or select <- c(1, 2)
#'
#' # Specifying 'mpg' as a continuous variables using column numbers
#' # Takes column names or numbers.
#' # If nothing was specified, all variables would have been used.
#' continuous <- 'mpg' # or continuous <- 1
#'
#' # How should breaks be specified?
#' # Specifying equal-width discretization with 5 bins for all continuous variables ('mpg')
#' # breaks <- 5
#'
#' # Specifying user-defined breakpoints for all continuous variables.
#' # breaks <- c(10, 15, 25, 30)
#'
#' # Same thing but only for 'mpg'.
#' # Here both notations are equivalent because 'mpg' is the only continuous variable.
#' # This notation is useful if you wish to specify different break points for different variables
#' # breaks <- list('mpg' = 5)
#' # breaks <- list('mpg' = c(10, 15, 25, 30))
#'
#' # Calling lassie
#' # Not specifying breaks means that the value in default_breaks (4) will be used.
#' las <- lassie(mtcars, select = c(1, 2), continuous = 1)
#'
#' # Print local association to console as an array
#' print(las)
#'
#' # Print local association and probabilities
#' # Here only rows having a positive local association are printed
#' # The data.frame is also sorted by observed probability
#' print(las, type = 'df', range = c(0, 1), what_sort = 'obs')
#'
#' # Plot results as heatmap
#' plot(las)
#'
#' # Plot observed probabilities using different colors
#' plot(las, what_x = 'obs', low = 'white', mid = 'grey', high = 'black', text_colour = 'red')
#'
#' @export
#'
lassie <- function(x,
select,
continuous,
breaks,
measure = "chisq",
default_breaks = 4) {
# Preprocess data (handle missing data and discretize continuous variables)
pre <- preprocess(x,
select = select,
continuous = continuous,
breaks = breaks,
default_breaks = default_breaks)
# Compute probabilities
prob <- estimate_prob(pre$pp)
# Compute local and global association
nr <- nrow(x)
lam <- local_association(prob, measure, nr)
global <- lam$global
local <- lam$local
# Retrieve variable and measure names
lassie_params <- list(var = colnames(pre$pp),
measure = measure,
select = pre$select,
continuous = pre$continuous,
breaks = pre$breaks,
default_breaks = pre$default_breaks)
# Return lassie and 'measure' S3 object
structure(list(data = pre,
prob = prob,
global = global,
local = local,
lassie_params = lassie_params),
class = c("lassie"))
}
#' @title Print a lassie object
#'
#' @description Print a \code{\link[zebu]{lassie}} object as an array or a data.frame.
#'
#' @inheritParams lassie_get
#' @inheritParams format.lassie
#'
#' @param type print style: 'array' for array or 'df' for data.frame.
#' @param ... other arguments passed on to methods. Not currently used.
#'
#' @seealso \code{\link[zebu]{lassie}}, \code{\link[zebu]{permtest}}, \code{\link[zebu]{chisqtest}}
#'
#' @export
#'
print.lassie <- function(x,
type,
what_x,
range,
what_range,
what_sort,
decreasing,
na.rm,
...) {
# Check arguments
if (missing(type) || is.null(type)) {
if (ncol(x$data$pp) == 2) {
type <- "array"
} else {
type <- "df"
}
} else if (!type %in% c("array", "df")) {
stop("Invalid 'type' argument: choose from\n 'array': Array\n 'df' Melt array into a data frame")
}
if (missing(range)) {
range <- NULL
}
# Format for array
if (type == "array") {
if (missing(what_x) || is.null(what_x)) {
what_x <- "local"
}
print_x <- lassie_get(x, what_x)
if (!is.null(range)) {
range_x <- lassie_get(x, what_range)
in_range <- !is.na(range_x) & range_x >= range[1] & range_x <= range[2]
print_x[which(!in_range, arr.ind = TRUE)] <- NA_real_
}
# Format for data.frame
} else if (type == "df") {
if (missing(what_x)) {
what_x <- NULL
}
if (missing(what_range)) {
what_range <- NULL
}
if (missing(what_sort)) {
what_sort <- NULL
}
if (missing(decreasing)) {
decreasing <- NULL
}
if (missing(na.rm)) {
na.rm <- NULL
}
print_x <- format.lassie(x,
what_x = what_x,
range = range,
what_range = what_range,
what_sort = what_sort,
decreasing = decreasing,
na.rm = na.rm)
}
# Make header (measure name and global association value)
header <- paste0("Measure: ", measure_name(x), "\nGlobal: ", round(x$global, digits = 3))
if (! is.null(x$global_p)) {
global_p <- x$global_p
if (global_p == 0) global_p <- paste0("<1/", x$perm_params$nb)
header <- paste0(header, " (p-value: ", format(global_p, scientific = TRUE, digits = 3), ")")
}
header <- paste0(header, "\n")
# Replace null p-values
if ("local_p" %in% what_x) {
print_x[print_x == 0] <- paste0("<1/", x$perm_params$nb)
}
# Print to console
cat(header)
print(print_x)
invisible(x)
}
#' @title Format a lassie object
#'
#' @description Formats a \code{\link[zebu]{lassie}} object for printing to console
#' (see \code{\link[zebu]{print.lassie}}) and for writing to a file
#' (see \code{\link[zebu]{write.lassie}}). Melts probability or local association
#' measure arrays into a data.frame.
#'
#' @inheritParams lassie_get
#' @param range range of values to be retained (vector of two numeric values).
#' @param what_range character specifying what value \code{range} refers to
#' (same options as \code{what_x}).
#' By default, takes the first value in \code{what_x}.
#' @param what_sort character specifying according to which values should \code{x} be sorted
#' (same options as \code{what_x}).
#' By default, takes the first value in \code{what_x}.
#' @param decreasing logical value specifying sort order.
#' @param na.rm logical value indicating whether NA values should be stripped.
#' @param ... other arguments passed on to methods. Not currently used.
#'
#' @seealso \code{\link[zebu]{lassie}}
#'
#' @export
#'
format.lassie <- function(x,
what_x,
range,
what_range,
what_sort,
decreasing,
na.rm, ...) {
# Check arguments
if (missing(what_x) || is.null(what_x)) {
what_x <- c("local", "obs", "exp")
if ("permtest" %in% class(x) | "chisqtest" %in% class(x))
what_x <- c(what_x, "local_p")
}
if (missing(na.rm) || is.null(na.rm)) {
na.rm <- FALSE
}
# Melt array to data frame
local <- reshape2::melt(x$local)
format_x <- local[, 1:(ncol(local) - 1)]
for (i in what_x) {
format_x[i] <- reshape2::melt(lassie_get(x, i))$value
}
# Retain only rows that in the specified range
if (!missing(range) && !is.null(range)) {
if (missing(what_range) || is.null(what_range)) {
what_range <- what_x[1]
} else if (any(!what_range %in% what_x)) {
stop("Invalid 'what_range' argument: values must also be present in 'what_x' argument")
}
if (length(what_range) > 1) {
stop("Invalid 'what_range' argument: can only handle one variable name")
}
if (missing(na.rm)) {
na.rm <- FALSE
}
range_x <- lassie_get(x, what_range)
in_range <- !is.na(range_x) & range_x >= range[1] & range_x <= range[2]
format_x <- format_x[in_range, ]
}
# Sort data frame
if (missing(what_sort) || is.null(what_sort)) {
what_sort <- what_x[1]
} else if (any(!what_sort %in% colnames(format_x))) {
stop(paste("Invalid 'what_sort' argument: Choose from:",
paste(colnames(format_x), collapse = ", ")))
}
index <- do.call("order", subset(format_x, select = what_sort))
# Reverse sort order
if (missing(decreasing) || is.null(decreasing))
decreasing <- TRUE
if (decreasing) {
index <- rev(index)
}
format_x <- format_x[index, ]
if (na.rm) {
format_x <- stats::na.omit(format_x)
}
# Replace null p-values
if ("local_p" %in% what_x) {
format_x$local_p[format_x$local_p == 0] <- paste0("<1/", x$perm_params$nb)
}
format_x
}
#' @title Plot a lassie object
#'
#' @description Plots a \code{\link[zebu]{lassie}} object as a tile plot using
#' the ggplot2 package. Only available for bivariate association.
#' @inheritParams lassie_get
#'
#' @param digits integer indicating the number of decimal places.
#' @param low colour for low end of the gradient.
#' @param mid colour for midpoint of the gradient.
#' @param high colour for high end of the gradient.
#' @param na colour for NA values.
#' @param text_colour colour of text inside cells.
#' @param text_size integer indicating text size inside cells.
#' @param limits limits of gradient.
#' @param midpoint midpoint of gradient.
#' @param ... other arguments passed on to methods. Not currently used.
#'
#' @seealso \code{\link[zebu]{lassie}}
#'
#' @export
#'
plot.lassie <- function(x,
what_x = "local",
digits = 3,
low = "royalblue",
mid = "gainsboro",
high = "firebrick",
na = "purple",
text_colour = "black",
text_size,
limits,
midpoint,
...) {
# Check if lassie object is bivariate
if (ncol(x$data$pp) != 2) {
stop("Cannot make tile plot for more than 2 variables.\n Use 'print()' function to visualize results.")
}
# Define text size in cells
if (missing(text_size)) {
if (what_x == "local" & ("permtest" %in% class(x) | "chisqtest" %in% class(x))) {
text_size <- 4
} else {
text_size <- 5
}
}
# Get values from lassie object
measure <- x$lassie_params$measure
tile_value <- lassie_get(x, what_x)
tile_value[is.infinite(tile_value) | is.nan(tile_value)] <- NA
tile_text <- as.character(round(tile_value, digits))
# Define limits of gradients
if (missing(limits) || is.null(limits)) {
if (what_x %in% c("local")) {
midpoint <- 0
if (measure %in% c("z", "npmi", "npmi2")) {
limits <- c(-1.00001, 1.00001)
} else if (measure %in% c("d", "pmi", "chisq")) {
limits <- range(tile_value, na.rm = TRUE)
} else {
stop("Invalid measure.")
}
} else {
# Probabilities
limits <- c(0, 1)
midpoint <- 0.5
}
}
# Define midpoint of gradient
if (missing(midpoint) || is.null(midpoint)) {
if (what_x %in% c("local")) {
midpoint <- 0
} else {
midpoint <- 0.5
}
}
# Format values to be displayed in cells
if (what_x == "obs" | what_x == "exp") {
tile_text <- paste0(tile_text, "\n", round(nrow(x$data$pp) * tile_value, digits))
} else if (what_x == "local" & ("permtest" %in% class(x) | "chisqtest" %in% class(x))) {
null_local_p <- x$local_p == 0
local_p <- format(x$local_p, digits = digits, scientific = TRUE)
local_p[null_local_p] <- paste0("<1/", x$perm_params$nb)
tile_text <- paste0(tile_text, "\n(", local_p, ")")
}
# Format values in data.frame for ggplot2
ggdf <- data.frame(reshape2::melt(tile_value), tile_text, stringsAsFactors = FALSE)
colnames(ggdf) <- c("Rows", "Columns", "Value", "Text")
ggdf$Text[is.na(tile_value)] <- ""
axis_labels <- names(dimnames(tile_value))
# Make title
title <- paste0(measure_name(x), "\nGlobal: ", round(x$global, digits))
if (! is.null(x$global_p)) {
global_p <- x$global_p
if (global_p == 0) global_p <- paste0("<1/", x$perm_params$nb)
title <- paste0(title, " (p-value: ", format(global_p, digits = digits, scientific = TRUE), ")")
}
# Plot as tiles
ggp <- ggplot2::ggplot(ggdf, ggplot2::aes_string(x = "factor(Columns)",
y = "factor(Rows)",
fill = "Value")) +
ggplot2::geom_tile() +
ggplot2::geom_text(ggplot2::aes_string(label = "Text"),
size = text_size,
colour = text_colour) +
ggplot2::scale_fill_gradient2(low = low,
mid = mid,
high = high,
na.value = na,
midpoint = midpoint,
limits = limits,
name = NULL) +
ggplot2::ggtitle(title) +
ggplot2::xlab(axis_labels[2]) +
ggplot2::ylab(axis_labels[1]) +
ggplot2::theme_minimal(base_size = 13) +
ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 1),
axis.ticks = ggplot2::element_blank(),
panel.grid = ggplot2::element_blank(),
axis.line = ggplot2::element_blank())
ggp
}
#' @title Write a lassie object
#'
#' @description Writes \code{\link[zebu]{lassie}} object to a file in a table structured format.
#'
#' @inheritParams utils::write.table
#'
#' @param x \code{\link[zebu]{lassie}} S3 object.
#' @param file character string naming a file.
#' @param ... other arguments passed on to write.table.
#'
#' @seealso \code{\link[zebu]{lassie}}, \code{\link[zebu]{permtest}}, \code{\link[zebu]{chisqtest}}
#'
#' @export
#'
write.lassie <- function(x,
file,
sep = ",",
dec = ".",
col.names = TRUE,
row.names = FALSE,
quote = TRUE,
...) {
if (missing(file) || is.null(file)) {
stop("Invalid 'file' argument: please use a character string naming a file ")
}
if (sep == dec) {
stop("Column separator ('sep') cannot be the same as decimal separator ('dec')")
}
com <- generate_comments(x)
writeLines(text = com, con = file)
# Suppress warnings because append is set to TRUE
suppressWarnings(utils::write.table(format.lassie(x), file = file, append = TRUE, ...))
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/lassie.R |
#' @title Return the value of 'lassie' object
#'
#' @description Subroutine for \code{\link[zebu]{lassie}} methods. Tries to retrieve a value from a \code{\link[zebu]{lassie}} object
#' and gives an error if value does not exist.
#'
#' @param x \code{\link[zebu]{lassie}} S3 object.
#' @param what_x vector specifying values to be returned:
#' \itemize{
#' \item 'local': local association measure values (default).
#' \item 'obs': observed probabilities.
#' \item 'exp': expected probabilities.
#' \item 'local_p': p-value of local association (after running \code{\link[zebu]{permtest}} or \code{\link[zebu]{chisqtest}}).
#' }
#'
#' @return Corresponding array contained in \code{\link[zebu]{lassie}} object.
#'
#' @examples
#' las <- lassie(trees)
#' las_array <- lassie_get(las, 'local')
#'
#' @export
#'
lassie_get <- function(x,
what_x) {
if (length(what_x) != 1 || ! what_x %in% c("local", "obs", "exp", "local_p")) {
stop("Invalid argument: choose one from\n 'local': Local association measure\n 'obs': Observed multivariate probabilities\n 'exp': Expected multivariate probabilities (independence)\n 'local_p: p-value of local association (after running permtest or chisqtest)")
}
if (! ("permtest" %in% class(x) | "chisqtest" %in% class(x)) && any(c("local_p") %in% what_x)) {
stop("Invalid 'what' argument: 'local_p' is only available after running permtest or chisqtest")
}
if (what_x == "local") {
x$local
} else if (what_x == "obs") {
x$prob$observed
} else if (what_x == "exp") {
x$prob$exp
} else if (what_x == "local_p") {
x$local_p
}
}
# Returns full local association measure name used in lassie object.
measure_name <- function(x) {
measure <- x$lassie_params[["measure"]]
if (measure == "z") {
"Ducher's Z"
} else if (measure == "d") {
"Lewontin's D"
} else if (measure == "pmi") {
"Pointwise Mutual Information"
} else if (measure == "npmi") {
"Normalized Pointwise Mutual Information (Bouma)"
} else if (measure == "npmi2") {
"Normalized Pointwise Mutual Information (Multivariate)"
} else if (measure == "chisq") {
"Chi-squared Residuals"
} else {
stop("Invalid 'measure' argument.")
}
}
# Generate comments for header of write.lassie file
generate_comments <- function(x) {
com <- paste0("# File generated by the zebu R package (", Sys.time(), ")\n",
"# https://github.com/oliviermfmartin/zebu\n", "#\n", "# Name of association measure: ",
measure_name(x), "\n", "# Global association value: ", x$global)
if ("permtest" %in% class(x) | "chisqtest" %in% class(x)) {
com <- paste0(com, "\n#\n", "# Permutation test parameters\n", "# Number of iterations: ",
x$perm_params$nb, "\n", "# P-value adjustment method: ", x$perm_params$p_adjust)
}
com <- paste0(com, "\n#")
com
}
.compute_expected_probability <- function(margins) {
Reduce(outer, margins)
}
.compute_theoretical_max_prob <- function(margins) {
Reduce(function(x, y) outer(x, y, pmin), margins)
}
.compute_theoretical_min_prob <- function(margins) {
M <- length(margins)
out <- Reduce(function(x, y) outer(x, y, `+`), margins)
out <- out - M + 1
out[out<0] <- 0
out
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/misc.R |
#' Permutation test for local and global association measures
#'
#' Permutation test: statistical significance of local and
#' global association measures
#'
#' @param x \code{\link[zebu]{lassie}} S3 object.
#'
#' @param nb number of resampling iterations.
#'
#' @param group list of column names specifying which columns
#' should be permuted together. This is useful for the multivariate case,
#' for example, when there is many dependent variables and one
#' independent variable. By default, permutes all columns separately.
#'
#' @param p_adjust multiple testing correction method.
#' (see \code{\link[stats]{p.adjust.methods}} for a list of methods).
#'
#' @return \code{permtest} returns an S3 object of \link[base]{class}
#' \code{\link[zebu]{lassie}} and \code{\link[zebu]{permtest}}.
#' Adds the following to the lassie object \code{x}:
#' \itemize{
#' \item global_p: global association p-value.
#' \item local_p: array of local association p-values.
#' \item global_perm: numeric global association values obtained with permutations.
#' \item local_perm: matrix local association values obtained with permutations. Column number correspond to positions in local association array after converting to numeric (e.g. local_perm[, 1] corresponds to local[1]).
#' \item perm_params: parameters used when calling permtest (nb and p_adjust).
#' }
#'
#' @seealso \code{\link[zebu]{lassie}}
#'
#' @examples
#'
#' # Calling lassie on cars dataset
#' las <- lassie(cars, continuous = colnames(cars))
#'
#' # Permutation test using default settings
#' permtest(las, nb = 30) # keep resampling low for example
#'
#' @export
#' @import data.table
#'
permtest <- function(x,
nb = 1000L,
group = as.list(colnames(x$data$pp)),
p_adjust = "BH") {
# Estimate p-value
p_value = function(observed_value, permuted_values) {
sum(abs(observed_value) < abs(permuted_values)) / length(permuted_values)
}
# Check arguments ----
if (! "lassie" %in% class(x)) {
stop("Invalid 'x' argument: must be a 'lassie' object")
}
if (! is.numeric(nb) || nb <= 1) {
stop("Invalid 'nb' argument: must a numeric")
}
if (! p_adjust %in% stats::p.adjust.methods) {
stop(paste("Invalid 'p_adjust' argument: methods supported are", stats::p.adjust.methods))
}
if (! is.list(group)) {
stop("Invalid 'group' argument: must be a list of characters that correspond to colnames.")
}
# Compute general variables ----
dimensions <- dim(x$prob$observed) # Dimensions
dim_names <- dimnames(x$prob$observed) # Dimension names
measure <- x$lassie_params[["measure"]] # Get association measure used
perm_params <- list(nb = nb, p_adjust = p_adjust) # Save parameters in list
# Convert group argument integers to characters refering to colnames
if (any(! unlist(group) %in% colnames(x$data$pp))) {
stop("Invalid 'group' argument: must be a list of characters that correspond colnames.")
}
# Resampling ----
permutations <- permtest_rcpp(x, nb, group)
# Compute p-values ----
# Compute global p-value
global_perm <- sapply(permutations, `[[`, "global")
global_p <- p_value(x$global, global_perm)
# Format local measure results to matrix: rows are local measure cells and
# columns are resampling iterations
local_perm <- sapply(permutations, `[[`, "local")
# browser()
# Compute local p-value for each cell
local_p <- sapply(seq_len(length(x$local)), function(i) {
# Retrieve observed value and permutation vector
local_i <- x$local[i]
local_perm_i <- local_perm[i, ]
# If observed value is non-numerical (NA, NaN of Inf), return NA for p-value
if (is.infinite(local_i) | is.na(local_i) | is.nan(local_i)) {
return(NA_real_)
}
# Remove NA and NaNs values from permutations
local_perm_i <- local_perm_i[! (is.na(local_perm_i) | is.nan(local_perm_i))]
# Replace Inf values by the largest integer which can be represented
inf <- is.infinite(local_perm_i)
local_perm_i[inf] <- sign(local_perm_i[inf]) * .Machine$integer.max
# Estimate p-value by intersection
p_value(local_i, local_perm_i)
})
# Multiple test correction
local_p <- stats::p.adjust(local_p, method = p_adjust)
# Format to array
local_p <- array(local_p, dim = dimensions, dimnames = dim_names)
x[["global_p"]] <- global_p
x[["local_p"]] <- local_p
x[["global_perm"]] <- global_perm
x[["local_perm"]] <- local_perm
x[["perm_params"]] <- perm_params
structure(x, class = c(class(x), "permtest"))
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/permtest.R |
#' @title Preprocess data
#'
#' @description Subroutine called by \code{\link[zebu]{lassie}}. Discretizes, subsets and remove missing data from a data.frame.
#'
#' @param x data.frame or matrix.
#'
#' @param select optional vector of column numbers or column names
#' specifying a subset of data to be used. By default, uses all columns.
#'
#' @param continuous optional vector of column numbers or column names specifying
#' continuous variables that should be discretized.
#' By default, assumes that every variable is categorical.
#'
#' @param breaks numeric vector or list passed on to \code{\link[base]{cut}} to discretize
#' continuous variables. When a numeric vector is specified, break points are
#' applied to all continuous variables. In order to specify variable-specific
#' breaks, lists are used. List names identify variables and list values identify
#' breaks. List names are column names (not numbers). If a continuous
#' variable has no specified breaks, then \code{default_breaks} will be applied.
#'
#' @param default_breaks default break points for discretizations.
#' Same syntax as in \code{\link[base]{cut}}.
#'
#' @return List containing the following values:
#' \itemize{
#' \item raw: raw subsetted data.frame
#' \item pp: discretized, subsetted and complete data.frame
#' \item select
#' \item continuous
#' \item breaks
#' \item default_breaks
#' }
#'
#' @example /inst/examples/lassie.R
#'
#' @export
#'
preprocess <- function(x,
select,
continuous,
breaks,
default_breaks = 4) {
# Try to convert 'x' to data.frame
x <- tryCatch(as.data.table(x), error = function(c) {
stop("Invalid 'x' argument: must be convertible to a data.frame")
})
# Be sure to have colnames
if (is.null(colnames(x))) {
colnames(x) <- paste("V", seq_len(ncol(x)))
}
# Handle missing arguments
if (missing(select) || is.null(select)) {
select <- colnames(x)
}
if (missing(continuous) || is.null(continuous)) {
continuous <- character(0L)
}
# Handle missing 'breaks' arguments
if (missing(breaks) || is.null(breaks)) {
breaks <- default_breaks
}
# Convert numeric columns to characters
if (all(is.numeric(select))) {
select <- colnames(x)[select]
}
if (all(is.numeric(continuous))) {
continuous <- colnames(x)[continuous]
}
# Check if 'continuous' variables not in 'subset'
if (any(! continuous %in% select)) {
stop("Invalid 'continous' argument: contains variables names not in 'select' argument")
}
# Categorical variables are variables that are not continuous
categorical <- setdiff(select, continuous)
# Breaks define as list
if (is.list(breaks)) {
if (is.null(names(breaks))) {
stop("Invalid 'breaks' argument: breaks does not have any names. Must correspond to colnames in 'x'")
# Check if breaks names are in continuous
} else if (any(!names(breaks) %in% select)) {
stop("Invalid 'breaks' argument: contains variable names not in 'continuous'")
}
# Breaks specified as numeric vector
} else if (all((is.numeric(breaks) && all(! is.na(breaks))))) {
breaks <- rep(list(breaks), length(continuous))
names(breaks) <- continuous
} else {
stop("Invalid 'breaks' argument: must be numeric vector or list (see help for format)")
}
# Subset data
remove_cols <- colnames(x)[! colnames(x) %in% select]
if (length(remove_cols) > 0) {
set(x, j = remove_cols, value = NULL)
}
# Save 'x' data.frame to 'raw'
raw <- as.data.frame(x)
# Discretize continuous variables according to breaks
# browser()
for (j in select) {
v <- x[[j]]
# Discretize if continuous
if (j %in% continuous) {
b <- breaks[[j]]
if (any(is.null(b) | is.na(b))) {
b <- default_breaks
}
if (! is.numeric(v)) {
v <- as.numeric(v)
}
v <- cut(v, breaks = b, include.lowest = TRUE)
}
v <- as.factor(v)
# Check if discretizations worked
if (is.null(v)) {
stop(paste("Could not discretize", j))
}
data.table::set(x, j = j, value = v)
}
# Remove NAs
x <- stats::na.omit(x)
x <- as.data.frame(x)
# Check if rows are left
if (nrow(x) == 0) {
stop("Too much missing data. Preprocessed data.frame contains 0 rows.")
}
list(raw = raw,
pp = x,
select = select,
continuous = continuous,
breaks = breaks,
default_breaks = default_breaks)
}
| /scratch/gouwar.j/cran-all/cranData/zebu/R/preprocess.R |
#' zebu: Local Association Measures
#'
#' The zebu package implements the estimation of local (and global) association measures:
#' Ducher's Z, Lewontin's D, pointwise mutual information, normalized pointwise mutual information and chi-squared residuals.
#' The significance of local (and global) association is accessed using p-values estimated by permutations.
#'
#' @section Functions:
#'
#' \code{\link[zebu]{lassie}} estimates local (and global) association measures: Ducher's Z, Lewontin's D, pointwise mutual information, normalized pointwise mutual information and chi-squared residuals.
#'
#' \code{\link[zebu]{permtest}} accesses the significance of local (and global) association values usingp-values estimated by permutations.
#'
#' \code{\link[zebu]{chisqtest}} accesses the significance for two dimensional chi-squared analysis.
#'
#' @name zebu
#'
"_PACKAGE"
| /scratch/gouwar.j/cran-all/cranData/zebu/R/zebu.R |
## ----opts = TRUE, setup = TRUE, include = FALSE-------------------------------
knitr::opts_chunk$set(echo = TRUE, comment = "")
## ----eval=FALSE---------------------------------------------------------------
# install.packages("zebu")
## -----------------------------------------------------------------------------
library(zebu)
## -----------------------------------------------------------------------------
starter_prob <- c("Tomato Mozzarella Salad" = 1/3, "Rice Tuna Salad" = 1/3, "Lentil Salad" = 1/3)
starter_prob
## -----------------------------------------------------------------------------
main_given_starter_prob <- matrix(c(5/11, 1/11, 5/11,
5/11, 5/11, 1/10,
1/11, 5/11, 5/11),
3, 3, byrow = TRUE)
rownames(main_given_starter_prob) <- names(starter_prob)
colnames(main_given_starter_prob) <- c("Sausage and Lentil Stew", "Pizza Margherita", "Pilaf Rice")
main_given_starter_prob
## -----------------------------------------------------------------------------
dessert_given_main <- matrix(c(2/6, 2/6, 2/6,
7/12, 1/12, 2/6,
1/12, 7/12, 2/6),
3, 3, byrow = TRUE)
rownames(dessert_given_main) <- colnames(main_given_starter_prob)
colnames(dessert_given_main) <- c("Rice Pudding", "Apple Pie", "Fruit Salad")
dessert_given_main
## -----------------------------------------------------------------------------
set.seed(0)
sample_size <- 1000
df <- t(sapply(seq_len(sample_size), function(i) {
starter <- sample(names(starter_prob), size = 1, prob = starter_prob)
main <- sample(colnames(main_given_starter_prob), size = 1, prob = main_given_starter_prob[starter, ])
dessert <- sample(colnames(dessert_given_main), size = 1, prob = dessert_given_main[main, ])
c(Starter = starter, Main = main, Dessert = dessert)
}))
df <- as.data.frame(df)
## -----------------------------------------------------------------------------
head(df)
## -----------------------------------------------------------------------------
table(df)
## -----------------------------------------------------------------------------
las <- lassie(df, select = c("Main", "Dessert"), measure = "z")
## -----------------------------------------------------------------------------
las <- permtest(las,
nb = 5000,
p_adjust = "BH")
## ----plot-local-association---------------------------------------------------
print(las)
plot(las)
## -----------------------------------------------------------------------------
las2 <- lassie(df, measure = "z")
las2 <- permtest(las2, nb = 5000)
print(las2, what_sort = "local_p", decreasing = FALSE)
| /scratch/gouwar.j/cran-all/cranData/zebu/inst/doc/zebu.R |
---
title: "zebu: Local Association Measures"
author:
- "Olivier M. F. Martin"
- "Michel Ducher"
date: "`r Sys.Date()`"
output: rmarkdown::html_document
bibliography: bibliography.bib
abstract: |-
Association measures can be local or global. Local association measures quantify the association between specific values of random variables (*e.g.* chi-squared residuals). Global association measures yield a single value used to summarize the association for all values taken by random variables (*e.g.* chi-squared). Classical data analysis has focused on global association and overlooked local association. Consequently, software presently available only allows computation of global association measures. Nonetheless, a significant global association can hide a non-significant local association, and a non-significant global association can hide a significant local association. \
The `zebu` R package allows estimation of local association measures and implements local association subgroup analysis. It is of interest to a wide range of scientific disciplines such as health and computer sciences and can be used by anyone with a basic knowledge of the R language. It is available in the CRAN and its source code is available at https://github.com/oliviermfmartin/zebu. \
Keywords: measure of association, statistical independence, local association, pointwise mutual information, Lewontin's D, Ducher’s Z, chi-squared residuals.
vignette: >
%\VignetteIndexEntry{"zebu: Local Association Measures"}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r opts = TRUE, setup = TRUE, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = "")
```
## Summary
1. [Introduction](#section-introdution)
2. [Background on Association and Independence](#section-background)
3. [Local Association Measures](#section-lam)
- [Derivation of Bivariate Forms](#section-lam1)
- [Global Association](#section-lam2)
- [Statistical Significance Tests](#section-lam3)
- [Derivation of Multivariate Forms](#section-lam3)
4. [User's Guide - An Example with Simulated Data](#section-ug)
- [Simulating the Dataset](#section-ug1)
- [Bivariate Association](#section-ug2)
- [Multivariate Association](#section-ug3)
5. [Future Research and Development](#section-future)
6. [References](#section-references)
<div id='section-introdution'>
## Introduction
Association measures can be local or global [@van_de_cruys_two_2011]. Local association measures quantify the association between specific values of random variables. In the case of a contingency table, they yield one value for each cell. An example is chi-squared residuals that are computed when constructing a chi-squared test. On the other hand, global association measures yield a single value used to summarize the association for all values taken by random variables. An example is the chi-squared statistic, the sum of squared residuals [@sheskin_handbook_2007].
Most often, we are only concerned with the global association and overlook local association. For example, analysis of chi-squared residuals is uncommon practice when compared to the chi-square independence test. Nonetheless, a significant global association can hide a non-significant local association, and a non-significant global association can hide a significant local association [@anselin_lisa_1995]. Accordingly, analysis of association should not limit itself to the global perspective. Indeed, the association between two variables can depend on their values. For example, in threshold mechanisms, variables are only associated with each other when one takes values above a certain critical level. In this case, local association measures allow pinpointing values for which variables are associated. Moreover, the existence of an association between two variables may depend on the value of a third variable. For example, the effect of a drug will depend on the patient's sensibility to the drug. The local association between drug intake and recovery will not be the same for patients that are sensitive than for those that are resistant to the drug.
The rest of the vignette is organized as follows. We first give the reader the necessary intuition and mathematical background about global and local associations. This leads to the description of chi-square residuals, Lewontin's $D$ [@Lewontin1964], Ducher's $Z$ [@ducher_statistical_1994], and pointwise mutual information [@van_de_cruys_two_2011]. We also introduce a multivariate and normalized measure of local association. Subsequently, we illustrate the usage of local association measures using the `zebu` R package. The vignette ends with a discussion about future development and research.
<div id='section-background'>
## Background on Association and Independence
Throughout the vignette, we will suppose that all random variables are discrete and write them in capital letters, such as $A$ and $B$. Lower letters, such as $a$ and $b$, will denote possible values taken by these random variables (*i.e.* events).
One way to think about a statistical association is as events co-occurring. For example, if event $a$ always occurs with event $b$, then these events are said to be associated. An intuitive measure of association could be the joint probability: $p(a, b)$, the long-term frequency of events showing up together. However, this measure fails if $a$ or $b$ is a rare event. Indeed, joint probabilities are always as small as its individual events are rare: $p(a, b) \leq \min p(a), p(b)$. As a consequence, it is necessary to compare *observed* probabilities $p(a, b)$ to *expected* probabilities in which the variables are considered independent. The expected probability, if events are independent, is the factor of marginalized probabilities of events: $p(a) \, p(b)$. Independence is then defined by the following mathematical relation, $p(a, b) = p(a) \, p(b)$, and local association measures are defined to be equal to zero.
Independence implies that knowing one or more variables does not give us any information about the others. This is what we are not interested in. It is, however, possible to define two cases where the former equality does not hold: co-occurrence and mutual exclusivity. Co-occurrence is defined as events showing up more often than expected: $p(a, b) > p(a) \, p(b)$ and local association measures are positive. Mutual exclusivity is defined as events showing up less often than expected: $p(a, b) < p(a) \, p(b)$ and local association measures are negative.
Statistical independence is, however, not the only manner to construct an association measure. Other possibilities are based on the proportion of explained variance such as Pearson's r. These former measures are parametric and suppose linear or at least monotone relationships between variables. Although intuitive and convenient, this assumption is not always justified. Measures based on statistical independence provide a non-parametric alternative that can detect non-linear relationships.
<div id='section-lam'>
## Local Association Measures
<div id='section-lam1'>
#### Derivation of Bivariate Forms
For two random variables, $A$ and $B$, we can estimate the local association for each combination of events $A = a$ and $B = b$. This is accomplished by comparing the observed from the expected probability of events $a$ and $b$. If these probabilities are equal, then events $a$ and $b$ are independent. If not, these events are associated; the sign of the measure indicates the orientation of the relationship, and the absolute value indicates its strength.
There are different measures to compare observed and expected probabilities, for example, by using subtraction and division. Hereunder, we define the difference or Lewontin's $D$ [@Lewontin1964] and the pointwise mutual information $pmi$ [@van_de_cruys_two_2011]. To simplify notation, and to show similarities between local association measures, we define $h(a) = - \log p(a)$ as the self-information of $a$.
\[
\begin{aligned}
D(a, b) & = p(a, b) - p(a) \, p(b) \\
pmi(a, b) & = \log \frac{p(a, b)} {p(a) p(b)} = - (h(a, b) - h(a) - h(b))
\end{aligned}
\]
The bounds of these two measures depend on the frequency of events, which makes it difficult to compare local association values for different combinations of events. For this reason, it is desirable to express association relative to the frequency of events. One common way to do this is using chi-squared residuals $r_{\chi}$ as follows where $N$ is the sample size.
\[
r_{\chi}(a,b) = \sqrt{N} \; \frac{p(a, b) - p(a) \, p(b)}{\sqrt{p(a) \, p(b)}}
\]
We may wish to normalize local association so that values are between -1 and 1 included. This can be done by using dividing the non-normalized values by their minimal or maximal values. To identify the theoretical minimal and maximal values of $D$, we will find the bounds of the observed bivariate probability $p(a, b)$ as a function of the marginal probabilities $p(a)$ and $p(b)$.
Using the inclusion-exclusion principle, we know that:
\[
p(a, b) = p(a \cap b) = p(a) + p(b) - p(a \cup b)
\]
The intersection probability $p(a, b)$ will be maximized when the union probability $p(a \cup b)$ is equal to zero and minimized when the union probability will be equal to one.
\[
p(a) + p(b) - 1 \le p(a, b) \le p(a) + p(b)
\]
Given the intersection probability can not be smaller than zero and can not be larger than the smallest marginal probability, we have:
\[
\max[0, \, p(a) + p(b) - 1] \le p(a, b) \le min[p(a), \, p(b)]
\]
Using this result, we can divide $D$ by its theoretical minimal or maximal value which leads to Lewontin's $D'$ [@Lewontin1964]. However, this removes the sign of the association. To preserve the sign, in the case where Lewontin's $D$ is negative, we divide it by the negative theoretical minimal value. We call this measure Ducher's $Z$. It should however be noted that the original definition of Ducher's $Z$ did not probably consider the lower bound of the intersection probability as we do here [@ducher_statistical_1994].
\[
Z(a, b) =
\begin{cases}
\frac{ p(a, b) - p(a) \, p(b) }{ \min[p(a), \, p(b)] - p(a) \, p(b) }
& D(a, b) > 0 \\
\\
\frac{ p(a, b) - p(a) \, p(b) }{p(a) p(b) - \max[0, \, p(a) + p(b) - 1]}
& D(a, b) < 0 \\
\\
0
& D(a, b) = 0
\end{cases}
\]
Normalization of case of $pmi$ is more subtle because $pmi(a, b)$ tends to $\infty$ when $p(a, b)$ tends to 0. Nonetheless, dividing $pmi(a, b)$ by $- h(a, b)$ solves this problem by making $npmi(a, b)$ tend to -1 when $p(a, b)$ tends to 0 and equal to 1 when $p(a, b) = \min[p(a), p(b)]$ [@bouma_normalized_2009].
\[
npmi(a, b) = \frac{ pmi(a, b) }{- h(a, b) }
= \frac{ h(a, b) - h(a) - h(b) }{ h(a, b) }
\]
The `zebu` package includes a function called `lassie` allowing estimation of Lewontin's $D$, Ducher's $Z$, $pmi$, $npmi$, and $r_{\chi}$.
<div id='section-lam2'>
#### Global Association
Global association measures yield a single value used to summarize the association for all values taken by the random variables. For example, mutual information is computed as the sum for all events of their observed probability times their pointwise mutual information. Most global association measures in `zebu` are defined likewise.
\[
\begin{aligned}
GD(A, B) &= \sum_{a, b} p(a, b) D(a, b) \\
GZ(A, B) &= \sum_{a, b} p(a, b) Z(a, b) \\
MI(A, B) &= \sum_{a, b} p(a, b) pmi(a, b) \\
NMI(A, B) &= \sum_{a, b} p(a, b) npmi(a, b) \\
\end{aligned}
\]
The global association measure related to chi-squared residuals is the chi-squared $\chi^2$. It is defined as the sum of its squared residuals.
\[
\chi^2 = \sum_{a, b} r_{\chi}(a,b)^2
\]
<div id='section-lam3'>
#### Statistical Significance Tests
Distinguishing the strength of association from its statistical significance is important. Indeed, a strong association can be non-significant (*e.g.* some physical law with small sample size) and a weak association can be significant (*e.g.* epidemiological risk factor with big sample size). Significance can be accessed using p-values estimated using the theoretical null distribution or by resampling techniques [@sheskin_handbook_2007]. Because the theoretical null distribution of local association measures is unknown, the `zebu` package resorts to estimating p-values by a permutation test. This can be undertaken using the `permtest` function of the package.
The null hypothesis $H_0$ being tested is that the association measure $L$ is equal to 0, that is, there is no association. The observed association is $L_{obs}$ and the permuted associations are denoted by the set $L_{perm}$. Moreover, we write $\#(\ldots)$ as the number of times and $|\ldots|$ as the absolute value. The two-sided p-value can then be estimated as follows.
\[
p = \frac{\#(|L_{obs}| < |L_{perm}|)}{\#(L_{perm})}
\]
With chi-squared residuals in a two-dimensional setting, an alternative analytical method for estimating the p-values can be employed as implemented by the `chisqtest` function. This function calculates two-sided p-values for each local chi-squared residual, assuming that these residuals are distributed according to a standard normal distribution. Thus, the two-sided p-value $p$ can be computed as follows where $\Phi(\ldots)$ is the cumulative distribution function of the standard normal distribution, and $L_{obs}$ denotes the observed chi-squared residuals:
\[
p = 2 \times (1 - \Phi(|L_{obs}|))
\]
As these local association measures involve conducting multiple statistical tests, it is advisable to apply corrections for multiple testing, such as the method proposed by Benjamini and Hochberg.
<div id='section-lam4'>
#### Derivation of Multivariate Forms
Multivariate association measures may help identify complex association relationships that cannot be detected only with bivariate association measures. For example, in the XOR gate, the output of the gate is not associated with any of the two inputs individually [@jakulin_analyzing_2003]. The association is only revealed when the two inputs and the output are taken together.
To derive multivariate forms of these local association measures, we assume that events are mutually independent. This means that for $M$ random variables $X_1, \ldots, X_M$, independence is defined by: $p(x_1, \ldots, x_M) = \prod_{i=1}^{M} p(x_i)$. We can thus define the following measures.
\[
\begin{aligned}
D(x_1, \ldots, x_M) & = p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) \\
pmi(x_1, \ldots, x_M) & = - [h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) ]
\end{aligned}
\]
By dividing $D(x_1, \ldots, x_M)$ by the expected probability we obtain multivariate chi-squared residuals
\[
r_{\chi}(x_1, \ldots, x_M) = \sqrt{N} \; \frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{ \sqrt{\prod_{i=1}^{M} p(x_i)} }
\]
To obtain a multivariate measure of Ducher's $Z$, we need to find the bounds of the observed probability $p(x_1, \ldots, x_M)$. We know that the upper bound will be the minimal marginal probability. Additionally, we find a formula to express the lower bound (proof at the end of the section). This leads to the following bounds.
\[
\max[0, -M - 1 + \sum_{i=1}^M p(x_i)] \le p(x_1, \ldots, x_M) \le \min[x_1, \ldots, x_M]$.
\]
We thus propose the following multivariate form of Ducher's $Z$.
\[
Z(x_1, \ldots, x_M) =
\begin{cases}
\frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{ \min[p(x_1), \ldots, p(x_M)] - \prod_{i=1}^{M} p(x_i) }
& D(x_1, \ldots, x_M) > 0 \\
\\
\frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{\prod_{i=1}^{M} p(x_i)- \max[0, - M - 1 + \sum_{i=1}^M p(x_i)]}
& D(x_1, \ldots, x_M) < 0 \\
\\
0
& D(x_1, \ldots, x_M) = 0
\end{cases}
\]
For pointwise mutual information, the normalization technique suggested by @bouma_normalized_2009 is not bounded by 1 for more than two variables. To solve this, we suggest the following normalization scheme which we call $npmi_2$.
\[
npmi_2(x_1, \ldots, x_M) =
\begin{cases}
\frac{ h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) }{ \min[h(x_1), \ldots, h(x_M)] - \sum_{i=1}^{M} h(x_i) }
& pmi(x_1, \ldots, x_M) > 0 \\
\\
\frac{ h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) }{h(x_1, \ldots, x_M)}
& pmi(x_1, \ldots, x_M) < 0 \\
\\
0
& pmi(x_1, \ldots, x_M) = 0
\end{cases}
\]
#### Proof of lower bound formula
Using induction and the inclusion-exclusion principle we give a formula for the lower bound of the observed intersection probability of $M$ events.
\[
\min[ p(x_1, \ldots, x_M) ] = \max[0, -M - 1 + \sum_{i=1}^M p(x_i)]
\]
We first show that this is true for the base case $M=2$. In this case, $p(x_1) + p(x_2) -1 \le p(x_1, x_2)$. We proved this using the inclusion-exclusion principle in the section where we [derive a bivariate form of Ducher's Z](#section-lam1).
We now show that the induction step is true: let's assume that this formula is true for $M$ variables. For $M+1$ variables, the inclusion-exclusion principle tells us that:
\[
\begin{align}
p(x_1, \ldots, x_{M+1})
&= p(\{\cap_{i=1}^M x_i \} \cap x_{M+1}) \\
&= p(\cap_{i=1}^M x_i) + p(x_{M+1}) - p(\{\cap_{i=1}^M x_M \} \cup x_{M+1}) \\
\end{align}
\]
We assumed that the lower bound $p(\cap_{i=1}^M x_i)$ is $-M - 1 + \sum_{i=1}^M p(x_i)$ and we know that the upper bound of $p(\{\cap_{i=1}^M x_M \} \cup x_{M+1})$ is one. Replacing these values in the last line leads to
\[
\min[ p(x_1, \ldots, x_{M+1}) ] = -(M+1) - 1 + \sum_{i=1}^{M+1} p(x_i)
\]
However, given that probabilities can not be lower than zero, we can write the following equation which completes the proof.
\[
\min[ p(x_1, \ldots, x_{M+1}) ] = \max[0, -(M+1) - 1 + \sum_{i=1}^{M+1} p(x_i)]
\]
<div id='section-ug'>
## User's Guide - An Example with Simulated Data
Once R is installed, the first step is to install the `zebu` package. You can install the released version from CRAN
```{R eval=FALSE}
install.packages("zebu")
```
We can then load the `zebu` R package.
```{r}
library(zebu)
```
<div id='section-ug1'>
### Simulating the Dataset
To illustrate local association measures and the `zebu` package, we'll simulate a small culinary dataset.
Each row corresponds to a client of a restaurant. We record the choices made by the client. There are three choices for each of the plates: starters, main dish, and dessert.
The clients take the starter with equal probability. The choice of the following dish depends only on the previous dish. The clients tend to avoid a dish with an ingredient that had in the previous dish. We define these probabilities hereunder.
```{r}
starter_prob <- c("Tomato Mozzarella Salad" = 1/3, "Rice Tuna Salad" = 1/3, "Lentil Salad" = 1/3)
starter_prob
```
```{r}
main_given_starter_prob <- matrix(c(5/11, 1/11, 5/11,
5/11, 5/11, 1/10,
1/11, 5/11, 5/11),
3, 3, byrow = TRUE)
rownames(main_given_starter_prob) <- names(starter_prob)
colnames(main_given_starter_prob) <- c("Sausage and Lentil Stew", "Pizza Margherita", "Pilaf Rice")
main_given_starter_prob
```
```{r}
dessert_given_main <- matrix(c(2/6, 2/6, 2/6,
7/12, 1/12, 2/6,
1/12, 7/12, 2/6),
3, 3, byrow = TRUE)
rownames(dessert_given_main) <- colnames(main_given_starter_prob)
colnames(dessert_given_main) <- c("Rice Pudding", "Apple Pie", "Fruit Salad")
dessert_given_main
```
We now simulate a dataset of 1000 clients given these probabilities.
```{r}
set.seed(0)
sample_size <- 1000
df <- t(sapply(seq_len(sample_size), function(i) {
starter <- sample(names(starter_prob), size = 1, prob = starter_prob)
main <- sample(colnames(main_given_starter_prob), size = 1, prob = main_given_starter_prob[starter, ])
dessert <- sample(colnames(dessert_given_main), size = 1, prob = dessert_given_main[main, ])
c(Starter = starter, Main = main, Dessert = dessert)
}))
df <- as.data.frame(df)
```
```{r}
head(df)
```
We look at the contingency table.
```{r}
table(df)
```
<div id='section-ug2'>
### Bivariate Association
The local (and global) association between these variables can be estimated using the `lassie` function. This function takes at least one argument: a `data.frame`. Columns are selected using the `select` arguments (column names or numbers). Variables are assumed to be categorical; continuous variables have to be specified using the `continuous` argument and the number of discretization bins with the `breaks` argument (as in the `cut` function). The local association measure that we use here is Ducher's Z as specified by setting the `measure` argument equal to `"z"`. We'll look at the relationship between the main dish and the dessert.
```{r}
las <- lassie(df, select = c("Main", "Dessert"), measure = "z")
```
The `permtest` function accesses the significance of local (and global) association using a permutation test. The number of iterations is specified by `nb` and the adjustment method of p-values for multiple comparisons by `p_adjust` (as in the `p.adjust` function).
```{r}
las <- permtest(las,
nb = 5000,
p_adjust = "BH")
```
The `lassie` and `permtest` functions return a `lassie` S3 object, as well as `permtest` for `permtest`. `lassie` objects can be visualized using the `plot` and `print` methods. The `plot` function returns a heatmap with the local association and p-values displayed between parenthesis.
```{r plot-local-association}
print(las)
plot(las)
```
Alternatively, for two dimensional chi-squared analysis, significance can be estimated using the `chisqtest` function.
Results can be saved in CSV format using `write.lassie`. To access the documentation of these functions, please type `help("print.lassie")`, `help("plot.lassie")` and `help(write.lassie)` in the R console.
In this example, we can see that the global association between the two variables is statistically significant. However, we see that there is only a local association between these two variables only for certain combinations. More specifically, knowing that a client took the lentils and sausages does not convey information about what dessert s/he will take, and likewise for the fruit salad. *A significant global association can hide a non-significant local association.*
<div id='section-ug3'>
### Multivariate Association
The number of variables that can be handled in the `zebu` package is not limited. We can use the `lassie` function to access the association between the three simulated variables.
In this case, we obtain a multidimensional local association `array`. Because of this, results cannot be plotted as a tile plot; the `plot` method is not available. The `print` method allows visualizing results by melting the `array` into a `data.frame`, by default sorted by decreasing local association.
```{r}
las2 <- lassie(df, measure = "z")
las2 <- permtest(las2, nb = 5000)
print(las2, what_sort = "local_p", decreasing = FALSE)
```
In this case, we see that there is no significant global association. However, we see that for certain combinations of variables, there is a significant local association. *A non-significant global association can hide a significant local association.*
<div id='section-future'>
## Future Research and Development
Local association measures are issued from empirical research. Although these have proven their interest in diverse applications, theoretical studies of their mathematical properties are sparse. A more theoretical approach to these measures could be of interest. For example, by determining the theoretical null distribution of these measures. Also, we have assumed mutual exclusivity of events for the multivariate association measures. This assumption may be too stringent for certain variables and usage of other independence models such as conditional independence may prove to be worthwhile.
In `zebu`, discretization is a necessary step for studying continuous variables. We have restrained ourselves to simple discretization methods: equal-width and user-defined. Other discretization algorithms exist [@dash_comparative_2011] and may be more adapted for the computation of association measures. Moreover, kernel methods could also be used to handle continuous variables better. Secondly, estimation of probabilities is done from the frequentist maximum-likelihood procedure which requires sufficiently large datasets. Unfortunately, in fields such as health sciences, datasets are sparse. Bayesian estimation methods are more robust to small sample sizes by not relying on asymptomatic assumptions and by allowing integration of prior knowledge [@wilkinson_bayesian_2007]. Such an implementation may also prove to be of interest.
<div id='section-references'>
## References
| /scratch/gouwar.j/cran-all/cranData/zebu/inst/doc/zebu.Rmd |
# This is what happens behind the curtains in the 'lassie' function
# Here we compute the association between the 'Girth' and 'Height' variables
# of the 'trees' dataset
# 'select' and 'continuous' take column numbers or names
select <- c('Girth', 'Height') # select subset of trees
continuous <-c(1, 2) # both 'Girth' and 'Height' are continuous
# equal-width discretization with 3 bins
breaks <- 3
# Preprocess data: subset, discretize and remove missing data
pre <- preprocess(trees, select, continuous, breaks)
# Estimates marginal and multivariate probabilities from preprocessed data.frame
prob <- estimate_prob(pre$pp)
# Computes local and global association using Ducher's Z
lam <- local_association(prob, measure = 'z')
| /scratch/gouwar.j/cran-all/cranData/zebu/inst/examples/lassie.R |
---
title: "zebu: Local Association Measures"
author:
- "Olivier M. F. Martin"
- "Michel Ducher"
date: "`r Sys.Date()`"
output: rmarkdown::html_document
bibliography: bibliography.bib
abstract: |-
Association measures can be local or global. Local association measures quantify the association between specific values of random variables (*e.g.* chi-squared residuals). Global association measures yield a single value used to summarize the association for all values taken by random variables (*e.g.* chi-squared). Classical data analysis has focused on global association and overlooked local association. Consequently, software presently available only allows computation of global association measures. Nonetheless, a significant global association can hide a non-significant local association, and a non-significant global association can hide a significant local association. \
The `zebu` R package allows estimation of local association measures and implements local association subgroup analysis. It is of interest to a wide range of scientific disciplines such as health and computer sciences and can be used by anyone with a basic knowledge of the R language. It is available in the CRAN and its source code is available at https://github.com/oliviermfmartin/zebu. \
Keywords: measure of association, statistical independence, local association, pointwise mutual information, Lewontin's D, Ducher’s Z, chi-squared residuals.
vignette: >
%\VignetteIndexEntry{"zebu: Local Association Measures"}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r opts = TRUE, setup = TRUE, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = "")
```
## Summary
1. [Introduction](#section-introdution)
2. [Background on Association and Independence](#section-background)
3. [Local Association Measures](#section-lam)
- [Derivation of Bivariate Forms](#section-lam1)
- [Global Association](#section-lam2)
- [Statistical Significance Tests](#section-lam3)
- [Derivation of Multivariate Forms](#section-lam3)
4. [User's Guide - An Example with Simulated Data](#section-ug)
- [Simulating the Dataset](#section-ug1)
- [Bivariate Association](#section-ug2)
- [Multivariate Association](#section-ug3)
5. [Future Research and Development](#section-future)
6. [References](#section-references)
<div id='section-introdution'>
## Introduction
Association measures can be local or global [@van_de_cruys_two_2011]. Local association measures quantify the association between specific values of random variables. In the case of a contingency table, they yield one value for each cell. An example is chi-squared residuals that are computed when constructing a chi-squared test. On the other hand, global association measures yield a single value used to summarize the association for all values taken by random variables. An example is the chi-squared statistic, the sum of squared residuals [@sheskin_handbook_2007].
Most often, we are only concerned with the global association and overlook local association. For example, analysis of chi-squared residuals is uncommon practice when compared to the chi-square independence test. Nonetheless, a significant global association can hide a non-significant local association, and a non-significant global association can hide a significant local association [@anselin_lisa_1995]. Accordingly, analysis of association should not limit itself to the global perspective. Indeed, the association between two variables can depend on their values. For example, in threshold mechanisms, variables are only associated with each other when one takes values above a certain critical level. In this case, local association measures allow pinpointing values for which variables are associated. Moreover, the existence of an association between two variables may depend on the value of a third variable. For example, the effect of a drug will depend on the patient's sensibility to the drug. The local association between drug intake and recovery will not be the same for patients that are sensitive than for those that are resistant to the drug.
The rest of the vignette is organized as follows. We first give the reader the necessary intuition and mathematical background about global and local associations. This leads to the description of chi-square residuals, Lewontin's $D$ [@Lewontin1964], Ducher's $Z$ [@ducher_statistical_1994], and pointwise mutual information [@van_de_cruys_two_2011]. We also introduce a multivariate and normalized measure of local association. Subsequently, we illustrate the usage of local association measures using the `zebu` R package. The vignette ends with a discussion about future development and research.
<div id='section-background'>
## Background on Association and Independence
Throughout the vignette, we will suppose that all random variables are discrete and write them in capital letters, such as $A$ and $B$. Lower letters, such as $a$ and $b$, will denote possible values taken by these random variables (*i.e.* events).
One way to think about a statistical association is as events co-occurring. For example, if event $a$ always occurs with event $b$, then these events are said to be associated. An intuitive measure of association could be the joint probability: $p(a, b)$, the long-term frequency of events showing up together. However, this measure fails if $a$ or $b$ is a rare event. Indeed, joint probabilities are always as small as its individual events are rare: $p(a, b) \leq \min p(a), p(b)$. As a consequence, it is necessary to compare *observed* probabilities $p(a, b)$ to *expected* probabilities in which the variables are considered independent. The expected probability, if events are independent, is the factor of marginalized probabilities of events: $p(a) \, p(b)$. Independence is then defined by the following mathematical relation, $p(a, b) = p(a) \, p(b)$, and local association measures are defined to be equal to zero.
Independence implies that knowing one or more variables does not give us any information about the others. This is what we are not interested in. It is, however, possible to define two cases where the former equality does not hold: co-occurrence and mutual exclusivity. Co-occurrence is defined as events showing up more often than expected: $p(a, b) > p(a) \, p(b)$ and local association measures are positive. Mutual exclusivity is defined as events showing up less often than expected: $p(a, b) < p(a) \, p(b)$ and local association measures are negative.
Statistical independence is, however, not the only manner to construct an association measure. Other possibilities are based on the proportion of explained variance such as Pearson's r. These former measures are parametric and suppose linear or at least monotone relationships between variables. Although intuitive and convenient, this assumption is not always justified. Measures based on statistical independence provide a non-parametric alternative that can detect non-linear relationships.
<div id='section-lam'>
## Local Association Measures
<div id='section-lam1'>
#### Derivation of Bivariate Forms
For two random variables, $A$ and $B$, we can estimate the local association for each combination of events $A = a$ and $B = b$. This is accomplished by comparing the observed from the expected probability of events $a$ and $b$. If these probabilities are equal, then events $a$ and $b$ are independent. If not, these events are associated; the sign of the measure indicates the orientation of the relationship, and the absolute value indicates its strength.
There are different measures to compare observed and expected probabilities, for example, by using subtraction and division. Hereunder, we define the difference or Lewontin's $D$ [@Lewontin1964] and the pointwise mutual information $pmi$ [@van_de_cruys_two_2011]. To simplify notation, and to show similarities between local association measures, we define $h(a) = - \log p(a)$ as the self-information of $a$.
\[
\begin{aligned}
D(a, b) & = p(a, b) - p(a) \, p(b) \\
pmi(a, b) & = \log \frac{p(a, b)} {p(a) p(b)} = - (h(a, b) - h(a) - h(b))
\end{aligned}
\]
The bounds of these two measures depend on the frequency of events, which makes it difficult to compare local association values for different combinations of events. For this reason, it is desirable to express association relative to the frequency of events. One common way to do this is using chi-squared residuals $r_{\chi}$ as follows where $N$ is the sample size.
\[
r_{\chi}(a,b) = \sqrt{N} \; \frac{p(a, b) - p(a) \, p(b)}{\sqrt{p(a) \, p(b)}}
\]
We may wish to normalize local association so that values are between -1 and 1 included. This can be done by using dividing the non-normalized values by their minimal or maximal values. To identify the theoretical minimal and maximal values of $D$, we will find the bounds of the observed bivariate probability $p(a, b)$ as a function of the marginal probabilities $p(a)$ and $p(b)$.
Using the inclusion-exclusion principle, we know that:
\[
p(a, b) = p(a \cap b) = p(a) + p(b) - p(a \cup b)
\]
The intersection probability $p(a, b)$ will be maximized when the union probability $p(a \cup b)$ is equal to zero and minimized when the union probability will be equal to one.
\[
p(a) + p(b) - 1 \le p(a, b) \le p(a) + p(b)
\]
Given the intersection probability can not be smaller than zero and can not be larger than the smallest marginal probability, we have:
\[
\max[0, \, p(a) + p(b) - 1] \le p(a, b) \le min[p(a), \, p(b)]
\]
Using this result, we can divide $D$ by its theoretical minimal or maximal value which leads to Lewontin's $D'$ [@Lewontin1964]. However, this removes the sign of the association. To preserve the sign, in the case where Lewontin's $D$ is negative, we divide it by the negative theoretical minimal value. We call this measure Ducher's $Z$. It should however be noted that the original definition of Ducher's $Z$ did not probably consider the lower bound of the intersection probability as we do here [@ducher_statistical_1994].
\[
Z(a, b) =
\begin{cases}
\frac{ p(a, b) - p(a) \, p(b) }{ \min[p(a), \, p(b)] - p(a) \, p(b) }
& D(a, b) > 0 \\
\\
\frac{ p(a, b) - p(a) \, p(b) }{p(a) p(b) - \max[0, \, p(a) + p(b) - 1]}
& D(a, b) < 0 \\
\\
0
& D(a, b) = 0
\end{cases}
\]
Normalization of case of $pmi$ is more subtle because $pmi(a, b)$ tends to $\infty$ when $p(a, b)$ tends to 0. Nonetheless, dividing $pmi(a, b)$ by $- h(a, b)$ solves this problem by making $npmi(a, b)$ tend to -1 when $p(a, b)$ tends to 0 and equal to 1 when $p(a, b) = \min[p(a), p(b)]$ [@bouma_normalized_2009].
\[
npmi(a, b) = \frac{ pmi(a, b) }{- h(a, b) }
= \frac{ h(a, b) - h(a) - h(b) }{ h(a, b) }
\]
The `zebu` package includes a function called `lassie` allowing estimation of Lewontin's $D$, Ducher's $Z$, $pmi$, $npmi$, and $r_{\chi}$.
<div id='section-lam2'>
#### Global Association
Global association measures yield a single value used to summarize the association for all values taken by the random variables. For example, mutual information is computed as the sum for all events of their observed probability times their pointwise mutual information. Most global association measures in `zebu` are defined likewise.
\[
\begin{aligned}
GD(A, B) &= \sum_{a, b} p(a, b) D(a, b) \\
GZ(A, B) &= \sum_{a, b} p(a, b) Z(a, b) \\
MI(A, B) &= \sum_{a, b} p(a, b) pmi(a, b) \\
NMI(A, B) &= \sum_{a, b} p(a, b) npmi(a, b) \\
\end{aligned}
\]
The global association measure related to chi-squared residuals is the chi-squared $\chi^2$. It is defined as the sum of its squared residuals.
\[
\chi^2 = \sum_{a, b} r_{\chi}(a,b)^2
\]
<div id='section-lam3'>
#### Statistical Significance Tests
Distinguishing the strength of association from its statistical significance is important. Indeed, a strong association can be non-significant (*e.g.* some physical law with small sample size) and a weak association can be significant (*e.g.* epidemiological risk factor with big sample size). Significance can be accessed using p-values estimated using the theoretical null distribution or by resampling techniques [@sheskin_handbook_2007]. Because the theoretical null distribution of local association measures is unknown, the `zebu` package resorts to estimating p-values by a permutation test. This can be undertaken using the `permtest` function of the package.
The null hypothesis $H_0$ being tested is that the association measure $L$ is equal to 0, that is, there is no association. The observed association is $L_{obs}$ and the permuted associations are denoted by the set $L_{perm}$. Moreover, we write $\#(\ldots)$ as the number of times and $|\ldots|$ as the absolute value. The two-sided p-value can then be estimated as follows.
\[
p = \frac{\#(|L_{obs}| < |L_{perm}|)}{\#(L_{perm})}
\]
With chi-squared residuals in a two-dimensional setting, an alternative analytical method for estimating the p-values can be employed as implemented by the `chisqtest` function. This function calculates two-sided p-values for each local chi-squared residual, assuming that these residuals are distributed according to a standard normal distribution. Thus, the two-sided p-value $p$ can be computed as follows where $\Phi(\ldots)$ is the cumulative distribution function of the standard normal distribution, and $L_{obs}$ denotes the observed chi-squared residuals:
\[
p = 2 \times (1 - \Phi(|L_{obs}|))
\]
As these local association measures involve conducting multiple statistical tests, it is advisable to apply corrections for multiple testing, such as the method proposed by Benjamini and Hochberg.
<div id='section-lam4'>
#### Derivation of Multivariate Forms
Multivariate association measures may help identify complex association relationships that cannot be detected only with bivariate association measures. For example, in the XOR gate, the output of the gate is not associated with any of the two inputs individually [@jakulin_analyzing_2003]. The association is only revealed when the two inputs and the output are taken together.
To derive multivariate forms of these local association measures, we assume that events are mutually independent. This means that for $M$ random variables $X_1, \ldots, X_M$, independence is defined by: $p(x_1, \ldots, x_M) = \prod_{i=1}^{M} p(x_i)$. We can thus define the following measures.
\[
\begin{aligned}
D(x_1, \ldots, x_M) & = p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) \\
pmi(x_1, \ldots, x_M) & = - [h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) ]
\end{aligned}
\]
By dividing $D(x_1, \ldots, x_M)$ by the expected probability we obtain multivariate chi-squared residuals
\[
r_{\chi}(x_1, \ldots, x_M) = \sqrt{N} \; \frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{ \sqrt{\prod_{i=1}^{M} p(x_i)} }
\]
To obtain a multivariate measure of Ducher's $Z$, we need to find the bounds of the observed probability $p(x_1, \ldots, x_M)$. We know that the upper bound will be the minimal marginal probability. Additionally, we find a formula to express the lower bound (proof at the end of the section). This leads to the following bounds.
\[
\max[0, -M - 1 + \sum_{i=1}^M p(x_i)] \le p(x_1, \ldots, x_M) \le \min[x_1, \ldots, x_M]$.
\]
We thus propose the following multivariate form of Ducher's $Z$.
\[
Z(x_1, \ldots, x_M) =
\begin{cases}
\frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{ \min[p(x_1), \ldots, p(x_M)] - \prod_{i=1}^{M} p(x_i) }
& D(x_1, \ldots, x_M) > 0 \\
\\
\frac{ p(x_1, \ldots, x_M) - \prod_{i=1}^{M} p(x_i) }{\prod_{i=1}^{M} p(x_i)- \max[0, - M - 1 + \sum_{i=1}^M p(x_i)]}
& D(x_1, \ldots, x_M) < 0 \\
\\
0
& D(x_1, \ldots, x_M) = 0
\end{cases}
\]
For pointwise mutual information, the normalization technique suggested by @bouma_normalized_2009 is not bounded by 1 for more than two variables. To solve this, we suggest the following normalization scheme which we call $npmi_2$.
\[
npmi_2(x_1, \ldots, x_M) =
\begin{cases}
\frac{ h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) }{ \min[h(x_1), \ldots, h(x_M)] - \sum_{i=1}^{M} h(x_i) }
& pmi(x_1, \ldots, x_M) > 0 \\
\\
\frac{ h(x_1, \ldots, x_M) - \sum_{i=1}^{M} h(x_i) }{h(x_1, \ldots, x_M)}
& pmi(x_1, \ldots, x_M) < 0 \\
\\
0
& pmi(x_1, \ldots, x_M) = 0
\end{cases}
\]
#### Proof of lower bound formula
Using induction and the inclusion-exclusion principle we give a formula for the lower bound of the observed intersection probability of $M$ events.
\[
\min[ p(x_1, \ldots, x_M) ] = \max[0, -M - 1 + \sum_{i=1}^M p(x_i)]
\]
We first show that this is true for the base case $M=2$. In this case, $p(x_1) + p(x_2) -1 \le p(x_1, x_2)$. We proved this using the inclusion-exclusion principle in the section where we [derive a bivariate form of Ducher's Z](#section-lam1).
We now show that the induction step is true: let's assume that this formula is true for $M$ variables. For $M+1$ variables, the inclusion-exclusion principle tells us that:
\[
\begin{align}
p(x_1, \ldots, x_{M+1})
&= p(\{\cap_{i=1}^M x_i \} \cap x_{M+1}) \\
&= p(\cap_{i=1}^M x_i) + p(x_{M+1}) - p(\{\cap_{i=1}^M x_M \} \cup x_{M+1}) \\
\end{align}
\]
We assumed that the lower bound $p(\cap_{i=1}^M x_i)$ is $-M - 1 + \sum_{i=1}^M p(x_i)$ and we know that the upper bound of $p(\{\cap_{i=1}^M x_M \} \cup x_{M+1})$ is one. Replacing these values in the last line leads to
\[
\min[ p(x_1, \ldots, x_{M+1}) ] = -(M+1) - 1 + \sum_{i=1}^{M+1} p(x_i)
\]
However, given that probabilities can not be lower than zero, we can write the following equation which completes the proof.
\[
\min[ p(x_1, \ldots, x_{M+1}) ] = \max[0, -(M+1) - 1 + \sum_{i=1}^{M+1} p(x_i)]
\]
<div id='section-ug'>
## User's Guide - An Example with Simulated Data
Once R is installed, the first step is to install the `zebu` package. You can install the released version from CRAN
```{R eval=FALSE}
install.packages("zebu")
```
We can then load the `zebu` R package.
```{r}
library(zebu)
```
<div id='section-ug1'>
### Simulating the Dataset
To illustrate local association measures and the `zebu` package, we'll simulate a small culinary dataset.
Each row corresponds to a client of a restaurant. We record the choices made by the client. There are three choices for each of the plates: starters, main dish, and dessert.
The clients take the starter with equal probability. The choice of the following dish depends only on the previous dish. The clients tend to avoid a dish with an ingredient that had in the previous dish. We define these probabilities hereunder.
```{r}
starter_prob <- c("Tomato Mozzarella Salad" = 1/3, "Rice Tuna Salad" = 1/3, "Lentil Salad" = 1/3)
starter_prob
```
```{r}
main_given_starter_prob <- matrix(c(5/11, 1/11, 5/11,
5/11, 5/11, 1/10,
1/11, 5/11, 5/11),
3, 3, byrow = TRUE)
rownames(main_given_starter_prob) <- names(starter_prob)
colnames(main_given_starter_prob) <- c("Sausage and Lentil Stew", "Pizza Margherita", "Pilaf Rice")
main_given_starter_prob
```
```{r}
dessert_given_main <- matrix(c(2/6, 2/6, 2/6,
7/12, 1/12, 2/6,
1/12, 7/12, 2/6),
3, 3, byrow = TRUE)
rownames(dessert_given_main) <- colnames(main_given_starter_prob)
colnames(dessert_given_main) <- c("Rice Pudding", "Apple Pie", "Fruit Salad")
dessert_given_main
```
We now simulate a dataset of 1000 clients given these probabilities.
```{r}
set.seed(0)
sample_size <- 1000
df <- t(sapply(seq_len(sample_size), function(i) {
starter <- sample(names(starter_prob), size = 1, prob = starter_prob)
main <- sample(colnames(main_given_starter_prob), size = 1, prob = main_given_starter_prob[starter, ])
dessert <- sample(colnames(dessert_given_main), size = 1, prob = dessert_given_main[main, ])
c(Starter = starter, Main = main, Dessert = dessert)
}))
df <- as.data.frame(df)
```
```{r}
head(df)
```
We look at the contingency table.
```{r}
table(df)
```
<div id='section-ug2'>
### Bivariate Association
The local (and global) association between these variables can be estimated using the `lassie` function. This function takes at least one argument: a `data.frame`. Columns are selected using the `select` arguments (column names or numbers). Variables are assumed to be categorical; continuous variables have to be specified using the `continuous` argument and the number of discretization bins with the `breaks` argument (as in the `cut` function). The local association measure that we use here is Ducher's Z as specified by setting the `measure` argument equal to `"z"`. We'll look at the relationship between the main dish and the dessert.
```{r}
las <- lassie(df, select = c("Main", "Dessert"), measure = "z")
```
The `permtest` function accesses the significance of local (and global) association using a permutation test. The number of iterations is specified by `nb` and the adjustment method of p-values for multiple comparisons by `p_adjust` (as in the `p.adjust` function).
```{r}
las <- permtest(las,
nb = 5000,
p_adjust = "BH")
```
The `lassie` and `permtest` functions return a `lassie` S3 object, as well as `permtest` for `permtest`. `lassie` objects can be visualized using the `plot` and `print` methods. The `plot` function returns a heatmap with the local association and p-values displayed between parenthesis.
```{r plot-local-association}
print(las)
plot(las)
```
Alternatively, for two dimensional chi-squared analysis, significance can be estimated using the `chisqtest` function.
Results can be saved in CSV format using `write.lassie`. To access the documentation of these functions, please type `help("print.lassie")`, `help("plot.lassie")` and `help(write.lassie)` in the R console.
In this example, we can see that the global association between the two variables is statistically significant. However, we see that there is only a local association between these two variables only for certain combinations. More specifically, knowing that a client took the lentils and sausages does not convey information about what dessert s/he will take, and likewise for the fruit salad. *A significant global association can hide a non-significant local association.*
<div id='section-ug3'>
### Multivariate Association
The number of variables that can be handled in the `zebu` package is not limited. We can use the `lassie` function to access the association between the three simulated variables.
In this case, we obtain a multidimensional local association `array`. Because of this, results cannot be plotted as a tile plot; the `plot` method is not available. The `print` method allows visualizing results by melting the `array` into a `data.frame`, by default sorted by decreasing local association.
```{r}
las2 <- lassie(df, measure = "z")
las2 <- permtest(las2, nb = 5000)
print(las2, what_sort = "local_p", decreasing = FALSE)
```
In this case, we see that there is no significant global association. However, we see that for certain combinations of variables, there is a significant local association. *A non-significant global association can hide a significant local association.*
<div id='section-future'>
## Future Research and Development
Local association measures are issued from empirical research. Although these have proven their interest in diverse applications, theoretical studies of their mathematical properties are sparse. A more theoretical approach to these measures could be of interest. For example, by determining the theoretical null distribution of these measures. Also, we have assumed mutual exclusivity of events for the multivariate association measures. This assumption may be too stringent for certain variables and usage of other independence models such as conditional independence may prove to be worthwhile.
In `zebu`, discretization is a necessary step for studying continuous variables. We have restrained ourselves to simple discretization methods: equal-width and user-defined. Other discretization algorithms exist [@dash_comparative_2011] and may be more adapted for the computation of association measures. Moreover, kernel methods could also be used to handle continuous variables better. Secondly, estimation of probabilities is done from the frequentist maximum-likelihood procedure which requires sufficiently large datasets. Unfortunately, in fields such as health sciences, datasets are sparse. Bayesian estimation methods are more robust to small sample sizes by not relying on asymptomatic assumptions and by allowing integration of prior knowledge [@wilkinson_bayesian_2007]. Such an implementation may also prove to be of interest.
<div id='section-references'>
## References
| /scratch/gouwar.j/cran-all/cranData/zebu/vignettes/zebu.Rmd |
#' @import behavr
#' @importFrom data.table ":=" "%between%"
#' @importFrom stats "acf" "approx" "na.omit" "pchisq" "pnorm" "power" "qchisq" "qnorm" "spec.pgram"
NULL
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/aaa.R |
#' Methods For Computing Periodograms
#'
#' These functions provides a series of methods to assess periodicity of circadian processes.
#'
#' @param x numeric vector
#' @param sampling_rate the -- implicitly regular -- sampling rate of x (in hertz)
#' @inheritParams periodogram
#' @return a [data.table] with the columns:
#' * `period` -- the period (in s)
#' * `power` -- the power (or equivalent) for a given period
#' * `p_value` -- the significance of the power
#' * `signif_threshold` -- the significance threshold of the power (at alpha)
#' @seealso
#' * [lomb::lsp] -- the orginal function for `ls_periodogram`
#' * [xsp::chiSqPeriodogram] -- code modified from
#' * [stats::acf] -- the orginal function for `ac_periodogram`
#' * [WaveletComp::analyze.wavelet] -- the orginal function for `cwt_periodogram`
#' @references
#' * [zeitgebr tutorial](https://rethomics.github.io/zeitgebr.html) -- the relevant rehtomics tutorial
#' @name periodogram_methods
NULL
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/aab-periodogram-methods.R |
#' @rdname periodogram_methods
#' @export
ac_periodogram <- function(x,
period_range = c(hours(16), hours(32)),
sampling_rate = 1 / mins(1),
alpha = 0.05
){
signif_threshold = period = power = p_value = NULL
max_lag <- period_range[2] * sampling_rate
min_lag <- period_range[1] * sampling_rate
res <- acf(x, lag.max = max_lag, plot = F)
clim <- qnorm((1 -alpha))/sqrt(res$n.used)
out <- data.table::data.table(period = res$lag[min_lag:length(res$lag)] /sampling_rate,
power = res$acf[min_lag:length(res$lag)],
signif_threshold = clim
)
out[, p_value := 1 - pnorm(power * sqrt(res$n.used))]
out
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/ac-periodogram.R |
#' @param time_resolution the resolution of periods to scan
#' @rdname periodogram_methods
#' @export
chi_sq_periodogram <- function(x,
period_range = c(hours(16), hours(32)),
sampling_rate = 1 / mins(1),
alpha = 0.05,
time_resolution = hours(0.1)){
# lsp can handle time series, so lets use that feature!
p_value = power = signif_threshold = period = .N = signif_threshold = NULL
out <- data.table::data.table(
period = seq(period_range[1],period_range[2],by=time_resolution)
)
corrected_alpha <- 1 - out[,(1 - alpha) ^ (1 / .N)]
out[ , power := sapply(period, calc_Qp, x, sampling_rate)]
out[ , signif_threshold := qchisq(corrected_alpha , round(period * sampling_rate), lower.tail = FALSE)]
out[ , p_value := pchisq(power, round(period * sampling_rate), lower.tail = FALSE)]
}
#' Calculate Qp
#'
#' @param values activity values (each value represents the measured activity in a minute)
#' @param target_period a period at which the chi-squared statistics is to be calculated
#'
#' @return a numeric of the calculated chi-squared statistics at the given varPer
#' @noRd
calc_Qp <- function(target_period, values, sampling_rate){
. = NULL
col_num <- round(target_period * sampling_rate)
#row_num <- ceiling(length(values) / col_num)
row_num <- length(values) / col_num
dt <- data.table::data.table( col = (0 : (length(values) -1) %% col_num) + 1,
#row = ceiling(1:length(values) / col_num),
values = values,
key = "col")
avg_P <- dt[, .(avg_P = mean(values)),by=col]$avg_P
avg_all <- mean(values)
numerator <- sum((avg_P - avg_all) ^ 2) * (nrow(dt) * row_num)
denom <- sum((values - avg_all) ^ 2)
numerator / denom
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/chi-sq-periodogram.R |
#' @param n_sim the number of shuffling simulation to compute p-value (see [WaveletComp::analyze.wavelet])
#' @param resolution the period resolution of the CWT (i.e. the number of suboctaves)
#' @rdname periodogram_methods
#' @export
cwt_periodogram <- function(x,
period_range = c(hours(16), hours(32)),
sampling_rate = 1 / mins(1),
alpha = 0.05,
resolution = 1/512,
n_sim = 10
){
signif_threshold = period = power = p_value = NULL
min_period <- period_range[1]
max_period <- period_range[2]
upper_period = ceiling( log2(max_period* sampling_rate))
lower_period = floor( log2(min_period* sampling_rate))
# wt works with data frames
dd <- data.table::data.table(x = x)
#upper_period = ceiling(1 + log2(max_period/ min_period))
wt <- WaveletComp::analyze.wavelet(dd,"x",
loess.span = 0,
dj = resolution,
dt = 1,
lowerPeriod = 2 ^ lower_period,
upperPeriod = 2 ^ upper_period,
make.pval = ifelse(n_sim >1,T,F),
verbose = F,
n.sim = n_sim,
method = "shuffle"
)
out <- data.table::data.table(power=wt$Power.avg, period = wt$Period /sampling_rate,
p_value = ifelse(is.null(wt$Power.avg.pval),NA,wt$Power.avg.pval))
out[, signif_threshold := ifelse(p_value > alpha, 0, power/1.1)]
out[period > period_range[1] & period < period_range[2]]
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/cwt-periodogram.R |
#' Computes a spectrogram using CWT
#'
#' A port of Continuous Wavelet transform to `rethomics`.
#' This function is intended to be used as an argument in the [spectrogram] wrapper.
#' @inheritParams cwt_periodogram
#' @param summary_time_window the sampling period after post-processing.
#' Values of power are avegraged over this time window, for each period.
#' @seealso
#' * [spectrogram] -- to apply this fucntion to all indivvidual, with some preprocessing.
#' * [WaveletComp::analyze.wavelet] -- the orginal function for `cwt_spectrogram`
#' @export
cwt_spectrogram <- function(x,
period_range = c(hours(1), hours(32)),
sampling_rate = 1 / mins(1),
resolution = 1/64,
summary_time_window = mins(30)){
signif_threshold = period = power = p_value = NULL
ridge = period_at_ridge = . = NULL
min_period <- period_range[1]
max_period <- period_range[2]
upper_period = ceiling( log2(max_period* sampling_rate))
lower_period = floor( log2(min_period* sampling_rate))
# wt works with data frames
dd <- data.table::data.table(x = x)
#upper_period = ceiling(1 + log2(max_period/ min_period))
wt <- WaveletComp::analyze.wavelet(dd,"x",
loess.span = 0,
dj = resolution,
dt = 1,
lowerPeriod = 2 ^ lower_period,
upperPeriod = 2 ^ upper_period,
make.pval = FALSE,
verbose = FALSE,
n.sim = 1
)
m <- cbind(expand.grid(wt$axis.2, wt$axis.1 / sampling_rate), as.vector(wt$Power), as.integer(as.vector(wt$Ridge)))
out <- data.table::as.data.table(m)
data.table::setnames(out, c("period", "t","power", "ridge"))
out[, t := floor(t/summary_time_window) * summary_time_window]
out[, period := 2^period / sampling_rate]
out[, .(power=mean(power), ridge=(sum(ridge))), by="t,period"]
ridge_period_dt <- out[, .(period_at_ridge = ifelse(max(ridge) > 0, period[which.max(ridge)],NA_real_)), by="t"]
out <- ridge_period_dt[out, on=c("t")]
out[, ridge := ridge & as.integer(!is.na(period_at_ridge) & period_at_ridge == period)]
out[, period_at_ridge := NULL]
out[, ridge := ifelse(period == min(period), F, ridge)]
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/cwt-spectrogram.R |
#' A behavr table with approximately ten days of DAM2 recording for 32 fruit flies.
#' The first 10, the following 11 and the last 11 animals have long, short and wild type period,
#' respectively (see `meta(dams_sample)`).
#'
#' @author Luis Garcia
#' @references Raw data stored at [https://github.com/rethomics/zeitgebr/tree/master/raw_data](https://github.com/rethomics/zeitgebr/tree/master/raw_data)
"dams_sample"
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/data.R |
#' Find peaks in a periodogram
#'
#' This function locates the peaks in a pregenerated periodogram.
#' Detection is based on [pracma::findpeaks].
#' Only the significant (i.e. `power > signif_threshold`) peaks are extracted.
#'
#' @param data [behavr::behavr] table representing a periodogram, as returned by [periodogram]
#' @param n_peaks maximal numbers of peak to be detected
#' @return [behavr::behavr] table that is `data` with an extra column `peak`.
#' `peak` is filled with zeros except for rows match a peak.
#' In which case, rows have an integer value corresponding to the rank of the peak (e.g. 1 for the first peak).
#' @examples
#' data(dams_sample)
#' # only four ndividuals for the sake of the example
#' dt <- dams_sample[xmv(region_id) %in% c(1, 7, 21, 31)]
#' per_dt_xs <- periodogram(activity, dt, FUN = chi_sq_periodogram)
#' per_dt_xs_with_peaks <- find_peaks(per_dt_xs)
#' per_dt_xs_with_peaks[peak == 1]
#' @seealso
#' * [periodogram] -- to generate a periodogram in a first place
#' * [ggetho::geom_peak] -- a layer to show peaks on a periodogram
#' @references
#' * [zeitgebr tutorial](https://rethomics.github.io/zeitgebr.html) -- the relevant rehtomics tutorial
#' @export
find_peaks <- function(data, n_peaks=3){
.SD = peak = NULL
out <- data.table::copy(data)
out[ , peak := find_peaks_wapped(.SD, n_peaks = n_peaks), by = c(data.table::key(out))]
# peaks are 0, not NA
out[, peak := ifelse(is.na(peak), 0L, peak)]
}
#' @noRd
find_peaks_wapped <- function(d, n_peaks = 3){
signif_threshold = NULL
x <- d[, power - signif_threshold]
peak_mat <- pracma::findpeaks(x,
peakpat = "[+]{1,}[0]*[-]{1,}",
sortstr = TRUE,
minpeakheight = 0
)
peak_idx <- rep(NA_real_,n_peaks)
out <- rep(NA_integer_, nrow(d))
if(!is.null(peak_mat))
out[peak_mat[,2]] <- 1:nrow(peak_mat)
out
}
# adapted from [pracma::findpeaks]
#' @noRd
findpeaks_pval <- function (x, #pval, #signif_threshold,
nups = 1, ndowns = nups, zero = "0", peakpat = "[+]{1,}[0]*[-]{1,}",
minpeakdistance = 1, threshold = 0, npeaks = 0, sortstr = FALSE){
stopifnot(is.vector(x, mode = "numeric") || length(is.na(x)) ==
0)
if (!zero %in% c("0", "+", "-"))
stop("Argument 'zero' can only be '0', '+', or '-'.")
xc <- paste(as.character(sign(diff(x))), collapse = "")
xc <- gsub("1", "+", gsub("-1", "-", xc))
if (zero != "0")
xc <- gsub("0", zero, xc)
if (is.null(peakpat)) {
peakpat <- sprintf("[+]{%d,}[-]{%d,}", nups, ndowns)
}
rc <- gregexpr(peakpat, xc)[[1]]
if (rc[1] < 0)
return(NULL)
x1 <- rc
x2 <- rc + attr(rc, "match.length")
attributes(x1) <- NULL
attributes(x2) <- NULL
n <- length(x1)
xv <- xp <- numeric(n)
for (i in 1:n) {
xp[i] <- which.max(x[x1[i]:x2[i]]) + x1[i] - 1
xv[i] <- x[xp[i]]
}
inds <- which( xv - pmax(x[x1], x[x2]) >=
threshold)
X <- cbind(xv[inds], xp[inds], x1[inds], x2[inds])
if (minpeakdistance < 1)
warning("Handling 'minpeakdistance < 1' is logically not possible.")
if (sortstr || minpeakdistance > 1) {
sl <- sort.list(X[, 1], na.last = NA, decreasing = TRUE)
X <- X[sl, , drop = FALSE]
}
if (length(X) == 0)
return(c())
if (minpeakdistance > 1) {
no_peaks <- nrow(X)
badpeaks <- rep(FALSE, no_peaks)
for (i in 1:no_peaks) {
ipos <- X[i, 2]
if (!badpeaks[i]) {
dpos <- abs(ipos - X[, 2])
badpeaks <- badpeaks | (dpos > 0 & dpos < minpeakdistance)
}
}
X <- X[!badpeaks, ]
}
if (npeaks > 0 && npeaks < nrow(X)) {
X <- X[1:npeaks, , drop = FALSE]
}
return(X)
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/find-peaks.R |
#' @rdname periodogram_methods
#' @export
fourier_periodogram <- function(x,
period_range = c(hours(16), hours(32)),
sampling_rate = 1 / mins(1),
alpha = 0.05
){
.N = period = p_value = signif_threshold = NULL
raw_periodo <- spec.pgram(x, detrend=TRUE, plot=FALSE)
out <- data.table::data.table(power = raw_periodo$spec,
period = 1/ (raw_periodo$freq *sampling_rate) # frequence, in seconds
)
out <- out[ period %between% period_range]
# peak period = argmax[period](power)
peak_period <-out[power == max(power), period]
# one should compute the pvalues directly
out[, p_value := NA]
# Compute the significance level with probablility 0.01, acordind to fisher 1929
# signif_threshold is independent of period with this method
out[, signif_threshold := - mean(power) * log((1 - (1 - alpha) ^ (1 / .N)))]
out
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/fourier-periodogram.R |
#' @param oversampling the oversampling factor (see [lomb::lsp])
#' @rdname periodogram_methods
#' @export
ls_periodogram <- function(x,
period_range = c(hours(16), hours(32)),
sampling_rate = 1 / mins(1),
alpha = 0.05,
oversampling = 8
){
# lsp can handle time series, so lets use that feature!
lsp_results <- lomb::lsp(x,
times = 1:length(x) / sampling_rate,
from = period_range[1],
to = period_range[2],
type="period",
alpha = alpha,
ofac= oversampling,
plot=FALSE)
p_values <- exp(-lsp_results$power) * lsp_results$n.out * 2 / oversampling
p_values <- ifelse(p_values >= 1, 1, p_values)
out <- data.table::data.table(period = lsp_results$scanned,
power = lsp_results$power,
p_value = p_values,
signif_threshold = lsp_results$sig.level)
out[power == lsp_results$peak]
out
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/ls-periodogram.R |
#' Computes periodograms
#'
#' This function builds periodograms, with one of several methods, for each individual of a [behavr] table
#'
#' @param var variable to analyse
#' @param data [behavr] table
#' @param period_range vector of size 2 defining minimal and maximal range of period to study (in seconds)
#' @param resample_rate frequency to resample (up or down) the data at (in hertz)
#' @param alpha significance level
#' @param FUN function used to compute periodogram (see [periodogram_methods])
#' @param ... additional arguments to be passed to FUN
#' @return A [behavr::behavr] table.
#' In addition to the metadata, it contains data that encodes a periodogram (i.e. power vs period).
#' The data contains the columns:
#' * `power` -- the power the or equivalent (according to `FUN`)
#' * `period` -- the period at which `power` is computed (in seconds)
#' * `p_value` -- the p value associated to the power estimation
#' * `signif threshold` -- the threshold above which power is considered significant
#'
#' @examples
#' data(dams_sample)
#' # only four individuals for the sake of the example
#' dt <- dams_sample[xmv(region_id) %in% c(1, 7, 21, 31)]
#' pdt <- periodogram(activity, dt, FUN = ls_periodogram, oversampling = 4)
#' pdt <- periodogram(activity, dt, FUN = chi_sq_periodogram)
#' \donttest{
#' require(ggetho)
#' ggperio(pdt, aes(colour=period_group)) + stat_pop_etho()
#' }
#'
#' @seealso
#' * [periodogram_methods] -- the list of built-in methods
#' * [find_peaks] -- to find peaks in the periodogram
#' * [ggetho::ggperio] -- to plot periodograms
#' @references
#' * [zeitgebr tutorial](https://rethomics.github.io/zeitgebr.html) -- the relevant rehtomics tutorial
#' @export
periodogram <- function(var,
data,
period_range = c(hours(16), hours(32)),
resample_rate = 1 / mins(15),
alpha = 0.01,
FUN = chi_sq_periodogram,
...){
n_val = var__ = key = . = .N = NULL
var_of_interest <- deparse(substitute(var))
regular_data <- resample(data, var_of_interest, resample_rate)
key = data.table::key(regular_data)
data.table::setnames(regular_data, var_of_interest, "var__")
reg_data_nval <- regular_data[, .(n_val = length(unique(var__))),
by = c(key)]
invalid <- reg_data_nval[n_val < 2][[key]]
if(length(invalid) > 0)
warning(sprintf("Removing individuals that have only one unique value for `val`:\n%s",
paste(invalid, sep="\n")))
regular_data <- regular_data[!(key %in% invalid)]
regular_data[, FUN(var__,
period_range = period_range,
sampling_rate = resample_rate,
alpha = alpha,
...),
by = c(key)]
}
#' helper unit-testable function
#' @noRd
resample <- function(data, var_of_interest, resample_rate){
.N = .SD = NULL
regular_data <- behavr::bin_apply_all(data,
x = "t",
y = var_of_interest,
x_bin_length = 1 / resample_rate,
string_xy = TRUE)
f <- function(d){
new_x <- seq(from = d[1, t], to = d[.N, t], by=1/resample_rate)
out <- na.omit(data.table::as.data.table(approx(d[["t"]],y = d[[var_of_interest]], xout = new_x)))
data.table::setnames(out, c("x", "y"), c("t",var_of_interest))
out
}
regular_data <- regular_data[, f(.SD), by=c(data.table::key(regular_data))]
regular_data
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/periodogram.R |
#' Computes spectrogram
#'
#' This function builds spectrogram, using CWT, for each individual of a [behavr] table
#'
#' @param var variable to analyse
#' @param data [behavr] table
#' @param period_range vector of size 2 defining minimal and maximal range of period to study (in seconds)
#' @param resample_rate frequency to resample (up or down) the data at (in hertz)
#' @param FUN function used to compute spectrograms (so far, only CWT is implemented via [cwt_spectrogram])
#' @param ... additional arguments to be passed to FUN
#' @return A [behavr::behavr] table.
#' In addition to the metadata, it contains data that encodes a spectrogram (i.e. power vs period).
#' The data contains the columns:
#' * `t` -- the time (in s) (same range the input time)
#' * `period` -- the period at which the `power` is computed, for a given `t` (in s)
#' * `power` -- the power the or equivalent (according to `FUN`)
#' * `ridge` -- a logical defining whether the point (`t` and `period`) is a ridge
#' @details A spectrogram is a estimation of the local periodicity of a signal at a given time.
#' In the context of circadian rhythm, it can be useful to understand how infradian rhythms change along the day or,
#' for instance, how circadian rhythm change ver the course of an multi-day experiment.
#' @examples
#' data(dams_sample)
#' dt <- dams_sample[id %in% dams_sample[meta=TRUE, ,id[1:5]]]
#' spect_dt <- spectrogram(activity, dt)
#'
#' \donttest{
#' require(ggetho)
#' ggspectro(spect_dt) +
#' stat_tile_etho() +
#' scale_y_log10() +
#' facet_wrap(~ id)
#' }
#' @seealso
#' * [periodogram] -- to compute periodogram instead
#' * [cwt_spectrogram] -- The dunction use to compute individual spectrograms
#' * [ggetho::ggspectro] -- to plot spectrograms
#' @references
#' * [spectrogram tutorial](https://rethomics.github.io/ggetho.html#spectrograms) -- the relevant rehtomics tutorial
#' @export
spectrogram <- function(var,
data,
period_range = c(hours(16), hours(32)),
resample_rate = 1 / mins(15),
FUN = cwt_spectrogram,
...){
n_val = var__ = key = . = .N = t0 = .SD = NULL
var_of_interest <- deparse(substitute(var))
regular_data <- resample(data, var_of_interest, resample_rate)
key <- data.table::key(regular_data)
data.table::setnames(regular_data, var_of_interest, "var__")
reg_data_nval <- regular_data[, .(n_val = length(unique(var__))),
by = c(key)]
invalid <- reg_data_nval[n_val < 2][[key]]
if(length(invalid) > 0)
warning(sprintf("Removing individuals that have only one unique value for `val`:\n%s",paste(invalid, sep="\n")))
regular_data <- regular_data[!(key %in% invalid)]
out <- regular_data[, FUN(var__,
period_range = period_range,
sampling_rate = resample_rate,
...),
by = c(key)]
time_origin <- data[, .(t0 = .SD[1,t]),by=c(key)]
out[, t:= out[time_origin, on=key][,t +t0]]
out
}
| /scratch/gouwar.j/cran-all/cranData/zeitgebr/R/spectrogram.R |
#' ZenodoManager
#' @docType class
#' @export
#' @keywords zenodo manager
#' @return Object of \code{\link{R6Class}} for modelling an ZenodoManager
#' @format \code{\link{R6Class}} object.
#'
#' @examples
#' \dontrun{
#' ZENODO <- ZenodoManager$new(
#' url = "https://sandbox.zenodo.org/api",
#' token = "<your_token>",
#' logger = "INFO"
#' )
#'
#' #create (deposit) an empty record
#' newRec <- ZENODO$createEmptyRecord()
#'
#' #create and fill a local (not yet deposited) record
#' myrec <- ZenodoRecord$new()
#' myrec$setTitle("my R package")
#' myrec$setDescription("A description of my R package")
#' myrec$setUploadType("software")
#' myrec$addCreator(
#' firstname = "John", lastname = "Doe",
#' affiliation = "Independent", orcid = "0000-0000-0000-0000"
#' )
#' myrec$setLicense("mit")
#' myrec$setAccessRight("open")
#' myrec$setDOI("mydoi") #use this method if your DOI has been assigned elsewhere, outside Zenodo
#' myrec$addCommunity("ecfunded")
#'
#' #deposit the record
#' myrec <- ZENODO$depositRecord(myrec)
#'
#' #publish a record (with caution!!)
#' #this method will PUBLISH the deposition done earlier
#' ZENODO$publishRecord(myrec$id)
#' #With even more caution the publication can be done with a shortcut argument at deposit time
#' ZENODO$depositRecord(myrec, publish = TRUE)
#'
#' #delete a record (by id)
#' #this methods only works for unpublished deposits
#' #(if a record is published, it cannot be deleted anymore!)
#' ZENODO$deleteRecord(myrec$id)
#'
#' #HOW TO UPLOAD FILES to a deposit
#'
#' #upload a file
#' ZENODO$uploadFile("path/to/your/file", record = myrec)
#'
#' #list files
#' zen_files <- ZENODO$getFiles(myrec$id)
#'
#' #delete a file?
#' ZENODO$deleteFile(myrec$id, zen_files[[1]]$id)
#' }
#'
#' @note Main user class to be used with \pkg{zen4R}
#'
#' @author Emmanuel Blondel <emmanuel.blondel1@@gmail.com>
#'
ZenodoManager <- R6Class("ZenodoManager",
inherit = zen4RLogger,
private = list(
keyring_backend = NULL,
keyring_service = NULL,
url = "https://zenodo.org/api",
verbose.info = FALSE
),
public = list(
#' @field sandbox Zenodo manager sandbox status, \code{TRUE} if we interact with Sandbox infra
sandbox = FALSE,
#' @field anonymous Zenodo manager anonymous status, \code{TRUE} when no token is specified
anonymous = FALSE,
#' @description initializes the Zenodo Manager
#' @param url Zenodo API URL. By default, the url is set to "https://zenodo.org/api". For tests,
#' the Zenodo sandbox API URL can be used: https://sandbox.zenodo.org/api
#' @param token the user token. By default an attempt will be made to retrieve token using \link{zenodo_pat}
#' @param sandbox Indicates if the Zenodo sandbox platform should be used. Default is \code{FALSE}
#' @param logger logger type. The logger can be either NULL, "INFO" (with minimum logs), or "DEBUG"
#' (for complete curl http calls logs)
#' @param keyring_backend The \pkg{keyring} backend used to store user token. The \code{keyring_backend}
#' can be set to use a different backend for storing the Zenodo token with \pkg{keyring} (Default value is 'env').
initialize = function(url = "https://zenodo.org/api", token = zenodo_pat(), sandbox = FALSE, logger = NULL,
keyring_backend = 'env'){
super$initialize(logger = logger)
if(sandbox) url = "https://sandbox.zenodo.org/api"
private$url = url
if(url == "https://sandbox.zenodo.org/api") self$sandbox = TRUE
if(!is.null(token)) if(nzchar(token)){
if(!keyring_backend %in% names(keyring:::known_backends)){
errMsg <- sprintf("Backend '%s' is not a known keyring backend!", keyring_backend)
self$ERROR(errMsg)
stop(errMsg)
}
private$keyring_backend <- keyring:::known_backends[[keyring_backend]]$new()
private$keyring_service = paste0("zen4R@", url)
private$keyring_backend$set_with_value(private$keyring_service, username = "zen4R", password = token)
deps <- self$getDepositions(size = 1, quiet = TRUE)
if(!is.null(deps$status)) {
if(deps$status == 401){
errMsg <- "Cannot connect to your Zenodo deposit: Invalid token"
self$ERROR(errMsg)
stop(errMsg)
}
}else{
self$INFO("Successfully connected to Zenodo with user token")
}
}else{
self$INFO("Successfully connected to Zenodo as anonymous user")
self$anonymous <- TRUE
}
},
#' @description Get user token
#' @return the token, object of class \code{character}
getToken = function(){
token <- NULL
if(!is.null(private$keyring_service)){
token <- suppressWarnings(private$keyring_backend$get(private$keyring_service, username = "zen4R"))
}
return(token)
},
#Licenses
#------------------------------------------------------------------------------------------
#' @description Get Licenses supported by Zenodo.
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of licenses as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of licenses.
#' @return list of licenses as \code{data.frame} or \code{list}
getLicenses = function(pretty = TRUE){
zenReq <- ZenodoRequest$new(private$url, "GET", "licenses/?q=&size=1000",
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
out <- out$hits$hits
if(pretty){
out = do.call("rbind", lapply(out,function(x){
rec = x$metadata
rec$`$schema` <- NULL
rec$is_generic <- NULL
rec$suggest <- NULL
rec <- as.data.frame(rec)
rec <- rec[,c("id", "title", "url", "domain_content", "domain_data", "domain_software", "family",
"maintainer", "od_conformance", "osd_conformance", "status")]
return(rec)
}))
}
self$INFO("Successfully fetched list of licenses")
}else{
self$ERROR(sprintf("Error while fetching licenses: %s", out$message))
}
return(out)
},
#' @description Get license by Id.
#' @param id license id
#' @return the license
getLicenseById = function(id){
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("licenses/%s",id),
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
self$INFO(sprintf("Successfully fetched license '%s'",id))
}else{
self$ERROR(sprintf("Error while fetching license '%s': %s", id, out$message))
}
return(out)
},
#Communities
#------------------------------------------------------------------------------------------
#' @description Get Communities supported by Zenodo.
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of communities as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of communities
#' @return list of communities as \code{data.frame} or \code{list}
getCommunities = function(pretty = TRUE){
zenReq <- ZenodoRequest$new(private$url, "GET", "communities/?q=&size=10000",
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
out <- out$hits$hits
if(pretty){
out = do.call("rbind", lapply(out,function(x){
rec = data.frame(
id = x$id,
title = x$title,
description = x$description,
curation_policy = x$curation_policy,
url = x$links$html,
created = x$created,
updated = x$updated,
stringsAsFactors = FALSE
)
return(rec)
}))
}
self$INFO("Successfully fetched list of communities")
}else{
self$ERROR(sprintf("Error while fetching communities: %s", out$message))
}
return(out)
},
#' @description Get community by Id.
#' @param id community id
#' @return the community
getCommunityById = function(id){
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("communities/%s",id),
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
self$INFO(sprintf("Successfully fetched community '%s'",id))
}else{
self$ERROR(sprintf("Error while fetching community '%s': %s", id, out$message))
out <- NULL
}
return(out)
},
#Grants
#------------------------------------------------------------------------------------------
#' @description Get Grants supported by Zenodo.
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of grants as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of grants
#' @param q an ElasticSearch compliant query, object of class \code{character}. Default is emtpy.
#' Note that the Zenodo API restrains a maximum number of 10,000 grants to be retrieved. Consequently,
#' not all grants can be listed from Zenodo, a query has to be specified.
#' @param size number of grants to be returned. By default equal to 1000.
#' @return list of grants as \code{data.frame} or \code{list}
getGrants = function(q = "", pretty = TRUE, size = 1000){
if(q=="") size = 10000
page <- 1
lastPage <- FALSE
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("grants/?q=%s&size=%s&page=%s", URLencode(q), size, page),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
grants <- resp$hits$hits
total <- resp$hits$total
if(total > 10000){
self$WARN(sprintf("Total of %s records found: the Zenodo API limits to a maximum of 10,000 records!", total))
}
total_remaining <- total
hasGrants <- length(grants)>0
while(hasGrants){
out <- c(out, grants)
if(!is.null(grants)){
self$INFO(sprintf("Successfully fetched list of grants - page %s", page))
if(q!=""){
page <- page+1 #next
total_remaining <- total_remaining-length(grants)
}else{
break;
}
}else{
lastPage <- TRUE
}
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("grants/?q=%s&size=%s&page=%s", URLencode(q), size, page),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
grants <- resp$hits$hits
hasGrants <- length(grants)>0
if(lastPage) break;
}else{
self$WARN(sprintf("Maximum allowed size for list of grants - page %s - attempt to decrease size", page))
size <- size-1
hasGrants <- TRUE
grants <- NULL
}
}
self$INFO("Successfully fetched list of grants!")
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while fetching grants: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
if(pretty){
out = do.call("rbind", lapply(out,function(x){
rec = data.frame(
id = x$metadata$internal_id,
code = x$metadata$code,
title = x$metadata$title,
startdate = x$metadata$startdate,
enddate = x$metadata$enddate,
url = x$metadata$url,
created = x$created,
updated = x$updated,
funder_country = x$metadata$funder$country,
funder_doi = x$metadata$funder$doi,
funder_name = x$metadata$funder$name,
funder_type = x$metadata$funder$type,
funder_subtype = x$metadata$funder$subtype,
funder_parent_country = if(length(x$metadata$funder$parent)>0) x$metadata$funder$parent$country else NA,
funder_parent_doi = if(length(x$metadata$funder$parent)>0) x$metadata$funder$parent$doi else NA,
funder_parent_name = if(length(x$metadata$funder$parent)>0) x$metadata$funder$parent$name else NA,
funder_parent_type = if(length(x$metadata$funder$parent)>0) x$metadata$funder$parent$type else NA,
funder_parent_subtype = if(length(x$metadata$funder$parent)>0) x$metadata$funder$parent$subtype else NA,
stringsAsFactors = FALSE
)
return(rec)
}))
}
return(out)
},
#' @description Get grants by name.
#' @param name name
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of grants as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of grants
#' @return list of grants as \code{data.frame} or \code{list}
getGrantsByName = function(name, pretty = TRUE){
query = sprintf("title:%s", URLencode(paste0("\"",name,"\"")))
self$getGrants(q = query, pretty = pretty)
},
#' @description Get grant by Id.
#' @param id grant id
#' @return the grant
getGrantById = function(id){
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("grants/%s",id),
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
self$INFO(sprintf("Successfully fetched grant '%s'",id))
}else{
self$ERROR(sprintf("Error while fetching grant '%s': %s", id, out$message))
out <- NULL
}
return(out)
},
#Funders
#------------------------------------------------------------------------------------------
#' @description Get Funders supported by Zenodo based on a query.
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of funders as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of funders
#' @param q an ElasticSearch compliant query, object of class \code{character}. Default is emtpy.
#' Note that the Zenodo API restrains a maximum number of 10,000 funders to be retrieved. Consequently,
#' not all funders can be listed from Zenodo, a query has to be specified.
#' @param size number of funders to be returned. By default equal to 1000.
#' @return list of funders as \code{data.frame} or \code{list}
getFunders = function(q = "", pretty = TRUE, size = 1000){
if(q=="") size = 10000
page <- 1
lastPage <- FALSE
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("funders/?q=%s&size=%s&page=%s", URLencode(q), size, page),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
funders <- resp$hits$hits
total <- resp$hits$total
if(total > 10000){
self$WARN(sprintf("Total of %s records found: the Zenodo API limits to a maximum of 10,000 records!", total))
}
total_remaining <- total
hasFunders <- length(funders)>0
while(hasFunders){
out <- c(out, funders)
if(!is.null(funders)){
self$INFO(sprintf("Successfully fetched list of funders - page %s", page))
if(q != ""){
page <- page+1 #next
total_remaining <- total_remaining-length(funders)
}else{
break;
}
}else{
lastPage <- TRUE
}
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("funders/?q=%s&size=%s&page=%s", URLencode(q), size, page),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
funders <- resp$hits$hits
hasFunders <- length(funders)>0
if(lastPage) break;
}else{
self$WARN(sprintf("Maximum allowed size for list of funders - page %s - attempt to decrease size", page))
size <- size-1
hasFunders <- TRUE
funders <- NULL
}
}
self$INFO("Successfully fetched list of funders!")
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while fetching funders: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
if(pretty){
out = do.call("rbind", lapply(out,function(x){
rec = data.frame(
id = x$metadata$doi,
doi = x$metadata$doi,
country = x$metadata$country,
name = x$metadata$name,
type = x$metadata$type,
subtype = x$metadata$subtype,
created = x$created,
updated = x$updated,
stringsAsFactors = FALSE
)
return(rec)
}))
}
return(out)
},
#' @description Get funders by name.
#' @param name name
#' @param pretty Prettify the output. By default the argument \code{pretty} is set to
#' \code{TRUE} which will returns the list of funders as \code{data.frame}.
#' Set \code{pretty = FALSE} to get the raw list of funders
#' @return list of funders as \code{data.frame} or \code{list}
getFundersByName = function(name, pretty = TRUE){
query = sprintf("name:%s", URLencode(paste0("\"",name,"\"")))
self$getFunders(q = query, pretty = pretty)
},
#' @description Get funder by Id.
#' @param id funder id
#' @return the funder
getFunderById = function(id){
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("funders/%s",id),
token= self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- zenReq$getResponse()
if(zenReq$getStatus() == 200){
self$INFO(sprintf("Successfully fetched funder '%s'",id))
}else{
self$ERROR(sprintf("Error while fetching funder '%s': %s", id, out$message))
out <- NULL
}
return(out)
},
#Depositions
#------------------------------------------------------------------------------------------
#' @description Get the list of Zenodo records deposited in your Zenodo workspace. By defaut
#' the list of depositions will be returned by page with a size of 10 results per
#' page (default size of the Zenodo API). The parameter \code{q} allows to specify
#' an ElasticSearch-compliant query to filter depositions (default query is empty
#' to retrieve all records). The argument \code{all_versions}, if set to TRUE allows
#' to get all versions of records as part of the depositions list. The argument \code{exact}
#' specifies that an exact matching is wished, in which case paginated search will be
#' disabled (only the first search page will be returned).
#' Examples of ElasticSearch queries for Zenodo can be found at \href{https://help.zenodo.org/guides/search/}{https://help.zenodo.org/guides/search/}.
#' @param q Elastic-Search-compliant query, as object of class \code{character}. Default is ""
#' @param size number of depositions to be retrieved per request (paginated). Default is 10
#' @param all_versions object of class \code{logical} indicating if all versions of deposits have to be retrieved. Default is \code{FALSE}
#' @param exact object of class \code{logical} indicating if exact matching has to be applied. Default is \code{TRUE}
#' @param quiet object of class \code{logical} indicating if logs have to skipped. Default is \code{FALSE}
#' @return a list of \code{ZenodoRecord}
getDepositions = function(q = "", size = 10, all_versions = FALSE, exact = TRUE,
quiet = FALSE){
page <- 1
baseUrl <- "deposit/depositions"
#set in #72, now re-deactivated through #76 (due to Zenodo server-side changes)
#if(!private$sandbox) baseUrl <- paste0(baseUrl, "/")
req <- sprintf("%s?q=%s&size=%s&page=%s", baseUrl, URLencode(q), size, page)
if(all_versions) req <- paste0(req, "&all_versions=1")
zenReq <- ZenodoRequest$new(private$url, "GET", req,
token = self$getToken(),
logger = if(quiet) NULL else self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
hasRecords <- length(resp)>0
while(hasRecords){
out <- c(out, lapply(resp, ZenodoRecord$new))
if(!quiet) self$INFO(sprintf("Successfully fetched list of depositions - page %s", page))
if(exact){
hasRecords <- FALSE
}else{
#next
page <- page+1
nextreq <- sprintf("%s?q=%s&size=%s&page=%s", baseUrl, q, size, page)
if(all_versions) nextreq <- paste0(nextreq, "&all_versions=1")
zenReq <- ZenodoRequest$new(private$url, "GET", nextreq,
token = self$getToken(),
logger = if(quiet) NULL else self$loggerType)
zenReq$execute()
resp <- zenReq$getResponse()
hasRecords <- length(resp)>0
}
}
if(!quiet) self$INFO("Successfully fetched list of depositions!")
}else{
out <- zenReq$getResponse()
if(!quiet) self$ERROR(sprintf("Error while fetching depositions: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
return(out)
},
#' @description Get a Zenodo deposition record by concept DOI (generic DOI common to all deposition record versions).
#' @param conceptdoi the concept DOI, object of class \code{character}
#' @return an object of class \code{ZenodoRecord} if record does exist, NULL otherwise
getDepositionByConceptDOI = function(conceptdoi){
query <- sprintf("conceptdoi:\"%s\"", conceptdoi)
result <- self$getDepositions(q = query, exact = TRUE)
if(length(result)>0){
conceptdois <- vapply(result, function(i){
i$getConceptDOI()
}, character(1))
if (!conceptdoi %in% conceptdois){
result <- NULL
}else{
result <- result[[which(conceptdois == conceptdoi)[1]]]
self$INFO(sprintf("Successfully fetched record for concept DOI '%s'!", conceptdoi))
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for concept DOI '%s'!", conceptdoi))
if(is.null(result)){
#try to get record by id
if( regexpr("zenodo", conceptdoi)>0){
conceptrecid <- unlist(strsplit(conceptdoi, "zenodo."))[2]
self$INFO(sprintf("Try to get deposition by Zenodo specific record id '%s'", conceptrecid))
conceptrec <- self$getDepositionByConceptId(conceptrecid)
last_doi <- tail(conceptrec$getVersions(),1L)$doi
if(length(last_doi)==0) {
if(nzchar(conceptrec$metadata$doi)){
last_doi = conceptrec$metadata$doi
}else{
last_doi = conceptrec$metadata$prereserve_doi$doi
}
}
result <- self$getDepositionByDOI(last_doi)
}
}
return(result)
},
#' @description Get a Zenodo deposition record by DOI.
#' @param doi the DOI, object of class \code{character}
#' @return an object of class \code{ZenodoRecord} if record does exist, NULL otherwise
getDepositionByDOI = function(doi){
query <- sprintf("doi:\"%s\"", doi)
result <- self$getDepositions(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$doi == doi){
self$INFO(sprintf("Successfully fetched record for DOI '%s'!",doi))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for DOI '%s'!",doi))
if(is.null(result)){
#try to get record by id
if( regexpr("zenodo", doi)>0){
recid <- unlist(strsplit(doi, "zenodo."))[2]
self$INFO(sprintf("Try to get deposition by Zenodo specific record id '%s'", recid))
result <- self$getDepositionById(recid)
}
}
return(result)
},
#' @description Get a Zenodo deposition record by ID.
#' @param recid the record ID, object of class \code{character}
#' @return an object of class \code{ZenodoRecord} if record does exist, NULL otherwise
getDepositionById = function(recid){
query <- sprintf("recid:%s", recid)
result <- self$getDepositions(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$id == recid){
self$INFO(sprintf("Successfully fetched record for id '%s'!",recid))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for id '%s'!",recid))
return(result)
},
#' @description Get a Zenodo deposition record by concept ID.
#' @param conceptrecid the record concept ID, object of class \code{character}
#' @return an object of class \code{ZenodoRecord} if record does exist, NULL otherwise
getDepositionByConceptId = function(conceptrecid){
query <- sprintf("conceptrecid:%s", conceptrecid)
result <- self$getDepositions(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$conceptrecid == conceptrecid){
self$INFO(sprintf("Successfully fetched record for concept id '%s'!",conceptrecid))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for concept id '%s'!",conceptrecid))
return(result)
},
#' @description Deposits a record on Zenodo.
#' @param record the record to deposit, object of class \code{ZenodoRecord}
#' @param publish object of class \code{logical} indicating if record has to be published (default \code{FALSE}).
#' Can be set to \code{TRUE} (to use CAUTIOUSLY, only if you want to publish your record)
#' @return \code{TRUE} if deposited (and eventually published), \code{FALSE} otherwise
depositRecord = function(record, publish = FALSE){
data <- record
type <- ifelse(is.null(record$id), "POST", "PUT")
request <- ifelse(is.null(record$id), "deposit/depositions",
sprintf("deposit/depositions/%s", record$id))
zenReq <- ZenodoRequest$new(private$url, type, request, data = data,
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() %in% c(200,201)){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO("Successful record deposition")
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while depositing record: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
if(publish){
out <- self$publishRecord(record$id)
}
return(out)
},
#' @description Deposits a record version on Zenodo. For details about the behavior of this function,
#' see \href{https://developers.zenodo.org/#new-version}{https://developers.zenodo.org/#new-version}
#' @param record the record version to deposit, object of class \code{ZenodoRecord}
#' @param delete_latest_files object of class \code{logical} indicating if latest files have to be deleted. Default is \code{TRUE}
#' @param files a list of files to be uploaded with the new record version
#' @param publish object of class \code{logical} indicating if record has to be published (default \code{FALSE})
#' @return \code{TRUE} if deposited (and eventually published), \code{FALSE} otherwise
depositRecordVersion = function(record, delete_latest_files = TRUE, files = list(), publish = FALSE){
type <- "POST"
if(is.null(record$conceptrecid)){
stop("The record concept id cannot be null for creating a new version")
}
if(is.null(record$conceptdoi)){
stop("Concept DOI is null: a new version can only be added to a published record")
}
#id of the last record
record_id <- unlist(strsplit(record$links$latest,"records/"))[[2]]
self$INFO(sprintf("Creating new version for record '%s' (concept DOI: '%s')", record_id, record$getConceptDOI()))
request <- sprintf("deposit/depositions/%s/actions/newversion", record_id)
zenReq <- ZenodoRequest$new(private$url, type, request, data = NULL,
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
out_id <- NULL
if(zenReq$getStatus() %in% c(200,201)){
out <- zenReq$getResponse()
out_id <- unlist(strsplit(out$links$latest_draft,"depositions/"))[[2]]
out <- self$getDepositionById(out_id)
self$INFO(sprintf("Successful new version record created for concept DOI '%s'", record$getConceptDOI()))
record$id <- out$id
record$metadata$doi <- NULL
record$doi <- NULL
record$prereserveDOI(TRUE)
out <- self$depositRecord(record)
if(delete_latest_files){
self$INFO("Deleting files copied from latest record")
invisible(lapply(out$files, function(x){
self$deleteFile(out$id, x$id)
Sys.sleep(0.6)
}))
}
if(length(files)>0){
self$INFO("Upload files to new version")
for(f in files){
self$INFO(sprintf("Upload file '%s' to new version", f))
self$uploadFile(f, record = out)
}
}
if(publish){
out <- self$publishRecord(record$id)
}
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while creating new version: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
return(out)
},
#' @description Deletes a record given its ID
#' @param recordId the ID of the record to be deleted
#' @return \code{TRUE} if deleted, \code{FALSE} otherwise
deleteRecord = function(recordId){
zenReq <- ZenodoRequest$new(private$url, "DELETE", "deposit/depositions",
data = recordId, token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- FALSE
if(zenReq$getStatus() == 204){
out <- TRUE
self$INFO(sprintf("Successful deleted record '%s'", recordId))
}else{
resp <- zenReq$getResponse()
self$ERROR(sprintf("Error while deleting record '%s': %s", recordId, resp$message))
}
return(out)
},
#' @description Deletes a record by DOI
#' @param doi the DOI of the record to be deleted
#' @return \code{TRUE} if deleted, \code{FALSE} otherwise
deleteRecordByDOI = function(doi){
self$INFO(sprintf("Deleting record with DOI '%s'", doi))
deleted <- FALSE
rec <- self$getDepositionByDOI(doi)
if(!is.null(rec)){
deleted <- self$deleteRecord(rec$id)
}
return(deleted)
},
#' @description Deletes all Zenodo deposited (unpublished) records.
#' The parameter \code{q} allows to specify an ElasticSearch-compliant query to filter depositions (default query
#' is empty to retrieve all records). Examples of ElasticSearch queries for Zenodo can be found at
#' \href{https://help.zenodo.org/guides/search/}{https://help.zenodo.org/guides/search/}.
#' @param q an ElasticSearch compliant query, object of class \code{character}
#' @param size number of records to be passed to \code{$getDepositions} method
#' @return \code{TRUE} if all records have been deleted, \code{FALSE} otherwise
deleteRecords = function(q = "", size = 10){
records <- self$getDepositions(q = q, size = size)
records <- records[sapply(records, function(x){!x$submitted})]
hasDraftRecords <- length(records)>0
if(length(records)>0){
record_ids <- sapply(records, function(x){x$id})
deleted.all <- sapply(record_ids, self$deleteRecord)
deleted.all <- deleted.all[is.na(deleted.all)]
deleted <- all(deleted.all)
if(!deleted){
self$ERROR("Error while deleting records")
}
}
self$INFO("Successful deleted records")
},
#' @description Creates an empty record in the Zenodo deposit. Returns the record
#' newly created in Zenodo, as an object of class \code{ZenodoRecord} with an
#' assigned identifier.
#' @return an object of class \code{ZenodoRecord}
createEmptyRecord = function(){
return(self$depositRecord(NULL))
},
#' @description Unlocks a record already submitted. Required to edit metadata of a Zenodo record already published.
#' @param recordId the ID of the record to unlock and set in editing mode.
#' @return an object of class \code{ZenodoRecord}
editRecord = function(recordId){
zenReq <- ZenodoRequest$new(private$url, "POST", sprintf("deposit/depositions/%s/actions/edit", recordId),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 201){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO(sprintf("Successful unlocked record '%s' for edition", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while unlocking record '%s' for edition: %s", recordId, out$message))
}
return(out)
},
#' @description Discards changes on a Zenodo record.
#' @param recordId the ID of the record for which changes have to be discarded.
#' @return an object of class \code{ZenodoRecord}
discardChanges = function(recordId){
zenReq <- ZenodoRequest$new(private$url, "POST", sprintf("deposit/depositions/%s/actions/discard", recordId),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 201){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO(sprintf("Successful discarded changes for record '%s' for edition", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while discarding record '%s' changes: %s", recordId, out$message))
}
return(out)
},
#' @description Publishes a Zenodo record.
#' @param recordId the ID of the record to be published.
#' @return an object of class \code{ZenodoRecord}
publishRecord = function(recordId){
zenReq <- ZenodoRequest$new(private$url, "POST", sprintf("deposit/depositions/%s/actions/publish",recordId),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 202){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO(sprintf("Successful published record '%s'", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while publishing record '%s': %s", recordId, out$message))
}
return(out)
},
#' @description Get list of files attached to a Zenodo record.
#' @param recordId the ID of the record.
#' @return list of files
getFiles = function(recordId){
zenReq <- ZenodoRequest$new(private$url, "GET", sprintf("deposit/depositions/%s/files", recordId),
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 201){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO(sprintf("Successful fetched file(s) for record '%s'", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while fetching file(s) for record '%s': %s", recordId, out$message))
}
return(out)
},
#' @description Uploads a file to a Zenodo record
#' @param path Local path of the file
#' @param record object of class \code{ZenodoRecord}
#' @param recordId ID of the record. Deprecated, use \code{record} instead to take advantage of the new Zenodo bucket upload API.
uploadFile = function(path, record = NULL, recordId = NULL){
newapi = TRUE
if(!is.null(recordId)){
self$WARN("'recordId' argument is deprecated, please consider using 'record' argument giving an object of class 'ZenodoRecord'")
self$WARN("'recordId' is used, cannot determine new API record bucket, switch to old upload API...")
newapi <- FALSE
}
if(!is.null(record)) recordId <- record$id
fileparts <- unlist(strsplit(path,"/"))
filename <- fileparts[length(fileparts)]
if(!"bucket" %in% names(record$links)){
self$WARN(sprintf("No bucket link for record id = %s. Revert to old file upload API", recordId))
newapi <- FALSE
}
method <- if(newapi) "PUT" else "POST"
if(newapi) self$INFO(sprintf("Using new file upload API with bucket: %s", record$links$bucket))
method_url <- if(newapi) sprintf("%s/%s", unlist(strsplit(record$links$bucket, "api/"))[2], URLencode(filename)) else sprintf("deposit/depositions/%s/files", recordId)
zenReq <- if(newapi){
ZenodoRequest$new(
private$url, method, method_url,
data = upload_file(path),
progress = TRUE,
token = self$getToken(),
logger = self$loggerType
)
}else{
ZenodoRequest$new(
private$url, method, method_url,
data = filename, file = upload_file(path),
progress = TRUE,
token = self$getToken(),
logger = self$loggerType
)
}
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 201){
out <- ZenodoRecord$new(obj = zenReq$getResponse())
self$INFO(sprintf("Successful uploaded file to record '%s'", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while uploading file to record '%s': %s", recordId, out$message))
}
return(out)
},
#' @description Deletes a file for a record
#' @param recordId ID of the record
#' @param fileId ID of the file to delete
deleteFile = function(recordId, fileId){
zenReq <- ZenodoRequest$new(private$url, "DELETE", sprintf("deposit/depositions/%s/files", recordId),
data = fileId, token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- FALSE
if(zenReq$getStatus() == 204){
out <- TRUE
self$INFO(sprintf("Successful deleted file from record '%s'", recordId))
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while deleting file from record '%s': %s", recordId, out$message))
}
return(out)
},
#Records
#------------------------------------------------------------------------------------------
#' @description Get the list of Zenodo records. By defaut the list of records will be returned by
#' page with a size of 10 results per page (default size of the Zenodo API). The parameter
#' \code{q} allows to specify an ElasticSearch-compliant query to filter depositions
#' (default query is empty to retrieve all records). The argument \code{all_versions},
#' if set to TRUE allows to get all versions of records as part of the depositions list.
#' The argument \code{exact} specifies that an exact matching is wished, in which case
#' paginated search will be disabled (only the first search page will be returned).
#' Examples of ElasticSearch queries for Zenodo can be found at \href{https://help.zenodo.org/guides/search/}{https://help.zenodo.org/guides/search/}.
#' @param q Elastic-Search-compliant query, as object of class \code{character}. Default is ""
#' @param size number of records to be retrieved per request (paginated). Default is 10
#' @param all_versions object of class \code{logical} indicating if all versions of records have to be retrieved. Default is \code{FALSE}
#' @param exact object of class \code{logical} indicating if exact matching has to be applied. Default is \code{TRUE}
#' @param quiet object of class \code{logical} indicating if logs have to skipped. Default is \code{FALSE}
#' @return a list of \code{ZenodoRecord}
getRecords = function(q = "", size = 10, all_versions = FALSE, exact = FALSE){
page <- 1
req <- sprintf("records/?q=%s&size=%s&page=%s", URLencode(q), size, page)
if(all_versions) req <- paste0(req, "&all_versions=1")
zenReq <- ZenodoRequest$new(private$url, "GET_WITH_CURL", req,
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
out <- NULL
if(zenReq$getStatus() == 200){
resp <- zenReq$getResponse()
hasRecords <- length(resp)>0
while(hasRecords){
out <- c(out, lapply(resp, ZenodoRecord$new))
self$INFO(sprintf("Successfully fetched list of published records - page %s", page))
if(exact){
hasRecords <- FALSE
}else{
#next
page <- page+1
nextreq <- sprintf("records/?q=%s&size=%s&page=%s", URLencode(q), size, page)
if(all_versions) nextreq <- paste0(nextreq, "&all_versions=1")
zenReq <- ZenodoRequest$new(private$url, "GET_WITH_CURL", nextreq,
token = self$getToken(),
logger = self$loggerType)
zenReq$execute()
resp <- zenReq$getResponse()
hasRecords <- length(resp)>0
}
}
self$INFO("Successfully fetched list of published records!")
}else{
out <- zenReq$getResponse()
self$ERROR(sprintf("Error while fetching published records: %s", out$message))
for(error in out$errors){
self$ERROR(sprintf("Error: %s - %s", error$field, error$message))
}
}
return(out)
},
#' @description Get Record by concept DOI
#' @param conceptdoi the concept DOI
#' @return a object of class \code{ZenodoRecord}
getRecordByConceptDOI = function(conceptdoi){
if(regexpr("zenodo", conceptdoi) < 0){
stop(sprintf("DOI '%s' doesn not seem to be a Zenodo DOI", conceptdoi))
}
query <- sprintf("conceptdoi:\"%s\"", conceptdoi)
result <- self$getRecords(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$conceptdoi == conceptdoi){
self$INFO(sprintf("Successfully fetched published record for concept DOI '%s'!", conceptdoi))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No published record for concept DOI '%s'!", conceptdoi))
if(is.null(result)){
#try to get record by id
if( regexpr("zenodo", conceptdoi)>0){
conceptrecid <- unlist(strsplit(conceptdoi, "zenodo."))[2]
self$INFO(sprintf("Try to get published record by Zenodo concept record id '%s'", conceptrecid))
conceptrec <- self$getRecordByConceptId(conceptrecid)
last_doi <- tail(conceptrec$getVersions(),1L)$doi
result <- self$getRecordByDOI(last_doi)
}
}
return(result)
},
#' @description Get Record by DOI
#' @param doi the DOI
#' @return a object of class \code{ZenodoRecord}
getRecordByDOI = function(doi){
if(regexpr("zenodo", doi) < 0){
stop(sprintf("DOI '%s' doesn not seem to be a Zenodo DOI", doi))
}
query <- sprintf("doi:\"%s\"", doi)
result <- self$getRecords(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$doi == doi){
self$INFO(sprintf("Successfully fetched record for DOI '%s'!",doi))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for DOI '%s'!",doi))
if(is.null(result)){
#try to get record by id
if( regexpr("zenodo", doi)>0){
recid <- unlist(strsplit(doi, "zenodo."))[2]
self$INFO(sprintf("Try to get deposition by Zenodo specific record id '%s'", recid))
result <- self$getRecordById(recid)
}
}
return(result)
},
#' @description Get Record by ID
#' @param recid the record ID
#' @return a object of class \code{ZenodoRecord}
getRecordById = function(recid){
query <- sprintf("recid:%s", recid)
result <- self$getRecords(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$id == recid){
self$INFO(sprintf("Successfully fetched record for id '%s'!",recid))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for id '%s'!",recid))
return(result)
},
#' @description Get Record by concept ID
#' @param conceptrecid the concept ID
#' @return a object of class \code{ZenodoRecord}
getRecordByConceptId = function(conceptrecid){
query <- sprintf("conceptrecid:%s", conceptrecid)
result <- self$getRecords(q = query, all_versions = TRUE, exact = TRUE)
if(length(result)>0){
result <- result[[1]]
if(result$conceptrecid == conceptrecid){
self$INFO(sprintf("Successfully fetched record for concept id '%s'!",conceptrecid))
}else{
result <- NULL
}
}else{
result <- NULL
}
if(is.null(result)) self$WARN(sprintf("No record for concept id '%s'!",conceptrecid))
return(result)
}
)
)
| /scratch/gouwar.j/cran-all/cranData/zen4R/R/ZenodoManager.R |
#' ZenodoRecord
#' @docType class
#' @export
#' @keywords zenodo record
#' @return Object of \code{\link{R6Class}} for modelling an ZenodoRecord
#' @format \code{\link{R6Class}} object.
#'
#' @author Emmanuel Blondel <emmanuel.blondel1@@gmail.com>
#'
ZenodoRecord <- R6Class("ZenodoRecord",
inherit = zen4RLogger,
private = list(
allowed_upload_types = c("publication","poster","presentation", "dataset","image","video","software", "lesson", "physicalobject", "other"),
allowed_publication_types = c("annotationcollection", "book","section","conferencepaper","datamanagementplan", "article","patent","preprint",
"deliverable", "milestone", "proposal", "report","softwaredocumentation", "taxonomictreatment", "technicalnote",
"thesis","workingpaper","other"),
allowed_image_types = c("figure","plot","drawing","diagram","photo","other"),
allowed_relations = c("isCitedBy", "cites", "isSupplementTo", "isSupplementedBy", "isContinuedBy", "continues",
"isDescribedBy", "describes", "hasMetadata", "isMetadataFor", "isNewVersionOf", "isPreviousVersionOf",
"isPartOf", "hasPart", "isReferencedBy", "references", "isDocumentedBy", "documents", "isCompiledBy",
"compiles", "isVariantFormOf", "isOriginalFormof", "isIdenticalTo", "isAlternateIdentifier",
"isReviewedBy", "reviews", "isDerivedFrom", "isSourceOf", "requires", "isRequiredBy",
"isObsoletedBy", "obsoletes"),
export_formats = c("BibTeX","CSL","DataCite","DublinCore","DCAT","JSON","JSON-LD","GeoJSON","MARCXML"),
getExportFormatExtension = function(format){
switch(format,
"BibTeX" = "bib",
"CSL" = "json",
"DataCite" ="xml",
"DublinCore" = "xml",
"DCAT" = "rdf",
"JSON" = "json",
"JSON-LD" = "json",
"GeoJSON" = "json",
"MARCXML" = "xml"
)
},
fromList = function(obj){
self$conceptdoi = obj$conceptdoi
self$conceptrecid = obj$conceptrecid
self$created = obj$created
self$doi = obj$doi
self$doi_url = obj$doi_url
self$files = lapply(obj$files, function(file){
list(
filename = if(!is.null(file$filename)) file$filename else file$key,
filesize = if(!is.null(file$filesize)) file$filesize else file$size,
checksum = if(!startsWith(file$checksum, "md5:")) file$checksum else unlist(strsplit(file$checksum, "md5:"))[2],
download = if(!is.null(file$links$download)) file$links$download else file$links$self
)
})
self$id = obj$id
self$links = obj$links
self$metadata = obj$metadata
self$modified = obj$modified
self$owner = obj$owner
self$record_id = obj$record_id
self$state = obj$state
self$submitted = obj$submitted
self$title = obj$title
self$version = obj$version
if(!is.null(obj$stats)) self$stats = data.frame(obj$stats)
}
),
public = list(
#' @field conceptdoi record Concept DOI (common to all record versions)
conceptdoi = NULL,
#' @field conceptrecid record concept id
conceptrecid = NULL,
#' @field created record creation date
created = NULL,
#' @field doi record doi
doi = NULL,
#' @field doi_url record doi URL
doi_url = NULL,
#' @field files list of files associated to the record
files = list(),
#' @field id record id
id = NULL,
#' @field links list of links associated to the record
links = list(),
#' @field metadata metadata elements associated to the record
metadata = list(),
#' @field modified record modification date
modified = NULL,
#' @field owner record owner
owner = NULL,
#' @field record_id record_id
record_id = NULL,
#' @field state record state
state = NULL,
#' @field submitted record submission status
submitted = FALSE,
#' @field title record title
title = NULL,
#' @field version record version
version = NULL,
#' @field stats stats
stats = NULL,
#' @description method is used to instantiate a \code{\link{ZenodoRecord}}
#' @param obj an optional list object to create the record
#' @param logger a logger to print log messages. It can be either NULL, "INFO" (with minimum logs),
#' or "DEBUG" (for complete curl http calls logs)
initialize = function(obj = NULL, logger = "INFO"){
super$initialize(logger = logger)
self$prereserveDOI(TRUE)
if(!is.null(obj)) private$fromList(obj)
},
#' @description Set prereserve_doi if \code{TRUE}, \code{FALSE} otherwise to create a record without
#' prereserved DOI by Zenodo. By default, this method will be called to prereserve a DOI assuming
#' the record created doesn't yet handle a DOI. To avoid prereserving a DOI call \code{$prereserveDOI(FALSE)}
#' on your record.
#' @param prereserve whether a DOI has to be pre-reserved by Zenodo
prereserveDOI = function(prereserve){
if(!is(prereserve,"logical")){
stop("The argument should be 'logical' (TRUE/FALSE)")
}
self$metadata$prereserve_doi <- prereserve
},
#' @description Set the DOI. This method can be used if a DOI has been already assigned outside Zenodo.
#' This method will call the method \code{$prereserveDOI(FALSE)}.
#' @param doi DOI to set for the record
setDOI = function(doi){
self$metadata$doi <- doi
self$prereserveDOI(FALSE)
},
#' @description Get the concept (generic) DOI. The concept DOI is a generic DOI common to all versions
#' of a Zenodo record. When a deposit is unsubmitted, this concept DOI is inherited based
#' on the prereserved DOI of the first record version.
#' @return the concept DOI, object of class \code{character}
getConceptDOI = function(){
conceptdoi <- self$conceptdoi
if(is.null(conceptdoi)){
doi <- self$metadata$prereserve_doi
if(!is.null(doi)) {
doi_parts <- unlist(strsplit(doi$doi, "zenodo."))
conceptdoi <- paste0(doi_parts[1], "zenodo.", self$conceptrecid)
}
}
return(conceptdoi)
},
#' @description Get DOI of the first record version.
#' @return the first DOI, object of class \code{character}
getFirstDOI = function(){
versions <- self$getVersions()
return(versions[1,"doi"])
},
#' @description Get DOI of the latest record version.
#' @return the last DOI, object of class \code{character}
getLastDOI = function(){
versions <- self$getVersions()
return(versions[nrow(versions),"doi"])
},
#' @description Get record versions with creation/publication date,
#' version (ordering number) and DOI.
#' @return a \code{data.frame} with the record versions
getVersions = function(){
record_type <- if(self$state == "done") "record" else if(self$state == "unsubmitted") "deposit"
ref_link <- if(record_type == "record") "latest_html" else if(record_type == "deposit") "latest_draft_html"
zenodo_url <- paste0(unlist(strsplit(self$links[[ref_link]], paste0("/", record_type)))[1],"/api")
zenodo <- ZenodoManager$new(url = zenodo_url)
records <- zenodo$getRecords(q = sprintf("conceptrecid:%s", self$conceptrecid), all_versions = T)
versions <- data.frame(
created = character(0),
date = character(0),
version = character(0),
doi = character(0),
stringsAsFactors = FALSE
)
if(length(records)>0){
versions = do.call("rbind", lapply(records, function(version){
return(data.frame(
created = as.POSIXct(version$created, format = "%Y-%m-%dT%H:%M:%OS"),
date = as.Date(version$metadata$publication_date),
version = if(!is.null(version$metadata$version)) version$metadata$version else NA,
doi = version$doi,
stringsAsFactors = FALSE
))
}))
versions <- versions[order(versions$created),]
row.names(versions) <- 1:nrow(versions)
if(all(is.na(versions$version))) versions$version <- 1:nrow(versions)
}
return(versions)
},
#' @description Get record statistics
#' @return statistics as \code{data.frame}
getStats = function(){
return(self$stats)
},
#' @description Set the upload type (mandatory).
#' @param uploadType record upload type among the following values: 'publication', 'poster',
#' 'presentation', 'dataset', 'image', 'video', 'software', 'lesson', 'physicalobject', 'other'
setUploadType = function(uploadType){
if(!(uploadType %in% private$allowed_upload_types)){
errorMsg <- sprintf("The upload type should be among the values [%s]",
paste(private$allowed_upload_types, collapse=","))
self$ERROR(errorMsg)
stop(errorMsg)
}
self$metadata$upload_type <- uploadType
},
#' @description Set the publication type (mandatory if upload type is 'publication').
#' @param publicationType record publication type among the following values: 'annotationcollection', 'book',
#' 'section', 'conferencepaper', 'datamanagementplan', 'article', 'patent', 'preprint', 'deliverable', 'milestone',
#' 'proposal', 'report', 'softwaredocumentation', 'taxonomictreatment', 'technicalnote', 'thesis', 'workingpaper',
#' 'other'
setPublicationType = function(publicationType){
if(!(publicationType %in% private$allowed_publication_types)){
errorMsg <- sprintf("The publication type should be among the values [%s]",
paste(private$allowed_publication_types, collapse=","))
self$ERROR(errorMsg)
stop(errorMsg)
}
self$setUploadType("publication")
self$metadata$publication_type <- publicationType
},
#' @description Set the image type (mandatory if image type is 'image').
#' @param imageType record publication type among the following values: 'figure','plot',
#' 'drawing','diagram','photo', or 'other'
setImageType = function(imageType){
if(!(imageType %in% private$allowed_image_types)){
errorMsg <- sprintf("The image type should be among the values [%s",
paste(private$allowed_image_types, collapse=","))
self$ERROR(errorMsg)
stop(errorMsg)
}
self$setUploadType("image")
self$metadata$image_type <- imageType
},
#' @description Set the publication date.
#' @param publicationDate object of class \code{Date}
setPublicationDate = function(publicationDate){
if(!is(publicationDate,"Date")){
stop("The publication date should be a 'Date' object")
}
self$metadata$publication_date <- as(publicationDate, "character")
},
#' @description Set the embargo date.
#' @param embargoDate object of class \code{Date}
setEmbargoDate = function(embargoDate){
if(!is(embargoDate,"Date")){
stop("The embargo date should be a 'Date' object")
}
self$metadata$embargo_date <- as(embargoDate, "character")
},
#' @description Set the record title.
#' @param title object of class \code{character}
setTitle = function(title){
self$metadata$title <- title
},
#' @description Set the record description
#' @param description object of class \code{character}
setDescription = function(description){
self$metadata$description <- description
},
#' @description Set the access right.
#' @param accessRight record access right among the following values: 'open','embargoed', 'restricted','closed'
setAccessRight = function(accessRight){
accessRightValues <- c("open","embargoed","restricted","closed")
if(!(accessRight %in% accessRightValues)){
errorMsg <- sprintf("The access right should be among the values [%s",
paste(accessRightValues, collapse=","))
self$ERROR(errorMsg)
stop(errorMsg)
}
self$metadata$access_right <- accessRight
},
#' @description set the access conditions.
#' @param accessConditions object of class \code{character}
setAccessConditions = function(accessConditions){
self$metadata$access_conditions <- accessConditions
},
#' @description Add a creator for the record. One approach is to use the \code{firstname} and
#' \code{lastname} arguments, that by default will be concatenated for Zenodo as
#' \code{lastname, firstname}. For more flexibility over this, the \code{name}
#' argument can be directly used.
#' @param firstname creator first name
#' @param lastname creator last name
#' @param name creator name
#' @param affiliation creator affiliation (optional)
#' @param orcid creator ORCID (optional)
#' @param gnd creator GND (optional)
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addCreator = function(firstname, lastname, name = paste(lastname, firstname, sep = ", "),
affiliation = NULL, orcid = NULL, gnd = NULL){
creator <- list(name = name)
if(!is.null(affiliation)) creator <- c(creator, affiliation = affiliation)
if(!is.null(orcid)) creator <- c(creator, orcid = orcid)
if(!is.null(gnd)) creator <- c(creator, gnd = gnd)
if(is.null(self$metadata$creators)) self$metadata$creators <- list()
self$metadata$creators[[length(self$metadata$creators)+1]] <- creator
},
#' @description Removes a creator by a property. The \code{by} parameter should be the name
#' of the creator property ('name' - in the form 'lastname, firstname', 'affiliation',
#' 'orcid' or 'gnd').
#' @param by property used as criterion to remove the creator
#' @param property property value used to remove the creator
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCreator = function(by,property){
removed <- FALSE
for(i in 1:length(self$metadata$creators)){
creator <- self$metadata$creators[[i]]
if(creator[[by]]==property){
self$metadata$creators[[i]] <- NULL
removed <- TRUE
}
}
return(removed)
},
#' @description Removes a creator by name.
#' @param name creator name
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCreatorByName = function(name){
return(self$removeCreator(by = "name", name))
},
#' @description Removes a creator by affiliation.
#' @param affiliation creator affiliation
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCreatorByAffiliation = function(affiliation){
return(self$removeCreator(by = "affiliation", affiliation))
},
#' @description Removes a creator by ORCID.
#' @param orcid creator ORCID
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCreatorByORCID = function(orcid){
return(self$removeCreator(by = "orcid", orcid))
},
#' @description Removes a creator by GND.
#' @param gnd creator GND
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCreatorByGND = function(gnd){
return(self$removeCreator(by = "gnd", gnd))
},
#' @description Add a contributor for the record. One approach is to use the \code{firstname} and
#' \code{lastname} arguments, that by default will be concatenated for Zenodo as
#' \code{lastname, firstname}. For more flexibility over this, the \code{name}
#' argument can be directly used.
#' @param firstname contributor first name
#' @param lastname contributor last name
#' @param name contributor name
#' @param type contributor type, among values: ContactPerson,
#' DataCollector, DataCurator, DataManager, Distributor, Editor, Funder, HostingInstitution,
#' Producer, ProjectLeader, ProjectManager, ProjectMember, RegistrationAgency, RegistrationAuthority,
#' RelatedPerson, Researcher, ResearchGroup, RightsHolder, Supervisor, Sponsor, WorkPackageLeader, Other.
#' @param affiliation contributor affiliation (optional)
#' @param orcid contributor orcid (optional)
#' @param gnd contributor gnd (optional)
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addContributor = function(firstname, lastname, name = paste(lastname, firstname, sep = ", "),
type, affiliation = NULL, orcid = NULL, gnd = NULL){
allowedTypes <- c("ContactPerson", "DataCollector", "DataCurator", "DataManager","Distributor",
"Editor", "Funder", "HostingInstitution", "Producer", "ProjectLeader", "ProjectManager",
"ProjectMember", "RegistrationAgency", "RegistrationAuthority", "RelatedPerson",
"Researcher", "ResearchGroup", "RightsHolder","Supervisor", "Sponsor", "WorkPackageLeader", "Other")
if(!(type %in% allowedTypes)){
stop(sprintf("The contributor type should be one value among values [%s]",
paste(allowedTypes, collapse=",")))
}
contributor <- list(name = name, type = type)
if(!is.null(affiliation)) contributor <- c(contributor, affiliation = affiliation)
if(!is.null(orcid)) contributor <- c(contributor, orcid = orcid)
if(!is.null(gnd)) contributor <- c(contributor, gnd = gnd)
if(is.null(self$metadata$contributors)) self$metadata$contributors <- list()
self$metadata$contributors[[length(self$metadata$contributors)+1]] <- contributor
},
#' @description Removes a contributor by a property. The \code{by} parameter should be the name
#' of the contributor property ('name' - in the form 'lastname, firstname', 'affiliation',
#' 'orcid' or 'gnd').
#' \code{FALSE} otherwise.
#' @param by property used as criterion to remove the contributor
#' @param property property value used to remove the contributor
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeContributor = function(by,property){
removed <- FALSE
for(i in 1:length(self$metadata$contributors)){
contributor <- self$metadata$contributors[[i]]
if(contributor[[by]]==property){
self$metadata$contributors[[i]] <- NULL
removed <- TRUE
}
}
return(removed)
},
#' @description Removes a contributor by name.
#' @param name contributor name
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeContributorByName = function(name){
return(self$removeContributor(by = "name", name))
},
#' @description Removes a contributor by affiliation.
#' @param affiliation contributor affiliation
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeContributorByAffiliation = function(affiliation){
return(self$removeContributor(by = "affiliation", affiliation))
},
#' @description Removes a contributor by ORCID.
#' @param orcid contributor ORCID
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeContributorByORCID = function(orcid){
return(self$removeContributor(by = "orcid", orcid))
},
#' @description Removes a contributor by GND.
#' @param gnd contributor GND
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeContributorByGND = function(gnd){
return(self$removeContributor(by = "gnd", gnd))
},
#' @description Set license. The license should be set with the Zenodo id of the license. If not
#' recognized by Zenodo, the function will return an error. The list of licenses can
#' fetched with the \code{ZenodoManager} and the function \code{$getLicenses()}.
#' @param licenseId a license Id
#' @param sandbox Use the Zenodo sandbox infrastructure as basis to control available licenses. Default is \code{FALSE}
setLicense = function(licenseId, sandbox = FALSE){
zen <- ZenodoManager$new(sandbox = sandbox)
zen_license <- zen$getLicenseById(licenseId)
if(!is.null(zen_license$status)){
errorMsg <- sprintf("License with id '%s' doesn't exist in Zenodo", licenseId)
self$ERROR(errorMsg)
stop(errorMsg)
}
self$metadata$license <- licenseId
},
#' @description Set record version.
#' @param version the record version to set
setVersion = function(version){
self$metadata$version <- version
},
#' @description Set the language.
#' @param language ISO 639-2 or 639-3 code
setLanguage = function(language){
self$metadata$language <- language
},
#' @description Adds a related identifier with a given relation.
#' @param relation relation type among following values: isCitedBy, cites, isSupplementTo, isSupplementedBy,
#' isContinuedBy, continues, isDescribedBy, describes, hasMetadata, isMetadataFor, isNewVersionOf,
#' isPreviousVersionOf, isPartOf, hasPart, isReferencedBy, references, isDocumentedBy, documents,
#' isCompiledBy, compiles, isVariantFormOf, isOriginalFormof, isIdenticalTo, isAlternateIdentifier,
#' isReviewedBy, reviews, isDerivedFrom, isSourceOf, requires, isRequiredBy, isObsoletedBy, obsoletes
#' @param identifier resource identifier
#' @param resource_type optional resource type, value among possible publication types, image types, or upload
#' types (except 'publication' and 'image' for which a publication/image has to be specified). Default is \code{NULL}
addRelatedIdentifier = function(relation, identifier, resource_type = NULL){
if(!(relation %in% private$allowed_relations)){
stop(sprintf("Relation '%s' incorrect. Use a value among the following [%s]",
relation, paste(private$allowed_relations, collapse=",")))
}
added <- FALSE
if(is.null(self$metadata$related_identifiers)) self$metadata$related_identifiers <- list()
ids_df <- data.frame(relation = character(0), identifier = character(0), stringsAsFactors = FALSE)
if(length(self$metadata$related_identifiers)>0){
ids_df <- do.call("rbind", lapply(self$metadata$related_identifiers, function(x){
data.frame(relation = x$relation, identifier = x$identifier, stringsAsFactors = FALSE)
}))
}
if(nrow(ids_df[ids_df$relation == relation & ids_df$identifier == identifier,])==0){
new_rel <- list(relation = relation, identifier = identifier)
if(!is.null(resource_type)) {
allowed_resource_types <- c(private$allowed_upload_types, private$allowed_publication_types, private$allowed_image_types)
allowed_resource_types <- allowed_resource_types[!(allowed_resource_types %in% c("publication", "image"))]
if(!(resource_type %in% allowed_resource_types)){
stop(sprintf("Relation resource type '%s' incorrect. Use a value among the following [%s]",
relation, paste(allowed_resource_types, collapse=",")))
}
resource_type_prefix <- ""
if(resource_type %in% private$allowed_publication_types)resource_type_prefix = "publication-"
if(resource_type %in% private$allowed_image_types)resource_type_prefix = "image-"
new_rel$resource_type <- paste0(resource_type_prefix, resource_type)
}
self$metadata$related_identifiers[[length(self$metadata$related_identifiers)+1]] <- new_rel
added <- TRUE
}
return(added)
},
#' @description Removes a related identifier with a given relation.
#' @param relation relation type among following values: isCitedBy, cites, isSupplementTo, isSupplementedBy,
#' isContinuedBy, continues, isDescribedBy, describes, hasMetadata, isMetadataFor, isNewVersionOf,
#' isPreviousVersionOf, isPartOf, hasPart, isReferencedBy, references, isDocumentedBy, documents,
#' isCompiledBy, compiles, isVariantFormOf, isOriginalFormof, isIdenticalTo, isAlternateIdentifier,
#' isReviewedBy, reviews, isDerivedFrom, isSourceOf, requires, isRequiredBy, isObsoletedBy, obsoletes
#' @param identifier resource identifier
removeRelatedIdentifier = function(relation, identifier){
if(!(relation %in% private$allowed_relations)){
stop(sprintf("Relation '%s' incorrect. Use a value among the following [%s]",
relation, paste(private$allowed_relations, collapse=",")))
}
removed <- FALSE
if(!is.null(self$metadata$related_identifiers)){
for(i in 1:length(self$metadata$related_identifiers)){
related_id <- self$metadata$related_identifiers[[i]]
if(related_id$relation == relation & related_id$identifier == identifier){
self$metadata$related_identifiers[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Set references
#' @param references a vector or list of references to set for the record
setReferences = function(references){
if(is.null(self$metadata$references)) self$metadata$references <- list()
for(reference in references){
self$addReference(reference)
}
},
#' @description Add a reference
#' @param reference the reference to add
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addReference = function(reference){
added <- FALSE
if(is.null(self$metadata$references)) self$metadata$references <- list()
if(!(reference %in% self$metadata$references)){
self$metadata$references[[length(self$metadata$references)+1]] <- reference
added <- TRUE
}
return(added)
},
#' @description Remove a reference
#' @param reference the reference to remove
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeReference = function(reference){
removed <- FALSE
if(!is.null(self$metadata$references)){
for(i in 1:length(self$metadata$references)){
ref <- self$metadata$references[[i]]
if(ref == reference){
self$metadata$references[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Set keywords
#' @param keywords a vector or list of keywords to set for the record
setKeywords = function(keywords){
if(is.null(self$metadata$keywords)) self$metadata$keywords <- list()
for(keyword in keywords){
self$addKeyword(keyword)
}
},
#' @description Add a keyword
#' @param keyword the keyword to add
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addKeyword = function(keyword){
added <- FALSE
if(is.null(self$metadata$keywords)) self$metadata$keywords <- list()
if(!(keyword %in% self$metadata$keywords)){
self$metadata$keywords[[length(self$metadata$keywords)+1]] <- keyword
added <- TRUE
}
return(added)
},
#' @description Remove a keyword
#' @param keyword the keyword to remove
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeKeyword = function(keyword){
removed <- FALSE
if(!is.null(self$metadata$keywords)){
for(i in 1:length(self$metadata$keywords)){
kwd <- self$metadata$keywords[[i]]
if(kwd == keyword){
self$metadata$keywords[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Adds a subject given a term and identifier
#' @param term subject term
#' @param identifier subject identifier
addSubject = function(term, identifier){
subject <- list(term = term, identifier = identifier)
if(is.null(self$metadata$subjects)) self$metadata$subjects <- list()
self$metadata$subjects[[length(self$metadata$subjects)+1]] <- subject
},
#' @description Removes subject(s) by a property. The \code{by} parameter should be the name
#' of the subject property ('term' or 'identifier').
#' @param by property used as criterion to remove subjects
#' @param property property value used to remove subjects
#' @return \code{TRUE} if at least one subject is removed, \code{FALSE} otherwise.
removeSubject = function(by, property){
removed <- FALSE
for(i in 1:length(self$metadata$subjects)){
subject <- self$metadata$subjects[[i]]
if(subject[[by]]==property){
self$metadata$subjects[[i]] <- NULL
removed <- TRUE
}
}
return(removed)
},
#' @description Removes subject(s) by term.
#' @param term the term to use to remove subject(s)
#' @return \code{TRUE} if at least one subject is removed, \code{FALSE} otherwise.
removeSubjectByTerm = function(term){
return(self$removeSubject(by = "term", property = term))
},
#' @description Removes subject(s) by identifier
#' @param identifier the identifier to use to remove subject(s)
#' @return \code{TRUE} if at least one subject is removed, \code{FALSE} otherwise.
removeSubjectByIdentifier = function(identifier){
return(self$removeSubject(by = "identifier", property = identifier))
},
#' @description Set notes. HTML is not allowed
#' @param notes object of class \code{character}
setNotes = function(notes){
self$metadata$notes <- notes
},
#' @description Set a vector of character strings identifying communities
#' @param communities a vector or list of communities. Values should among known communities. The list of communities can
#' fetched with the \code{ZenodoManager} and the function \code{$getCommunities()}. Each community should be set with
#' the Zenodo id of the community. If not recognized by Zenodo, the function will return an error.
#' @param sandbox Use the Zenodo sandbox infrastructure as basis to control available communities. Default is \code{FALSE}
setCommunities = function(communities, sandbox = FALSE){
if(is.null(self$metadata$communities)) self$metadata$communities <- list()
for(community in communities){
self$addCommunity(community, sandbox = sandbox)
}
},
#' @description Adds a community to the record metadata.
#' @param community community to add. The community should be set with the Zenodo id of the community.
#' If not recognized by Zenodo, the function will return an error. The list of communities can fetched
#' with the \code{ZenodoManager} and the function \code{$getCommunities()}.
#' @param sandbox Use the Zenodo sandbox infrastructure as basis to control available communities. Default is \code{FALSE}
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addCommunity = function(community, sandbox = FALSE){
added <- FALSE
zen <- ZenodoManager$new(sandbox = sandbox)
if(is.null(self$metadata$communities)) self$metadata$communities <- list()
if(!(community %in% sapply(self$metadata$communities, function(x){x$identifier}))){
zen_community <- zen$getCommunityById(community)
if(is.null(zen_community)){
errorMsg <- sprintf("Community with id '%s' doesn't exist in Zenodo", community)
self$ERROR(errorMsg)
stop(errorMsg)
}
self$metadata$communities[[length(self$metadata$communities)+1]] <- list(identifier = community)
added <- TRUE
}
return(added)
},
#' @description Removes a community from the record metadata.
#' @param community community to remove. The community should be set with the Zenodo id of the community.
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeCommunity = function(community){
removed <- FALSE
if(!is.null(self$metadata$communities)){
for(i in 1:length(self$metadata$communities)){
com <- self$metadata$communities[[i]]
if(com == community){
self$metadata$communities[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Set a vector of character strings identifying grants
#' @param grants a vector or list of grants Values should among known grants The list of grants can
#' fetched with the \code{ZenodoManager} and the function \code{$getGrants()}. Each grant should be set with
#' the Zenodo id of the grant If not recognized by Zenodo, the function will raise a warning only.
#' @param sandbox Use the Zenodo sandbox infrastructure as basis to control available grants. Default is \code{FALSE}
setGrants = function(grants, sandbox = FALSE){
if(is.null(self$metadata$grants)) self$metadata$grants <- list()
for(grant in grants){
self$addGrant(grant, sandbox = sandbox)
}
},
#' @description Adds a grant to the record metadata.
#' @param grant grant to add. The grant should be set with the id of the grant. If not
#' recognized by Zenodo, the function will return an warning only. The list of grants can
#' fetched with the \code{ZenodoManager} and the function \code{$getGrants()}.
#' @param sandbox Use the Zenodo sandbox infrastructure as basis to control available grants. Default is \code{FALSE}
#' @return \code{TRUE} if added, \code{FALSE} otherwise
addGrant = function(grant, sandbox = FALSE){
added <- FALSE
zen <- ZenodoManager$new(sandbox = sandbox)
if(is.null(self$metadata$grants)) self$metadata$grants <- list()
if(!(grant %in% self$metadata$grants)){
if(regexpr("::", grant)>0){
zen_grant <- zen$getGrantById(grant)
if(is.null(zen_grant)){
warnMsg <- sprintf("Grant with id '%s' doesn't exist in Zenodo", grant)
self$WARN(warnMsg)
}
}
self$metadata$grants[[length(self$metadata$grants)+1]] <- list(id = grant)
added <- TRUE
}
return(added)
},
#' @description Removes a grant from the record metadata.
#' @param grant grant to remove. The grant should be set with the Zenodo id of the grant
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeGrant = function(grant){
removed <- FALSE
if(!is.null(self$metadata$grants)){
for(i in 1:length(self$metadata$grants)){
grt <- self$metadata$grants[[i]]
if(grt == grant){
self$metadata$grants[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Set Journal title to the record metadata
#' @param title a title, object of class \code{character}
setJournalTitle = function(title){
self$metadata$journal_title <- title
},
#' @description Set Journal volume to the record metadata
#' @param volume a volume
setJournalVolume = function(volume){
self$metadata$journal_volume <- volume
},
#' @description Set Journal issue to the record metadata
#' @param issue an issue
setJournalIssue = function(issue){
self$metadata$journal_issue <- issue
},
#' @description Set Journal pages to the record metadata
#' @param pages number of pages
setJournalPages = function(pages){
self$metadata$journal_pages <- pages
},
#' @description Set conference title to the record metadata
#' @param title conference title, object of class \code{character}
setConferenceTitle = function(title){
self$metadata$conference_title <- title
},
#' @description Set conference acronym to the record metadata
#' @param acronym conference acronym, object of class \code{character}
setConferenceAcronym = function(acronym){
self$metadata$conference_acronym <- acronym
},
#' @description Set conference dates to the record metadata
#' @param dates conference dates, object of class \code{character}
setConferenceDates = function(dates){
self$metadata$conference_dates <- dates
},
#' @description Set conference place to the record metadata
#' @param place conference place, object of class \code{character}
setConferencePlace = function(place){
self$metadata$conference_place <- place
},
#' @description Set conference url to the record metadata
#' @param url conference url, object of class \code{character}
setConferenceUrl = function(url){
self$metadata$conference_url <- url
},
#' @description Set conference session to the record metadata
#' @param session conference session, object of class \code{character}
setConferenceSession = function(session){
self$metadata$conference_session <- session
},
#' @description Set conference session part to the record metadata
#' @param part conference session part, object of class \code{character}
setConferenceSessionPart = function(part){
self$metadata$conference_session_part <- part
},
#' @description Set imprint publisher to the record metadata
#' @param publisher the publisher, object of class \code{character}
setImprintPublisher = function(publisher){
self$metadata$imprint_publisher <- publisher
},
#' @description Set imprint ISBN to the record metadata
#' @param isbn the ISBN, object of class \code{character}
setImprintISBN = function(isbn){
self$metadata$imprint_isbn <- isbn
},
#' @description Set imprint place to the record metadata
#' @param place the place, object of class \code{character}
setImprintPlace = function(place){
self$metadata$imprint_place <- place
},
#' @description Set title to which record is part of
#' @param title the title, object of class \code{character}
setPartofTitle = function(title){
self$metadata$partof_title <- title
},
#' @description Set pages to which record is part of
#' @param pages the pages, object of class \code{character}
setPartofPages = function(pages){
self$metadata$partof_pages <- pages
},
#' @description Set thesis university
#' @param university the university, object of class \code{character}
setThesisUniversity = function(university){
self$metadata_thesis_university <- university
},
#' @description Adds thesis supervisor
#' @param firstname supervisor first name
#' @param lastname supervisor last name
#' @param affiliation supervisor affiliation (optional)
#' @param orcid supervisor ORCID (optional)
#' @param gnd supervisor GND (optional)
addThesisSupervisor = function(firstname, lastname, affiliation = NULL, orcid = NULL, gnd = NULL){
supervisor <- list(name = paste(lastname, firstname, sep=", "))
if(!is.null(affiliation)) supervisor <- c(supervisor, affiliation = affiliation)
if(!is.null(orcid)) supervisor <- c(supervisor, orcid = orcid)
if(!is.null(gnd)) supervisor <- c(supervisor, gnd = gnd)
if(is.null(self$metadata$thesis_supervisors)) self$metadata$thesis_supervisors <- list()
self$metadata$thesis_supervisors[[length(self$metadata$thesis_supervisors)+1]] <- supervisor
},
#' @description Removes a thesis supervisor by a property. The \code{by} parameter should be the name
#' of the thesis supervisor property ('name' - in the form 'lastname, firstname', 'affiliation',
#' 'orcid' or 'gnd').
#' @param by property used as criterion to remove the thesis supervisor
#' @param property property value used to remove the thesis supervisor
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeThesisSupervisor = function(by,property){
removed <- FALSE
for(i in 1:length(self$metadata$thesis_supervisors)){
supervisor <- self$metadata$thesis_supervisors[[i]]
if(supervisor[[by]]==property){
self$metadata$thesis_supervisors[[i]] <- NULL
removed <- TRUE
}
}
return(removed)
},
#' @description Removes a thesis supervisor by name.
#' @param name thesis supervisor name
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeThesisSupervisorByName = function(name){
return(self$removeThesisSupervisor(by = "name", name))
},
#' @description Removes a thesis supervisor by affiliation
#' @param affiliation thesis supervisor affiliation
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeThesisSupervisorByAffiliation = function(affiliation){
return(self$removeThesisSupervisor(by = "affiliation", affiliation))
},
#' @description Removes a thesis supervisor by ORCID
#' @param orcid thesis supervisor ORCID
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeThesisSupervisorByORCID = function(orcid){
return(self$removeThesisSupervisor(by = "orcid", orcid))
},
#' @description Removes a thesis supervisor by GND
#' @param gnd thesis supervisor GND
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeThesisSupervisorByGND = function(gnd){
return(self$removeThesisSupervisor(by = "gnd", gnd))
},
#' @description Adds a location to the record metadata.
#' @param place place (required)
#' @param description description
#' @param lat latitude
#' @param lon longitude
addLocation = function(place, description = NULL, lat = NULL, lon = NULL){
if(is.null(self$metadata$locations)) self$metadata$locations <- list()
self$metadata$locations[[length(self$metadata$locations)+1]] <- list(place = place, description = description, lat = lat, lon = lon)
},
#' @description Removes a grant from the record metadata.
#' @param place place (required)
#' @return \code{TRUE} if removed, \code{FALSE} otherwise
removeLocation = function(place){
removed <- FALSE
if(!is.null(self$metadata$locations)){
for(i in 1:length(self$metadata$locations)){
loc <- self$metadata$locations[[i]]
if(loc$place == place){
self$metadata$locations[[i]] <- NULL
removed <- TRUE
break;
}
}
}
return(removed)
},
#' @description Exports record to a file by format.
#' @param format the export format to use. Possibles values are: BibTeX, CSL, DataCite, DublinCore, DCAT,
#' JSON, JSON-LD, GeoJSON, MARCXML
#' @param filename the target filename (without extension)
#' @param append_format wether format name has to be appended to the filename. Default is \code{TRUE} (for
#' backward compatibility reasons). Set it to \code{FALSE} if you want to use only the \code{filename}.
#' @return the writen file name (with extension)
exportAs = function(format, filename, append_format = TRUE){
zenodo_url <- self$links$record_html
if(is.null(zenodo_url)) zenodo_url <- self$links$latest_html
if(is.null(zenodo_url)){
stop("Ups, this record seems a draft, can't export metadata until it is published!")
}
metadata_export_url <- switch(format,
"BibTeX" = paste0(zenodo_url,"/export/hx"),
"CSL" = paste0(zenodo_url,"/export/csl"),
"DataCite" = paste0(zenodo_url,"/export/dcite4"),
"DublinCore" = paste0(zenodo_url,"/export/xd"),
"DCAT" = paste0(zenodo_url,"/export/dcat"),
"JSON" = paste0(zenodo_url,"/export/json"),
"JSON-LD" = paste0(zenodo_url,"/export/schemaorg_jsonld"),
"GeoJSON" = paste0(zenodo_url,"/export/geojson"),
"MARCXML" = paste0(zenodo_url,"/export/xm"),
NULL
)
if(is.null(metadata_export_url)){
stop(sprintf("Unknown Zenodo metadata export format '%s'. Supported export formats are [%s]", format, paste(private$export_formats, collapse=",")))
}
fileext <- private$getExportFormatExtension(format)
html <- xml2::read_html(metadata_export_url)
reference <- xml2::xml_find_all(html, ".//pre")
reference <- reference[1]
reference <- gsub("<pre.*\">","",reference)
reference <- gsub("</pre>","",reference)
if(fileext %in% c("xml", "rdf")){
reference <- gsub("<", "<", reference)
reference <- gsub(">", ">", reference)
}
destfile <- paste(paste0(filename, ifelse(append_format,paste0("_", format),"")), fileext, sep = ".")
writeChar(reference, destfile, eos = NULL)
return(destfile)
},
#' @description Exports record as BibTeX
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsBibTeX = function(filename){
self$exportAs("BibTeX", filename)
},
#' @description Exports record as CSL
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsCSL = function(filename){
self$exportAs("CSL", filename)
},
#' @description Exports record as DataCite
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsDataCite = function(filename){
self$exportAs("DataCite", filename)
},
#' @description Exports record as DublinCore
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsDublinCore = function(filename){
self$exportAs("DublinCore", filename)
},
#' @description Exports record as DCAT
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsDCAT = function(filename){
self$exportAs("DCAT", filename)
},
#' @description Exports record as JSON
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsJSON = function(filename){
self$exportAs("JSON", filename)
},
#' @description Exports record as JSONLD
#' @param filename the target filename (without extension)
exportAsJSONLD = function(filename){
self$exportAs("JSON-LD", filename)
},
#' @description Exports record as GeoJSON
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsGeoJSON = function(filename){
self$exportAs("GeoJSON", filename)
},
#' @description Exports record as MARCXML
#' @param filename the target filename (without extension)
#' @return the writen file name (with extension)
exportAsMARCXML = function(filename){
self$exportAs("MARCXML", filename)
},
#' @description Exports record in all Zenodo record export formats. This function will
#' create one file per Zenodo metadata formats.
#' @param filename the target filename (without extension)
exportAsAllFormats = function(filename){
invisible(lapply(private$export_formats, self$exportAs, filename))
},
#' @description list files attached to the record
#' @param pretty whether a pretty output (\code{data.frame}) should be returned (default \code{TRUE}), otherwise
#' the raw list of files is returned.
#' @return the files, as \code{data.frame} or \code{list}
listFiles = function(pretty = TRUE){
if(!pretty) return(self$files)
outdf <- do.call("rbind", lapply(self$files, function(x){
return(
data.frame(
filename = x$filename,
filesize = x$filesize,
checksum = x$checksum,
download = x$download,
stringsAsFactors = FALSE
)
)
}))
return(outdf)
},
#' @description Downloads files attached to the record
#' @param path target download path (by default it will be the current working directory)
#' @param files (list of) file(s) to download. If not specified, by default all files will be downloaded.
#' @param parallel whether download has to be done in parallel using the chosen \code{parallel_handler}. Default is \code{FALSE}
#' @param parallel_handler The parallel handler to use eg. \code{mclapply}. To use a different parallel handler (such as eg
#' \code{parLapply} or \code{parSapply}), specify its function in \code{parallel_handler} argument. For cluster-based parallel
#' download, this is the way to proceed. In that case, the cluster should be created earlier by the user with \code{makeCluster}
#' and passed as \code{cl} argument. After downloading all files, the cluster will be stopped automatically.
#' @param cl an optional cluster for cluster-based parallel handlers
#' @param quiet (default is \code{FALSE}) can be set to suppress informative messages (not warnings).
#' @param overwrite (default is \code{TRUE}) can be set to FALSE to avoid re-downloading existing files.
#' @param timeout (default is 60s) see \code{download.file}.
#' @param ... arguments inherited from \code{parallel::mclapply} or the custom \code{parallel_handler}
#' can be added (eg. \code{mc.cores} for \code{mclapply})
#'
#' @note See examples in \code{\link{download_zenodo}} utility function.
#'
downloadFiles = function(path = ".", files = list(),
parallel = FALSE, parallel_handler = NULL, cl = NULL, quiet = FALSE, overwrite=TRUE, timeout=60, ...){
if(length(self$files)==0){
self$WARN(sprintf("No files to download for record '%s' (doi: '%s')",
self$id, self$doi))
}else{
files.list <- self$files
if(!overwrite){
files.list <- files.list[
which(sapply(files.list, function(x){
!file.exists(file.path(path, x$filename))}))
]
}
if(length(files)>0) files.list <- files.list[sapply(files.list, function(x){x$filename %in% files})]
if(length(files.list)==0){
errMsg <- sprintf("No files available in record '%s' (doi: '%s') for file names [%s]",
self$id, self$doi, paste0(files, collapse=","))
self$ERROR(errMsg)
stop(errMsg)
}
for(file in files){
if(!file %in% sapply(files.list, function(x){x$filename})){
self$WARN(sprintf("No files available in record '%s' (doi: '%s') for file name '%s': ",
self$id, self$doi, file))
}
}
files_summary <- sprintf("Will download %s file%s from record '%s' (doi: '%s') - total size: %s",
length(files.list), ifelse(length(files.list)>1,"s",""), self$id, self$doi,
human_filesize(sum(sapply(files.list, function(x){x$filesize}))))
#download_file util
download_file <- function(file){
file$filename <- substring(file$filename, regexpr("/", file$filename)+1, nchar(file$filename))
if (!quiet) cat(sprintf("[zen4R][INFO] Downloading file '%s' - size: %s\n",
file$filename, human_filesize(file$filesize)))
target_file <- file.path(path, file$filename)
timeout_cache <- getOption("timeout")
options(timeout = timeout)
download.file(url = file$download, destfile = target_file,
quiet = quiet, mode = "wb")
options(timeout = timeout_cache)
}
#check_integrity util
check_integrity <- function(file){
file$filename <- substring(file$filename, regexpr("/", file$filename)+1, nchar(file$filename))
target_file <-file.path(path, file$filename)
#check md5sum
target_file_md5sum <- tools::md5sum(target_file)
if(target_file_md5sum==file$checksum){
if (!quiet) cat(sprintf("[zen4R][INFO] File '%s': integrity verified (md5sum: %s)\n",
file$filename, file$checksum))
}else{
warnMsg <- sprintf("[zen4R][WARN] Download issue: md5sum (%s) of file '%s' does not match Zenodo archive md5sum (%s)\n",
target_file_md5sum, tools::file_path_as_absolute(target_file), file$checksum)
cat(warnMsg)
warning(warnMsg)
}
}
if(parallel){
if (!quiet) self$INFO("Download in parallel mode")
if (is.null(parallel_handler)) {
errMsg <- "No 'parallel_handler' specified"
self$ERROR(errMsg)
stop(errMsg)
}
if(!is.null(parallel_handler)){
if(!is.null(cl)){
if (!requireNamespace("parallel", quietly = TRUE)) {
errMsg <- "Package \"parallel\" needed for cluster-based parallel handler. Please install it."
self$ERROR(errMsg)
stop(errMsg)
}
if (!quiet) self$INFO("Using cluster-based parallel handler (cluster 'cl' argument specified)")
if (!quiet) self$INFO(files_summary)
invisible(parallel_handler(cl, files.list, download_file, ...))
try(parallel::stopCluster(cl))
}else{
if (!quiet) self$INFO("Using non cluster-based (no cluster 'cl' argument specified)")
if (!quiet) self$INFO(files_summary)
invisible(parallel_handler(files.list, download_file, ...))
}
}
}else{
if (!quiet) self$INFO("Download in sequential mode")
if (!quiet) self$INFO(files_summary)
invisible(lapply(files.list, download_file))
}
if (!quiet) cat(sprintf("[zen4R][INFO] File%s downloaded at '%s'.\n",
ifelse(length(files.list)>1,"s",""), tools::file_path_as_absolute(path)))
if (!quiet) self$INFO("Verifying file integrity...")
invisible(lapply(files.list, check_integrity))
if (!quiet) self$INFO("End of download")
}
},
#'@description Prints a \link{ZenodoRecord}
#'@param ... any other parameter. Not used
#'@param format format to use for printing. By default, \code{internal} uses an \pkg{zen4R} internal
#' printing method. Other methods available are those supported by Zenodo for record export, and can be used
#' only if the record has already been published (with a DOI). Attemps to print using a Zenodo export format
#' for a record will raise a warning message and revert to "internal" format
#'@param depth an internal depth parameter for indentation of print statements, in case of listing or recursive use of print
print = function(..., format = "internal", depth = 1){
if(format != "internal"){
zenodo_url <- self$links$record_html
if(is.null(zenodo_url)) zenodo_url <- self$links$latest_html
if(is.null(zenodo_url)){
self$WARN(sprintf("Can't print record as '%s' format: record is not published! Use 'internal' printing format ...", format))
method <- "internal"
}
}
switch(format,
"internal" = {
cat(sprintf("<%s>", self$getClassName()))
fields <- rev(names(self))
fields <- fields[!sapply(fields, function(x){
(class(self[[x]])[1] %in% c("environment", "function")) ||
(x %in% c("verbose.info", "verbose.debug", "loggerType"))
})]
for(field in fields){
fieldObj <- self[[field]]
shift <- "...."
if(is(fieldObj, "list")){
if(length(fieldObj)>0){
cat(paste0("\n", paste(rep(shift, depth), collapse=""),"|-- ", field, ": "))
if(!is.null(names(fieldObj))){
#named list
for(fieldObjProp in names(fieldObj)){
item = fieldObj[[fieldObjProp]]
if(is(item, "list")){
if(length(item)>0){
cat(paste0("\n", paste(rep(shift, depth+1), collapse=""),"|-- ", fieldObjProp, ": "))
for(itemObj in names(item)){
cat(paste0("\n",paste(rep(shift, depth+2), collapse=""),"|-- ", itemObj, ": ", item[[itemObj]]))
}
}else{
item <- "<NULL>"
cat(paste0("\n",paste(rep(shift, depth+1), collapse=""),"|-- ", fieldObjProp, ": ", item))
}
}else{
cat(paste0("\n", paste(rep(shift, depth+1), collapse=""),"|-- ", fieldObjProp, ": ", item))
}
}
}else{
#unamed lists (eg. files)
for(i in 1:length(fieldObj)){
item = fieldObj[[i]]
cat(paste0("\n", paste(rep(shift, depth+1), collapse=""), i,"."))
for(itemObj in names(item)){
cat(paste0("\n", paste(rep(shift, depth+1), collapse=""),"|-- ", itemObj, ": ", item[[itemObj]]))
}
}
}
}else{
fieldObj <- "<NULL>"
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", field, ": ", fieldObj))
}
}else if(is(fieldObj, "data.frame")){
if(field == "stats"){
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", field, ":"))
download_cols = colnames(fieldObj)[regexpr("downloads", colnames(fieldObj))>0]
view_cols = colnames(fieldObj)[regexpr("views", colnames(fieldObj))>0]
volume_cols = colnames(fieldObj)[regexpr("volume", colnames(fieldObj))>0]
cols = c(download_cols, view_cols, volume_cols)
for(col in cols){
symbol = ""
if(regexpr("views", col)>0) symbol = "\U0001f441"
if(regexpr("downloads", col)>0) symbol = "\U2193"
if(regexpr("volume", col)>0) symbol = "\U25A0"
cat(paste0("\n",paste(rep(" ", depth), collapse="")," ", utf8::utf8_encode(symbol)," ", col, " = ", fieldObj[,col]))
}
}
}else{
if(is.null(fieldObj)) fieldObj <- "<NULL>"
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", field, ": ", fieldObj))
}
}
},
{
tmp <- tempfile()
export = self$exportAs(format = format, filename = tmp)
cat(suppressWarnings(paste(readLines(export),collapse="\n")))
unlink(tmp)
unlink(export)
}
)
invisible(self)
},
#'@description Maps to an \pkg{atom4R} \link{DCEntry}. Note: applies only to published records.
#'@return an object of class \code{DCEntry}
toDCEntry = function(){
tmp <- tempfile()
dcfile <- self$exportAsDublinCore(filename = tmp)
return(atom4R::DCEntry$new(xml = XML::xmlParse(dcfile)))
}
)
)
| /scratch/gouwar.j/cran-all/cranData/zen4R/R/ZenodoRecord.R |
#' ZenodoRequest
#'
#' @docType class
#' @export
#' @keywords Zenodo Request
#' @return Object of \code{\link{R6Class}} for modelling a generic Zenodo request
#' @format \code{\link{R6Class}} object.
#'
#' @note Abstract class used internally by \pkg{zen4R}
#'
#' @author Emmanuel Blondel <emmanuel.blondel1@@gmail.com>
#'
ZenodoRequest <- R6Class("ZenodoRequest",
inherit = zen4RLogger,
#private methods
private = list(
url = NA,
type = NA,
request = NA,
requestHeaders = NA,
data = NA,
file = NULL,
progress = FALSE,
status = NA,
response = NA,
exception = NA,
result = NA,
token = NULL,
agent = paste0("zen4R_", as(packageVersion("zen4R"),"character")),
prepareData = function(data){
if(is(data, "ZenodoRecord")){
data <- as.list(data)
data[[".__enclos_env__"]] <- NULL
for(prop in names(data)){
if(is(data[[prop]],"function")){
data[[prop]] <- NULL
}
}
if(!is.null(data[["submitted"]])) if(!data[["submitted"]]) data[["submitted"]] <- NULL
if(length(data[["files"]])==0) data[["files"]] <- NULL
if(length(data[["metadata"]])==0) data[["metadata"]] <- NULL
data[["links"]] <- NULL
data[["verbose.info"]] <- NULL
data[["verbose.debug"]] <- NULL
data[["loggerType"]] <- NULL
data <- data[!sapply(data, is.null)]
}else if(is(data, "list")){
meta <- data$metadata
if(!is.null(meta$prereserve_doi)) meta$prereserve_doi <- NULL
data <- list(metadata = meta)
}
data <- as(toJSON(data, pretty=T, auto_unbox=T), "character")
return(data)
},
GET = function(url, request, progress, use_curl = FALSE){
req <- paste(url, request, sep="/")
self$INFO(sprintf("Fetching %s", req))
headers <- c(
"User-Agent" = private$agent,
"Authorization" = paste("Bearer",private$token)
)
responseContent <- NULL
response <- NULL
if(use_curl){
h <- curl::new_handle()
curl::handle_setheaders(h, .list = as.list(headers))
response <- curl::curl_fetch_memory(req, handle = h)
responseContent = jsonlite::parse_json(rawToChar(response$content))
response <- list(
request = request, requestHeaders = rawToChar(response$headers),
status = response$status_code, response = responseContent$hits[[1]]
)
}else{
r <- NULL
if(self$verbose.debug){
r <- with_verbose(GET(req, add_headers(headers), if(progress) httr::progress(type = "up")))
}else{
r <- GET(req, add_headers(headers), if(progress) httr::progress(type = "up"))
}
responseContent <- content(r, type = "application/json", encoding = "UTF-8")
response <- list(request = request, requestHeaders = headers(r),
status = status_code(r), response = responseContent)
}
return(response)
},
POST = function(url, request, data, file = NULL, progress){
req <- paste(url, request, sep="/")
if(!is.null(file)){
contentType <- "multipart/form-data"
data <- list(file = file, filename = data)
}else{
contentType <- "application/json"
data <- private$prepareData(data)
}
#headers
headers <- c(
"User-Agent" = private$agent,
"Content-Type" = contentType,
"Authorization" = paste("Bearer",private$token)
)
#send request
if(self$verbose.debug){
r <- with_verbose(httr::POST(
url = req,
add_headers(headers),
encode = ifelse(is.null(file),"json", "multipart"),
body = data,
if(progress) httr::progress(type = "up")
))
}else{
r <- httr::POST(
url = req,
add_headers(headers),
encode = ifelse(is.null(file),"json", "multipart"),
body = data,
if(progress) httr::progress(type = "up")
)
}
responseContent <- content(r, type = "application/json", encoding = "UTF-8")
response <- list(request = data, requestHeaders = headers(r),
status = status_code(r), response = responseContent)
return(response)
},
PUT = function(url, request, data, progress){
req <- paste(url, request, sep="/")
if(regexpr("api/files", req)<0) data <- private$prepareData(data)
#headers
headers <- c(
"User-Agent" = private$agent,
"Content-Type" = if(regexpr("api/files", req)>0) "application/octet-stream" else "application/json",
"Authorization" = paste("Bearer",private$token)
)
#send request
if(self$verbose.debug){
r <- with_verbose(httr::PUT(
url = req,
add_headers(headers),
body = data,
if(progress) httr::progress(type = "up")
))
}else{
r <- httr::PUT(
url = req,
add_headers(headers),
body = data,
if(progress) httr::progress(type = "up")
)
}
responseContent <- content(r, type = "application/json", encoding = "UTF-8")
response <- list(request = data, requestHeaders = headers(r),
status = status_code(r), response = responseContent)
return(response)
},
DELETE = function(url, request, data){
req <- paste(url, request, data, sep="/")
#headers
headers <- c(
"User-Agent" = private$agent,
"Authorization" = paste("Bearer",private$token)
)
if(self$verbose.debug){
r <- with_verbose(httr::DELETE(
url = req,
add_headers(headers)
))
}else{
r <- httr::DELETE(
url = req,
add_headers(headers)
)
}
responseContent <- content(r, type = "application/json", encoding = "UTF-8")
response <- list(request = data, requestHeaders = headers(r),
status = status_code(r), response = responseContent)
return(response)
}
),
#public methods
public = list(
#' @description Initializes a \code{ZenodoRequest}
#' @param url request URL
#' @param type Type of request: 'GET', 'POST', 'PUT', 'DELETE'
#' @param request the method request
#' @param data payload (optional)
#' @param file to be uploaded (optional)
#' @param progress whether a progress status has to be displayed for download/upload
#' @param token user token
#' @param logger the logger type
#' @param ... any other arg
initialize = function(url, type, request, data = NULL, file = NULL, progress = FALSE,
token, logger = NULL, ...) {
super$initialize(logger = logger)
private$url = url
private$type = type
private$request = request
private$data = data
private$file = file
private$progress = progress
private$token = token
},
#' @description Executes the request
execute = function(){
req <- switch(private$type,
"GET" = private$GET(private$url, private$request, private$progress),
"GET_WITH_CURL" = private$GET(private$url, private$request, private$progress, use_curl = TRUE),
"POST" = private$POST(private$url, private$request, private$data, private$file, private$progress),
"PUT" = private$PUT(private$url, private$request, private$data, private$progress),
"DELETE" = private$DELETE(private$url, private$request, private$data)
)
private$request <- req$request
private$requestHeaders <- req$requestHeaders
private$status <- req$status
private$response <- req$response
if(private$type == "GET"){
if(private$status != 200){
private$exception <- sprintf("Error while executing request '%s'", req$request)
self$ERROR(private$exception)
}
}
},
#'@description Get request
getRequest = function(){
return(private$request)
},
#'@description Get request headers
getRequestHeaders = function(){
return(private$requestHeaders)
},
#'@description Get request status
getStatus = function(){
return(private$status)
},
#'@description Get request response
getResponse = function(){
return(private$response)
},
#'@description Get request exception
getException = function(){
return(private$exception)
},
#'@description Get request result
getResult = function(){
return(private$result)
},
#'@description Set request result
#'@param result result to be set
setResult = function(result){
private$result = result
}
)
) | /scratch/gouwar.j/cran-all/cranData/zen4R/R/ZenodoRequest.R |
.onLoad <- function (libname, pkgname) { # nocov start
} # nocov end
| /scratch/gouwar.j/cran-all/cranData/zen4R/R/profile.R |
#' @name zen4R
#' @aliases zen4R-package
#' @aliases zen4R
#' @docType package
#'
#' @importFrom R6 R6Class
#' @import methods
#' @import httr
#' @import jsonlite
#' @import xml2
#' @import XML
#' @import keyring
#' @importFrom tools file_path_as_absolute
#' @importFrom tools md5sum
#' @import atom4R
#' @importFrom utf8 utf8_encode
#'
#' @title Interface to 'Zenodo' REST API
#' @description Provides an Interface to 'Zenodo' (<https://zenodo.org>) REST API,
#' including management of depositions, attribution of DOIs by 'Zenodo',
#' upload and download of files.
#'
#'@author Emmanuel Blondel \email{emmanuel.blondel1@@gmail.com}
#'
NULL | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R.R |
#' @name download_zenodo
#' @aliases download_zenodo
#' @title download_zenodo
#' @description \code{download_zenodo} allows to download archives attached to a Zenodo
#' record, identified by its DOI or concept DOI.
#'
#' @examples
#' \dontrun{
#' #simple download (sequential)
#' download_zenodo("10.5281/zenodo.2547036")
#'
#' library(parallel)
#' #download files as parallel using a cluster approach (for both Unix/Win systems)
#' download_zenodo("10.5281/zenodo.2547036",
#' parallel = TRUE, parallel_handler = parLapply, cl = makeCluster(2))
#'
#' #download files as parallel using mclapply (for Unix systems)
#' download_zenodo("10.5281/zenodo.2547036",
#' parallel = TRUE, parallel_handler = mclapply, mc.cores = 2)
#' }
#'
#' @param doi a Zenodo DOI or concept DOI
#' @param path the target directory where to download files
#' @param files subset of filenames to restrain to download. If ignored, all files will be downloaded.
#' @param logger a logger to print Zenodo API-related messages. The logger can be either NULL,
#' "INFO" (with minimum logs), or "DEBUG" (for complete curl http calls logs)
#' @param quiet Logical (\code{FALSE} by default).
#' Do you want to suppress informative messages (not warnings)?
#' @param ... any other arguments for parallel downloading (more information at
#'\link{ZenodoRecord}, \code{downloadFiles()} documentation)
#'
#' @export
#'
download_zenodo = function(doi, path = ".", files = list(), logger = NULL, quiet = FALSE, ...){
#rec
rec = get_zenodo(doi = doi, logger = logger)
#download
rec$downloadFiles(path = path, files = files, quiet = quiet, ...)
}
#' Human-readable binary file size
#'
#' Takes an integer (referring to number of bytes) and returns an optimally
#' human-readable
#' \href{https://en.wikipedia.org/wiki/Binary_prefix}{binary-prefixed}
#' byte size (KiB, MiB, GiB, TiB, PiB, EiB).
#' The function is vectorised.
#'
#' @author Floris Vanderhaeghe, \email{floris.vanderhaeghe@@inbo.be}
#'
#' @param x A positive integer, i.e. the number of bytes (B).
#' Can be a vector of file sizes.
#'
#' @return
#' A character vector.
#'
#' @keywords internal
#'
human_filesize <- function(x) {
magnitude <- pmin(floor(log(x, base = 1024)), 8)
unit <- factor(magnitude,
levels = 0:8,
labels = c(
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB")
)
size <- round(x / 1024^magnitude, 1)
return(paste(size, unit))
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_downloader.R |
#' @name export_zenodo
#' @aliases export_zenodo
#' @title export_zenodo
#' @description \code{export_zenodo} allows to export a Zenodo record, identified by its
#' DOI or concept DOI, using one of the export formats supported by Zenodo.
#'
#' @examples
#' \dontrun{
#' export_zenodo("10.5281/zenodo.2547036", filename = "test", format = "BibTeX", append_format = F)
#' }
#'
#' @param doi a Zenodo DOI or concept DOI
#' @param filename a base file name (without file extension) to export to.
#' @param format a valid Zenodo export format among the following: BibTeX, CSL, DataCite, DublinCore,
#' DCAT, JSON, JSON-LD, GeoJSON, MARCXML.
#' @param append_format wether format name has to be appended to the filename. Default is \code{TRUE} (for
#' backward compatibility reasons). Set it to \code{FALSE} if you want to use only the \code{filename}.
#' @param logger a logger to print Zenodo API-related messages. The logger can be either NULL,
#' "INFO" (with minimum logs), or "DEBUG" (for complete curl http calls logs)
#' @return the exported file name (with extension)
#' @export
#'
export_zenodo = function(doi, filename, format, append_format = TRUE, logger = NULL){
#get
rec = get_zenodo(doi = doi, logger = logger)
#download
rec$exportAs(filename = filename, format = format, append_format = append_format)
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_exporter.R |
#' @name get_zenodo
#' @aliases get_zenodo
#' @title get_zenodo
#' @description \code{get_zenodo} allows to get a Zenodo record, identified by
#' its DOI or concept DOI.
#'
#' @examples
#' \dontrun{
#' get_zenodo("10.5281/zenodo.2547036")
#' }
#'
#' @param doi a Zenodo DOI or concept DOI
#' @param logger a logger to print messages. The logger can be either NULL,
#' "INFO" (with minimum logs), or "DEBUG" (for complete curl http calls logs)
#' @return an object of class \code{data.frame} giving the record versions
#' including date, version number and version-specific DOI.
#' @return object of class \code{ZenodoRecord}
#'
#' @export
#'
get_zenodo = function(doi, logger = NULL){
zenodo <- suppressWarnings(ZenodoManager$new(logger = logger))
rec <- zenodo$getRecordByDOI(doi)
if(is.null(rec)){
#try to get it as concept DOI
rec <- zenodo$getRecordByConceptDOI(doi)
if(is.null(rec)){
stop("The DOI specified doesn't match any existing Zenodo DOI or concept DOI")
}
}
return(rec)
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_getter.R |
#' @name get_licenses
#' @aliases get_licenses
#' @title get_licenses
#' @description \code{get_licenses} allows to list all licenses supported by Zenodo.
#'
#' @examples
#' \dontrun{
#' get_licenses(pretty = TRUE)
#' }
#'
#' @param pretty output delivered as \code{data.frame}
#' @return the licenses as \code{list} or \code{data.frame}
#' @export
#'
get_licenses <- function(pretty = TRUE){
zenodo = ZenodoManager$new()
return(zenodo$getLicenses(pretty = pretty))
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_licenses.R |
#' zen4RLogger
#'
#' @docType class
#' @export
#' @keywords logger
#' @return Object of \code{\link{R6Class}} for modelling a simple logger
#' @format \code{\link{R6Class}} object.
#'
#' @note Logger class used internally by zen4R
#'
zen4RLogger <- R6Class("zen4RLogger",
public = list(
#' @field verbose.info logger info status
verbose.info = FALSE,
#' @field verbose.debug logger debug status
verbose.debug = FALSE,
#' @field loggerType Logger type, either "INFO", "DEBUG" or NULL (if no logger)
loggerType = NULL,
#' @description internal logger function for the Zenodo manager
#' @param type logger message type, "INFO", "WARN", or "ERROR"
#' @param text log message
logger = function(type, text){
if(self$verbose.info){
cat(sprintf("[zen4R][%s] %s - %s \n", type, self$getClassName(), text))
}
},
#' @description internal INFO logger function
#' @param text log message
INFO = function(text){self$logger("INFO", text)},
#' @description internal WARN logger function
#' @param text log message
WARN = function(text){self$logger("WARN", text)},
#' @description internal ERROR logger function
#' @param text log message
ERROR = function(text){self$logger("ERROR", text)},
#' @description initialize the Zenodo logger
#' @param logger logger type NULL, 'INFO', or 'DEBUG'
initialize = function(logger = NULL){
#logger
if(!missing(logger)){
if(!is.null(logger)){
self$loggerType <- toupper(logger)
if(!(self$loggerType %in% c("INFO","DEBUG"))){
stop(sprintf("Unknown logger type '%s", logger))
}
if(self$loggerType == "INFO"){
self$verbose.info = TRUE
}else if(self$loggerType == "DEBUG"){
self$verbose.info = TRUE
self$verbose.debug = TRUE
}
}
}
},
#'@description Get object class name
#'@return the class name, object of class \code{character}
getClassName = function(){
return(class(self)[1])
},
#'@description Get object class
#'@return the class, object of class \code{R6}
getClass = function(){
class <- eval(parse(text=self$getClassName()))
return(class)
}
)
) | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_logger.R |
#' zenodo_pat
#' @description Get Zenodo personal access token, looking in env var `ZENODO_PAT`
#' @param quiet Hide log message, default is \code{TRUE}
zenodo_pat <- function(quiet = TRUE) {
pat <- Sys.getenv("ZENODO_PAT")
if (nzchar(pat)) {
if (!quiet) {
message("Using Zenodo personal access token (PAT) from environment variable 'ZENODO_PAT'\n")
}
return(pat)
}
NULL
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_pat.R |
#' @name get_versions
#' @aliases get_versions
#' @title get_versions
#' @description \code{get_versions} allows to execute a workflow
#'
#' @examples
#' \dontrun{
#' get_versions("10.5281/zenodo.2547036")
#' }
#'
#' @param doi a Zenodo DOI or concept DOI
#' @param logger a logger to print messages. The logger can be either NULL,
#' "INFO" (with minimum logs), or "DEBUG" (for complete curl http calls logs)
#' @return an object of class \code{data.frame} giving the record versions
#' including date, version number and version-specific DOI.
#'
#' @export
#'
get_versions = function(doi, logger = NULL){
#get
rec = get_zenodo(doi = doi, logger = logger)
#versions
versions <- rec$getVersions()
return(versions)
} | /scratch/gouwar.j/cran-all/cranData/zen4R/R/zen4R_versioning.R |
## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)
| /scratch/gouwar.j/cran-all/cranData/zen4R/inst/doc/zen4R.R |
---
title: zen4R User Manual
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zen4R User Manual}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# zen4R - R Interface to Zenodo REST API
[](https://doi.org/10.5281/zenodo.2547036)
Provides an Interface to [Zenodo](https://zenodo.org) REST API, including management of depositions, attribution of DOIs by 'Zenodo' and upload of files.
***
For zen4R sponsoring/funding new developments, enhancements, support requests, please contact me by [e-mail](mailto:[email protected])
Many thanks to the following organizations that have provided fundings for strenghtening the ``zen4R`` package:
<div style="float:left;">
<a href="https://www.fao.org/home/en/"><img height=200 width=200 src="https://www.fao.org/fileadmin/templates/family-farming-decade/images/FAO-IFAD-Logos/FAO-Logo-EN.svg">
<a href="https://en.ird.fr/"><img src="https://en.ird.fr/sites/ird_fr/files/2019-08/logo_IRD_2016_BLOC_UK_COUL.png" height=200 width=200/></a>
</div>
The following projects have contributed to strenghten ``zen4R``:
<a href="https://blue-cloud.org/"><img height=100 width=300 src="https://www.blue-cloud.org/sites/all/themes/arcadia/logo.png"/></a>
_Blue-Cloud has received funding from the European Union's Horizon programme call BG-07-2019-2020, topic: [A] 2019 - Blue Cloud services, Grant Agreement No.862409._
***
**Table of contents**
[**1. Overview**](#package_overview)<br/>
[**2. Package status**](#package_status)<br/>
[**3. Credits**](#package_credits)<br/>
[**4. User guide**](#user_guide)<br/>
[4.1 Installation](#install_guide)<br/>
[4.2 Connect to Zenodo REST API](#ZenodoManager)<br/>
[4.3 Query Zenodo deposited records](#ZenodoDeposit-query)<br/>
[4.3.1 Get Depositions](#ZenodoDeposit-getdepositions)<br/>
[4.3.2 Get Deposition By Concept DOI](#ZenodoDeposit-getdepositionbyconceptdoi)<br/>
[4.3.3 Get Deposition By DOI](#ZenodoDeposit-getdepositionbydoi)<br/>
[4.3.4 Get Deposition By Zenodo record ID](#ZenodoDeposit-getdepositionbyid)<br/>
[4.3.5 Get Deposition versions](#ZenodoDeposit-getversions)<br/>
[4.4 Manage Zenodo record depositions](#ZenodoDeposit)<br/>
[4.4.1 Create an empty record](#ZenodoDeposit-emptyRecord)<br/>
[4.4.2 Fill a record](#ZenodoDeposit-fill)<br/>
[4.4.3 Deposit/Update a record](#ZenodoDeposit-deposit)<br/>
[4.4.4 Delete a record](#ZenodoDeposit-delete)<br/>
[4.4.5 Publish a record](#ZenodoDeposit-publish)<br/>
[4.4.6 Edit/Update a published record](#ZenodoDeposit-edit)<br/>
[4.4.7 Discard changes of a draft record](#ZenodoDeposit-discard)<br/>
[4.4.8 Create a new record version](#ZenodoDeposit-version)<br/>
[4.5 Manage Zenodo record deposition files](#ZenodoDepositFile)<br/>
[4.5.1 Upload file](#ZenodoDepositFile-upload)<br/>
[4.5.2 Get files](#ZenodoDepositFile-get)<br/>
[4.5.3 Delete file](#ZenodoDepositFile-delete)<br/>
[4.6 Export Zenodo record metadata](#ZenodoDepositMetadata)<br/>
[4.6.1 Export Zenodo record metadata by format](#ZenodoDepositMetadata-byformat)<br/>
[4.6.2 Export Zenodo record metadata - all formats](#ZenodoDepositMetadata-allformats)<br/>
[4.7 Browse Zenodo controlled vocabularies](#ZenodoVocabularies)<br/>
[4.7.1 Communities](#ZenodoVocabularies-communities)<br/>
[4.7.2 Licenses](#ZenodoVocabularies-licenses)<br/>
[4.7.3 Funders](#ZenodoVocabularies-funders)<br/>
[4.7.4 Grants](#ZenodoVocabularies-grants)<br/>
[4.8 Query Zenodo published records](#ZenodoRecord-query)<br/>
[4.8.1 Get Records](#ZenodoRecord-getrecords)<br/>
[4.8.2 Get Record By Concept DOI](#ZenodoRecord-getrecordbyconceptdoi)<br/>
[4.8.3 Get Record By DOI](#ZenodoRecord-getrecordbydoi)<br/>
[4.8.4 Get Record By ID](#ZenodoRecord-getrecordbyid)<br/>
[4.9 Download files from Zenodo records](#ZenodoRecord-download)<br/>
[**5. Issue reporting**](#package_issues)<br/>
<a name="package_overview"/>
### 1. Overview and vision
***
The [zen4R](https://doi.org/10.5281/zenodo.2547036) package offers an R interface to the [Zenodo](https://zenodo.org) e-infrastructure. It supports the creation of metadata records (including versioning), upload of files, and assignment of Digital Object Identifier(s) (DOIs).
[zen4R](https://doi.org/10.5281/zenodo.2547036) is jointly developed together with the [geoflow](https://github.com/r-geoflow/geoflow) which intends to facilitate and automate the production of geographic metadata documents and their associated datasources, where [zen4R](https://doi.org/10.5281/zenodo.2547036) is used to assign DOIs and cross-reference these DOIs in other metadata documents such as geographic metadata (ISO 19115/19139) hosted in metadata catalogues and open data portals.
<a name="package_status"/>
### 2. Development status
***
* January 2019: Inception. Code source managed on GitHub.
* June 2019: Published on CRAN.
<a name="package_credits"/>
### 3. Credits
***
(c) 2019, Emmanuel Blondel
Package distributed under MIT license.
If you use ``zen4R``, I would be very grateful if you can add a citation in your published work. By citing ``zen4R``, beyond acknowledging the work, you contribute to make it more visible and guarantee its growing and sustainability. For citation, please use the DOI: [](https://doi.org/10.5281/zenodo.2547036)
<a name="user_guide"/>
### 4. User guide
***
<a name="install_guide"/>
#### 4.1 How to install zen4R in R
For now, the package can be installed from Github
```R
install.packages("remotes")
```
Once the remotes package loaded, you can use the install_github to install ``zen4R``. By default, package will be installed from ``master`` which is the current version in development (likely to be unstable).
```R
require("remotes")
install_github("eblondel/zen4R")
```
For Linux/OSX, make sure to install the `sodium` package as follows:
```
sudo apt-get install -y libsodium-dev
```
<a name="ZenodoManager"/>
#### 4.2 Connect to Zenodo REST API
The main entry point of ``zen4R`` is the ``ZenodoManager``. Some basic methods, such as listing licenses known by Zenodo, do not require the token.
```R
zenodo <- ZenodoManager$new()
```
To use deposit functions of ``zen4R``, you will need to specify the ``token``. This token can be created [here]( https://zenodo.org/account/settings/applications/tokens/new/).
```R
zenodo <- ZenodoManager$new(
token = <your_token>,
logger = "INFO" # use "DEBUG" to see detailed API operation logs, use NULL if you don't want logs at all
)
```
By default, the ``zen4R`` **logger** is deactivated. To enable the logger, specify the level of log you wish as parameter of the above R code. Two logging levels are available:
* ``INFO``: will print the ``zen4R`` logs. Three types of messages can be distinguished: ``INFO``, ``WARN``, ``ERROR``. The latter is generally associated with a ``stop`` and indicate an blocking error for the R method executed.
* ``DEBUG`` will print the above ``zen4R`` logs, and report all logs from HTTP requests performed with ``cURL``
If you want to use the [Zenodo sandbox](https://sandbox.zenodo.org) to test record management before going with the production Zenodo e-infrastructure, you can specify the Zenodo sandbox URL (https://sandbox.zenodo.org/api) in the ``ZenodoManager``.
**Important: To use the Zenodo sandbox, you need to set up a sandbox account separately from Zenodo, create a separate personal access token to the sandbox API, and you must confirm via the confirmation link this account separately in order to be able to test your record management on this clone of Zenodo.**
The below code instructs how to connect to the Sandbox Zenodo e-infrastructure:
```R
zenodo <- ZenodoManager$new(
url = "https://sandbox.zenodo.org/api",
token = <your_zenodo_sandbox_token>,
logger = "INFO"
)
```
<a name="ZenodoDeposit-query"/>
#### 4.3 Query Zenodo deposited records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers several methods to query Zenodo depositions.
<a name="ZenodoDeposit-query-getdepositions"/>
##### 4.3.1 Get Depositions
The generic way to query depositions is to use the method ``getDepositions``. If specified with no parameter, all depositions will be returned:
```
my_zenodo_records <- zenodo$getDepositions()
```
It is also possible to specify an ElasticSearch query using the ``q`` parameter. For helpers and query examples, please consult this [Zenodo Search guide](https://help.zenodo.org/guides/search/).
Since the Zenodo API is paginated, an extra parameter ``size`` can be specified to indicate the number of records to be queried by page (default value is 10).
By default, the Zenodo API will return only the latest versions of a record. It is possible to retrieve all versions of records by specifying ``all_versions = FALSE``.
<a name="ZenodoDeposit-query-getdepositionbyconceptdoi"/>
##### 4.3.2 Get Deposition By Concept DOI
It is possible to interrogate and get a Zenodo record with its concept DOI (generic DOI common to all versions of a record):
```
my_rec <- zenodo$getDepositionByConceptDOI("<my_concept_doi>")
```
<a name="ZenodoDeposit-query-getdepositionbydoi"/>
##### 4.3.3 Get Deposition By DOI
It is possible to interrogate and get a Zenodo record with its DOI (record version-specific DOI):
```
my_rec <- zenodo$getDepositionByDOI("<my_doi>")
```
<a name="ZenodoDeposit-query-getdepositionbyid"/>
##### 4.3.4 Get Deposition By Zenodo ID
It is possible to interrogate and get a Zenodo record with its internal ID:
```
my_rec <- zenodo$getDepositionById(id)
```
<a name="ZenodoDeposit-getversions"/>
##### 4.3.4 Get versions of a Zenodo record
For a given record, it's possible to get the list of versions of this record:
```
my_rec <- zenodo$getDepositionByConceptDOI("<some_concept_doi>")
my_rec$getVersions()
```
The list of versions is provided as ``data.frame`` given the date of publication, version number, and DOI of each version.
> Note: This function is not provided through the Zenodo API, but exploits to Zenodo website and has been added to [zen4R](https://doi.org/10.5281/zenodo.2547036) to facilitate the browsing of record versions.
<a name="ZenodoDeposit"/>
#### 4.4 Manage Zenodo record depositions
<a name="ZenodoDeposit-emptyRecord"/>
##### 4.4.1 Create an empty record
It is possible to create and deposit an empty record, ready for editing. For that, run the following R code:
```r
myrec <- zenodo$createEmptyRecord()
```
This method will return an object of class ``ZenodoRecord`` for which an internal ``id`` and a DOI have been pre-defined by Zenodo. An alternate method is to create a local empty record (not deposited on Zenodo) doing:
```r
myrec <- ZenodoRecord$new()
```
The next section explains how to fill the record with metadata elements.
<a name="ZenodoDeposit-fill"/>
##### 4.4.2 Fill a record
Zenodo records can be described a set of multiple metadata elements. For a full documentation of these metadata elements, please consult the zen4R documentation with ``?ZenodoRecord``. The online Zenodo API documentation can be consulted as well [here](https://developers.zenodo.org/#representation).
Example of record filling with metadata elements:
```r
myrec <- ZenodoRecord$new()
myrec$setTitle("my R package")
myrec$setDescription("A description of my R package")
myrec$setUploadType("software")
myrec$addCreator(firstname = "John", lastname = "Doe", affiliation = "Independent", orcid = "0000-0000-0000-0000")
myrec$setLicense("mit")
myrec$setAccessRight("open")
myrec$setDOI("mydoi") #use this method if your DOI has been assigned elsewhere, outside Zenodo
myrec$addCommunity("ecfunded")
```
<a name="ZenodoDeposit-deposit"/>
##### 4.4.3 Deposit/update a record
Once the record is edited/updated, you can deposit it on Zenodo with the following code:
```r
myrec <- zenodo$depositRecord(myrec)
```
In order to apply further methods on this record (e.g. upload a file, publish/delete a record), you need to get the output of the function ``depositRecord`` (see example above) since after the deposition Zenodo will return the record that now contains an internal ``id`` required to identify and apply further actions. This id can be inspected with ``myrec$id``.
Instead, if you don't get the output of ``depositRecord`` and try to upload files or publish/delete the record based on the local record you handle (built upon ``ZenodoRecord$new()``), this will not work. Because it is a local record, the ``id`` of the record will still be ``NULL``, with no value assigned by Zenodo, and Zenodo will be unable to identify which record needs to be handled.
<a name="ZenodoDeposit-delete"/>
##### 4.4.4 Delete a record
A record deposited on Zenodo but not yet published remains in the [Upload](https://zenodo.org/deposit) area of Zenodo (a kind of staging area where draft records are in edition). As long as it is not published, a record can be deleted from the Zenodo [Upload](https://zenodo.org/deposit) area using:
```r
zenodo$deleteRecord(myrec$id)
```
<a name="ZenodoDeposit-publish"/>
##### 4.4.5 Publish a record
To publish a deposited record and make it available publicly online on Zenodo, the following method can be run:
```r
myrec <- zenodo$publishRecord(myrec$id)
```
A shortcut to publish a record is also available through the method ``depositRecord``, specifying ``publish = TRUE``. This method should be used with cautious giving the fact the record will go straight online on Zenodo if published. By default the parameter ``publish`` will be set to ``FALSE``:
```r
myrec <- zenodo$depositRecord(myrec, publish = TRUE)
```
The publication of a record requires at least to have uploaded at least one file for this record. See section [4.4.1 Upload file](https://github.com/eblondel/zen4R/wiki#44-manage-zenodo-record-deposition-files).
<a name="ZenodoDeposit-edit"/>
##### 4.4.6 Edit/Update a published record
It is possible to update metadata of a published record, but not to modify the files associated to it. In order to update metadata of a published record, the ``state`` of this record has to be modified to make it editable. For that, use the ``editRecord`` function giving the ``id`` of the record to edit:
```
myrec <- zenodo$editRecord(myrec$id)
```
Next, perform your metadata updates, and re-deposit the record
```
myrec$setTitle("newtitle")
myrec <- zenodo$depositRecord(myrec, publish = FALSE)
```
Since the record has been switched back to ``draft`` state, the record has to be re-published otherwise it will remain a draft record in your Zenodo user session.
<a name="ZenodoDeposit-discard"/>
##### 4.4.7 Discard changes of a draft record
In case you started editing a record and you want to discard changes on it, it is possible to do it with the ``discardChanges``.
```
zenodo$discardChanges(myrec$id)
```
<a name="ZenodoDeposit-version"/>
##### 4.4.8 Create a new version record
To create a new record version, you should first retrieve the record for which you want to create a new version. You can retrieve this record with methods based on DOI such as ``getDepositionByConceptDOI`` (to get a record based on concept DOI) or ``getDepositionByDOI``; or by Zenodo ``id`` with ``getDepositionById`` :
```r
#get record by DOI
myrec <- zenodo$getDepositionByDOI("<some doi>")
#edit myrec with updated metadata for the new version
#...
#create new version
myrec <- zenodo$depositRecordVersion(myrec, delete_latest_files = TRUE, files = "newversion.csv", publish = FALSE)
```
The function ``depositRecordVersion`` will create a new version for the published record. The parameter ``delete_latest_files`` (default = ``TRUE``) allows to delete latest files (knowing that a new record version expect to have different file(s) than the latest version). The ``files`` parameter allows to list the files to be uploaded. As for the ``depositRecord``, it is possible to publish the record with the ``publish`` paramater.
<a name="ZenodoDepositFile"/>
#### 4.5 Manage Zenodo record deposition files
<a name="ZenodoDepositFile-upload"/>
##### 4.5.1 Upload file
With ``zen4R``, it is very easy to upload a file to a record deposition. The record should first deposited on Zenodo. To upload a file, the following single line can be used, where the file ``path`` is specified and the record deposit to which the file should be uploaded:
```r
zenodo$uploadFile("path/to/your/file", record = myrec)
```
<a name="ZenodoDepositFile-get"/>
##### 4.5.2 Get files
To get the list of files attached to a record, you can specify the following method adding the record ``id``:
```r
zen_files <- zenodo$getFiles(myrec$id)
```
This retrieves a list of files. Each file has a unique ``id``, that can be used to for file deletion.
<a name="ZenodoDepositFile-delete"/>
##### 4.5.3 Delete file
The following example shows how to delete the first file attached to the record defined earlier. To delete a file, we need to specify both the record and file identifiers:
```r
zenodo$deleteFile(myrec$id, zen_files[[1]]$id)
```
<a name="ZenodoDepositMetadata"/>
#### 4.6 Export Zenodo record metadata
For a given Zenodo record, [zen4R](https://doi.org/10.5281/zenodo.2547036) let you export the metadata in a metadata file, with a series of ``exportAs*`` methods.
The metadata formats supported are: ``BibTeX``, ``CSL``, ``DataCite``, ``DublinCore``, ``DCAT``, ``JSON``, ``JSON-LD``, ``GeoJSON``, ``MARCXML``
<a name="ZenodoDepositMetadata-byformat"/>
##### 4.6.1 Export Zenodo record metadata by format
To export a record in a given format, they are two ways:
```
#using the generic exportAs
myrec$exportAs("BibTeX", filename = "myfilename")
#using the format-specific wrapper
myrec$exportAsBibTeX(filename = "myfilename")
```
The ``filename`` provided should not include the file extension that is managed by zen4R, depending on the chosen format.
<a name="ZenodoDepositMetadata-allformats"/>
##### 4.6.2 Export Zenodo record metadata - all formats
To export a record in all above metadata formats:
```
myrec$exportAsAllFormats(filename = "myfilename")
```
The ``filename`` provided should not include the file extension that is managed by zen4R, depending on the format.
<a name="ZenodoVocabularies"/>
#### 4.7 Browse Zenodo controlled vocabularies
<a name="ZenodoVocabularies-communities"/>
##### 4.7.1 Communities
```
communities <- zenodo$getCommunities()
```
<a name="ZenodoVocabularies-licenses"/>
##### 4.7.2 Licenses
```
licenses <- zenodo$getLicenses()
```
<a name="ZenodoVocabularies-funders"/>
##### 4.7.3 Funders
```
funders <- zenodo$getFunders()
```
<a name="ZenodoVocabularies-grants"/>
##### 4.7.4 Grants
```
grants <- zenodo$getGrants()
```
<a name="ZenodoRecord-query"/>
#### 4.8 Query Zenodo published records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers several methods to query Zenodo records.
<a name="ZenodoRecord-getrecords"/>
##### 4.8.1 Get Records
The generic way to query records is to use the method ``getRecords``
```
my_zenodo_records <- zenodo$getRecords(q = "<my_elastic_search_query>")
```
The ``q`` parameter should be an ElasticSearch query. For helpers and query examples, please consult this [Zenodo Search guide](https://help.zenodo.org/guides/search/).
Since the Zenodo API is paginated, an extra parameter ``size`` can be specified to indicate the number of records to be queried by page (default value is 10).
By default, the Zenodo API will return only the latest versions of a record. It is possible to retrieve all versions of records by specifying ``all_versions = FALSE``.
<a name="ZenodoRecord-getrecordbyconceptdoi"/>
##### 4.8.2 Get Record By Concept DOI
It is possible to interrogate and get a Zenodo record with its concept DOI (generic DOI common to all versions of a record):
```
my_rec <- zenodo$getRecordByConceptDOI("<my_concept_doi>")
```
<a name="ZenodoRecord-getrecordbydoi"/>
##### 4.8.3 Get Record By DOI
It is possible to interrogate and get a Zenodo record with its DOI (record version-specific DOI):
```
my_rec <- zenodo$getRecordByDOI("<my_doi>")
```
<a name="ZenodoRecord-getrecordbyid"/>
##### 4.8.4 Get Record By Zenodo ID
It is possible to interrogate and get a Zenodo record with its internal ID:
```
my_rec <- zenodo$getRecordById(id)
```
<a name="ZenodoRecord-download"/>
#### 4.9 Download files from Zenodo records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers methods to download files Zenodo published records.
Being published records, the latter and their files are accessible without any user token using `zenodo <- ZenodoManager$new(logger = "INFO")`. Files can be then downloaded either from a Zenodo `record` object (fetched with `getRecordByDOI`):
```r
rec <- zenodo$getRecordByDOI("10.5281/zenodo.3378733")
files <- rec$listFiles(pretty = TRUE)
#create a folder where to download my files
dir.create("download_zenodo")
#download files
rec$downloadFiles(path = "download_zenodo")
downloaded_files <- list.files("download_zenodo")
```
or using the shortcut function `download_zenodo`:
```r
#create a folder where to download my files
dir.create("download_zenodo")
#download files with shortcut function 'download_zenodo'
download_zenodo(path = "download_zenodo", "10.5281/zenodo.3378733")
downloaded_files <- list.files("download_zenodo")
```
Download can be also be done in parallel with `parallel` package, depending on the plateform. See below examples:
* For both Unix/Win OS (using clusters)
```r
library(parallel)
#download files as parallel using a cluster approach (for both Unix/Win systems)
download_zenodo("10.5281/zenodo.2547036", parallel = TRUE, parallel_handler = parLapply, cl = makeCluster(2))
```
* For Unix OS (using `mclapply `)
```r
#download files as parallel using mclapply (for Unix systems)
download_zenodo("10.5281/zenodo.2547036", parallel = TRUE, parallel_handler = mclapply, mc.cores = 2)
```
<a name="package_issues"/>
### 5. Issue reporting
***
Issues can be reported at https://github.com/eblondel/zen4R/issues
| /scratch/gouwar.j/cran-all/cranData/zen4R/inst/doc/zen4R.Rmd |
---
title: zen4R User Manual
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zen4R User Manual}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# zen4R - R Interface to Zenodo REST API
[](https://doi.org/10.5281/zenodo.2547036)
Provides an Interface to [Zenodo](https://zenodo.org) REST API, including management of depositions, attribution of DOIs by 'Zenodo' and upload of files.
***
For zen4R sponsoring/funding new developments, enhancements, support requests, please contact me by [e-mail](mailto:[email protected])
Many thanks to the following organizations that have provided fundings for strenghtening the ``zen4R`` package:
<div style="float:left;">
<a href="https://www.fao.org/home/en/"><img height=200 width=200 src="https://www.fao.org/fileadmin/templates/family-farming-decade/images/FAO-IFAD-Logos/FAO-Logo-EN.svg">
<a href="https://en.ird.fr/"><img src="https://en.ird.fr/sites/ird_fr/files/2019-08/logo_IRD_2016_BLOC_UK_COUL.png" height=200 width=200/></a>
</div>
The following projects have contributed to strenghten ``zen4R``:
<a href="https://blue-cloud.org/"><img height=100 width=300 src="https://www.blue-cloud.org/sites/all/themes/arcadia/logo.png"/></a>
_Blue-Cloud has received funding from the European Union's Horizon programme call BG-07-2019-2020, topic: [A] 2019 - Blue Cloud services, Grant Agreement No.862409._
***
**Table of contents**
[**1. Overview**](#package_overview)<br/>
[**2. Package status**](#package_status)<br/>
[**3. Credits**](#package_credits)<br/>
[**4. User guide**](#user_guide)<br/>
[4.1 Installation](#install_guide)<br/>
[4.2 Connect to Zenodo REST API](#ZenodoManager)<br/>
[4.3 Query Zenodo deposited records](#ZenodoDeposit-query)<br/>
[4.3.1 Get Depositions](#ZenodoDeposit-getdepositions)<br/>
[4.3.2 Get Deposition By Concept DOI](#ZenodoDeposit-getdepositionbyconceptdoi)<br/>
[4.3.3 Get Deposition By DOI](#ZenodoDeposit-getdepositionbydoi)<br/>
[4.3.4 Get Deposition By Zenodo record ID](#ZenodoDeposit-getdepositionbyid)<br/>
[4.3.5 Get Deposition versions](#ZenodoDeposit-getversions)<br/>
[4.4 Manage Zenodo record depositions](#ZenodoDeposit)<br/>
[4.4.1 Create an empty record](#ZenodoDeposit-emptyRecord)<br/>
[4.4.2 Fill a record](#ZenodoDeposit-fill)<br/>
[4.4.3 Deposit/Update a record](#ZenodoDeposit-deposit)<br/>
[4.4.4 Delete a record](#ZenodoDeposit-delete)<br/>
[4.4.5 Publish a record](#ZenodoDeposit-publish)<br/>
[4.4.6 Edit/Update a published record](#ZenodoDeposit-edit)<br/>
[4.4.7 Discard changes of a draft record](#ZenodoDeposit-discard)<br/>
[4.4.8 Create a new record version](#ZenodoDeposit-version)<br/>
[4.5 Manage Zenodo record deposition files](#ZenodoDepositFile)<br/>
[4.5.1 Upload file](#ZenodoDepositFile-upload)<br/>
[4.5.2 Get files](#ZenodoDepositFile-get)<br/>
[4.5.3 Delete file](#ZenodoDepositFile-delete)<br/>
[4.6 Export Zenodo record metadata](#ZenodoDepositMetadata)<br/>
[4.6.1 Export Zenodo record metadata by format](#ZenodoDepositMetadata-byformat)<br/>
[4.6.2 Export Zenodo record metadata - all formats](#ZenodoDepositMetadata-allformats)<br/>
[4.7 Browse Zenodo controlled vocabularies](#ZenodoVocabularies)<br/>
[4.7.1 Communities](#ZenodoVocabularies-communities)<br/>
[4.7.2 Licenses](#ZenodoVocabularies-licenses)<br/>
[4.7.3 Funders](#ZenodoVocabularies-funders)<br/>
[4.7.4 Grants](#ZenodoVocabularies-grants)<br/>
[4.8 Query Zenodo published records](#ZenodoRecord-query)<br/>
[4.8.1 Get Records](#ZenodoRecord-getrecords)<br/>
[4.8.2 Get Record By Concept DOI](#ZenodoRecord-getrecordbyconceptdoi)<br/>
[4.8.3 Get Record By DOI](#ZenodoRecord-getrecordbydoi)<br/>
[4.8.4 Get Record By ID](#ZenodoRecord-getrecordbyid)<br/>
[4.9 Download files from Zenodo records](#ZenodoRecord-download)<br/>
[**5. Issue reporting**](#package_issues)<br/>
<a name="package_overview"/>
### 1. Overview and vision
***
The [zen4R](https://doi.org/10.5281/zenodo.2547036) package offers an R interface to the [Zenodo](https://zenodo.org) e-infrastructure. It supports the creation of metadata records (including versioning), upload of files, and assignment of Digital Object Identifier(s) (DOIs).
[zen4R](https://doi.org/10.5281/zenodo.2547036) is jointly developed together with the [geoflow](https://github.com/r-geoflow/geoflow) which intends to facilitate and automate the production of geographic metadata documents and their associated datasources, where [zen4R](https://doi.org/10.5281/zenodo.2547036) is used to assign DOIs and cross-reference these DOIs in other metadata documents such as geographic metadata (ISO 19115/19139) hosted in metadata catalogues and open data portals.
<a name="package_status"/>
### 2. Development status
***
* January 2019: Inception. Code source managed on GitHub.
* June 2019: Published on CRAN.
<a name="package_credits"/>
### 3. Credits
***
(c) 2019, Emmanuel Blondel
Package distributed under MIT license.
If you use ``zen4R``, I would be very grateful if you can add a citation in your published work. By citing ``zen4R``, beyond acknowledging the work, you contribute to make it more visible and guarantee its growing and sustainability. For citation, please use the DOI: [](https://doi.org/10.5281/zenodo.2547036)
<a name="user_guide"/>
### 4. User guide
***
<a name="install_guide"/>
#### 4.1 How to install zen4R in R
For now, the package can be installed from Github
```R
install.packages("remotes")
```
Once the remotes package loaded, you can use the install_github to install ``zen4R``. By default, package will be installed from ``master`` which is the current version in development (likely to be unstable).
```R
require("remotes")
install_github("eblondel/zen4R")
```
For Linux/OSX, make sure to install the `sodium` package as follows:
```
sudo apt-get install -y libsodium-dev
```
<a name="ZenodoManager"/>
#### 4.2 Connect to Zenodo REST API
The main entry point of ``zen4R`` is the ``ZenodoManager``. Some basic methods, such as listing licenses known by Zenodo, do not require the token.
```R
zenodo <- ZenodoManager$new()
```
To use deposit functions of ``zen4R``, you will need to specify the ``token``. This token can be created [here]( https://zenodo.org/account/settings/applications/tokens/new/).
```R
zenodo <- ZenodoManager$new(
token = <your_token>,
logger = "INFO" # use "DEBUG" to see detailed API operation logs, use NULL if you don't want logs at all
)
```
By default, the ``zen4R`` **logger** is deactivated. To enable the logger, specify the level of log you wish as parameter of the above R code. Two logging levels are available:
* ``INFO``: will print the ``zen4R`` logs. Three types of messages can be distinguished: ``INFO``, ``WARN``, ``ERROR``. The latter is generally associated with a ``stop`` and indicate an blocking error for the R method executed.
* ``DEBUG`` will print the above ``zen4R`` logs, and report all logs from HTTP requests performed with ``cURL``
If you want to use the [Zenodo sandbox](https://sandbox.zenodo.org) to test record management before going with the production Zenodo e-infrastructure, you can specify the Zenodo sandbox URL (https://sandbox.zenodo.org/api) in the ``ZenodoManager``.
**Important: To use the Zenodo sandbox, you need to set up a sandbox account separately from Zenodo, create a separate personal access token to the sandbox API, and you must confirm via the confirmation link this account separately in order to be able to test your record management on this clone of Zenodo.**
The below code instructs how to connect to the Sandbox Zenodo e-infrastructure:
```R
zenodo <- ZenodoManager$new(
url = "https://sandbox.zenodo.org/api",
token = <your_zenodo_sandbox_token>,
logger = "INFO"
)
```
<a name="ZenodoDeposit-query"/>
#### 4.3 Query Zenodo deposited records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers several methods to query Zenodo depositions.
<a name="ZenodoDeposit-query-getdepositions"/>
##### 4.3.1 Get Depositions
The generic way to query depositions is to use the method ``getDepositions``. If specified with no parameter, all depositions will be returned:
```
my_zenodo_records <- zenodo$getDepositions()
```
It is also possible to specify an ElasticSearch query using the ``q`` parameter. For helpers and query examples, please consult this [Zenodo Search guide](https://help.zenodo.org/guides/search/).
Since the Zenodo API is paginated, an extra parameter ``size`` can be specified to indicate the number of records to be queried by page (default value is 10).
By default, the Zenodo API will return only the latest versions of a record. It is possible to retrieve all versions of records by specifying ``all_versions = FALSE``.
<a name="ZenodoDeposit-query-getdepositionbyconceptdoi"/>
##### 4.3.2 Get Deposition By Concept DOI
It is possible to interrogate and get a Zenodo record with its concept DOI (generic DOI common to all versions of a record):
```
my_rec <- zenodo$getDepositionByConceptDOI("<my_concept_doi>")
```
<a name="ZenodoDeposit-query-getdepositionbydoi"/>
##### 4.3.3 Get Deposition By DOI
It is possible to interrogate and get a Zenodo record with its DOI (record version-specific DOI):
```
my_rec <- zenodo$getDepositionByDOI("<my_doi>")
```
<a name="ZenodoDeposit-query-getdepositionbyid"/>
##### 4.3.4 Get Deposition By Zenodo ID
It is possible to interrogate and get a Zenodo record with its internal ID:
```
my_rec <- zenodo$getDepositionById(id)
```
<a name="ZenodoDeposit-getversions"/>
##### 4.3.4 Get versions of a Zenodo record
For a given record, it's possible to get the list of versions of this record:
```
my_rec <- zenodo$getDepositionByConceptDOI("<some_concept_doi>")
my_rec$getVersions()
```
The list of versions is provided as ``data.frame`` given the date of publication, version number, and DOI of each version.
> Note: This function is not provided through the Zenodo API, but exploits to Zenodo website and has been added to [zen4R](https://doi.org/10.5281/zenodo.2547036) to facilitate the browsing of record versions.
<a name="ZenodoDeposit"/>
#### 4.4 Manage Zenodo record depositions
<a name="ZenodoDeposit-emptyRecord"/>
##### 4.4.1 Create an empty record
It is possible to create and deposit an empty record, ready for editing. For that, run the following R code:
```r
myrec <- zenodo$createEmptyRecord()
```
This method will return an object of class ``ZenodoRecord`` for which an internal ``id`` and a DOI have been pre-defined by Zenodo. An alternate method is to create a local empty record (not deposited on Zenodo) doing:
```r
myrec <- ZenodoRecord$new()
```
The next section explains how to fill the record with metadata elements.
<a name="ZenodoDeposit-fill"/>
##### 4.4.2 Fill a record
Zenodo records can be described a set of multiple metadata elements. For a full documentation of these metadata elements, please consult the zen4R documentation with ``?ZenodoRecord``. The online Zenodo API documentation can be consulted as well [here](https://developers.zenodo.org/#representation).
Example of record filling with metadata elements:
```r
myrec <- ZenodoRecord$new()
myrec$setTitle("my R package")
myrec$setDescription("A description of my R package")
myrec$setUploadType("software")
myrec$addCreator(firstname = "John", lastname = "Doe", affiliation = "Independent", orcid = "0000-0000-0000-0000")
myrec$setLicense("mit")
myrec$setAccessRight("open")
myrec$setDOI("mydoi") #use this method if your DOI has been assigned elsewhere, outside Zenodo
myrec$addCommunity("ecfunded")
```
<a name="ZenodoDeposit-deposit"/>
##### 4.4.3 Deposit/update a record
Once the record is edited/updated, you can deposit it on Zenodo with the following code:
```r
myrec <- zenodo$depositRecord(myrec)
```
In order to apply further methods on this record (e.g. upload a file, publish/delete a record), you need to get the output of the function ``depositRecord`` (see example above) since after the deposition Zenodo will return the record that now contains an internal ``id`` required to identify and apply further actions. This id can be inspected with ``myrec$id``.
Instead, if you don't get the output of ``depositRecord`` and try to upload files or publish/delete the record based on the local record you handle (built upon ``ZenodoRecord$new()``), this will not work. Because it is a local record, the ``id`` of the record will still be ``NULL``, with no value assigned by Zenodo, and Zenodo will be unable to identify which record needs to be handled.
<a name="ZenodoDeposit-delete"/>
##### 4.4.4 Delete a record
A record deposited on Zenodo but not yet published remains in the [Upload](https://zenodo.org/deposit) area of Zenodo (a kind of staging area where draft records are in edition). As long as it is not published, a record can be deleted from the Zenodo [Upload](https://zenodo.org/deposit) area using:
```r
zenodo$deleteRecord(myrec$id)
```
<a name="ZenodoDeposit-publish"/>
##### 4.4.5 Publish a record
To publish a deposited record and make it available publicly online on Zenodo, the following method can be run:
```r
myrec <- zenodo$publishRecord(myrec$id)
```
A shortcut to publish a record is also available through the method ``depositRecord``, specifying ``publish = TRUE``. This method should be used with cautious giving the fact the record will go straight online on Zenodo if published. By default the parameter ``publish`` will be set to ``FALSE``:
```r
myrec <- zenodo$depositRecord(myrec, publish = TRUE)
```
The publication of a record requires at least to have uploaded at least one file for this record. See section [4.4.1 Upload file](https://github.com/eblondel/zen4R/wiki#44-manage-zenodo-record-deposition-files).
<a name="ZenodoDeposit-edit"/>
##### 4.4.6 Edit/Update a published record
It is possible to update metadata of a published record, but not to modify the files associated to it. In order to update metadata of a published record, the ``state`` of this record has to be modified to make it editable. For that, use the ``editRecord`` function giving the ``id`` of the record to edit:
```
myrec <- zenodo$editRecord(myrec$id)
```
Next, perform your metadata updates, and re-deposit the record
```
myrec$setTitle("newtitle")
myrec <- zenodo$depositRecord(myrec, publish = FALSE)
```
Since the record has been switched back to ``draft`` state, the record has to be re-published otherwise it will remain a draft record in your Zenodo user session.
<a name="ZenodoDeposit-discard"/>
##### 4.4.7 Discard changes of a draft record
In case you started editing a record and you want to discard changes on it, it is possible to do it with the ``discardChanges``.
```
zenodo$discardChanges(myrec$id)
```
<a name="ZenodoDeposit-version"/>
##### 4.4.8 Create a new version record
To create a new record version, you should first retrieve the record for which you want to create a new version. You can retrieve this record with methods based on DOI such as ``getDepositionByConceptDOI`` (to get a record based on concept DOI) or ``getDepositionByDOI``; or by Zenodo ``id`` with ``getDepositionById`` :
```r
#get record by DOI
myrec <- zenodo$getDepositionByDOI("<some doi>")
#edit myrec with updated metadata for the new version
#...
#create new version
myrec <- zenodo$depositRecordVersion(myrec, delete_latest_files = TRUE, files = "newversion.csv", publish = FALSE)
```
The function ``depositRecordVersion`` will create a new version for the published record. The parameter ``delete_latest_files`` (default = ``TRUE``) allows to delete latest files (knowing that a new record version expect to have different file(s) than the latest version). The ``files`` parameter allows to list the files to be uploaded. As for the ``depositRecord``, it is possible to publish the record with the ``publish`` paramater.
<a name="ZenodoDepositFile"/>
#### 4.5 Manage Zenodo record deposition files
<a name="ZenodoDepositFile-upload"/>
##### 4.5.1 Upload file
With ``zen4R``, it is very easy to upload a file to a record deposition. The record should first deposited on Zenodo. To upload a file, the following single line can be used, where the file ``path`` is specified and the record deposit to which the file should be uploaded:
```r
zenodo$uploadFile("path/to/your/file", record = myrec)
```
<a name="ZenodoDepositFile-get"/>
##### 4.5.2 Get files
To get the list of files attached to a record, you can specify the following method adding the record ``id``:
```r
zen_files <- zenodo$getFiles(myrec$id)
```
This retrieves a list of files. Each file has a unique ``id``, that can be used to for file deletion.
<a name="ZenodoDepositFile-delete"/>
##### 4.5.3 Delete file
The following example shows how to delete the first file attached to the record defined earlier. To delete a file, we need to specify both the record and file identifiers:
```r
zenodo$deleteFile(myrec$id, zen_files[[1]]$id)
```
<a name="ZenodoDepositMetadata"/>
#### 4.6 Export Zenodo record metadata
For a given Zenodo record, [zen4R](https://doi.org/10.5281/zenodo.2547036) let you export the metadata in a metadata file, with a series of ``exportAs*`` methods.
The metadata formats supported are: ``BibTeX``, ``CSL``, ``DataCite``, ``DublinCore``, ``DCAT``, ``JSON``, ``JSON-LD``, ``GeoJSON``, ``MARCXML``
<a name="ZenodoDepositMetadata-byformat"/>
##### 4.6.1 Export Zenodo record metadata by format
To export a record in a given format, they are two ways:
```
#using the generic exportAs
myrec$exportAs("BibTeX", filename = "myfilename")
#using the format-specific wrapper
myrec$exportAsBibTeX(filename = "myfilename")
```
The ``filename`` provided should not include the file extension that is managed by zen4R, depending on the chosen format.
<a name="ZenodoDepositMetadata-allformats"/>
##### 4.6.2 Export Zenodo record metadata - all formats
To export a record in all above metadata formats:
```
myrec$exportAsAllFormats(filename = "myfilename")
```
The ``filename`` provided should not include the file extension that is managed by zen4R, depending on the format.
<a name="ZenodoVocabularies"/>
#### 4.7 Browse Zenodo controlled vocabularies
<a name="ZenodoVocabularies-communities"/>
##### 4.7.1 Communities
```
communities <- zenodo$getCommunities()
```
<a name="ZenodoVocabularies-licenses"/>
##### 4.7.2 Licenses
```
licenses <- zenodo$getLicenses()
```
<a name="ZenodoVocabularies-funders"/>
##### 4.7.3 Funders
```
funders <- zenodo$getFunders()
```
<a name="ZenodoVocabularies-grants"/>
##### 4.7.4 Grants
```
grants <- zenodo$getGrants()
```
<a name="ZenodoRecord-query"/>
#### 4.8 Query Zenodo published records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers several methods to query Zenodo records.
<a name="ZenodoRecord-getrecords"/>
##### 4.8.1 Get Records
The generic way to query records is to use the method ``getRecords``
```
my_zenodo_records <- zenodo$getRecords(q = "<my_elastic_search_query>")
```
The ``q`` parameter should be an ElasticSearch query. For helpers and query examples, please consult this [Zenodo Search guide](https://help.zenodo.org/guides/search/).
Since the Zenodo API is paginated, an extra parameter ``size`` can be specified to indicate the number of records to be queried by page (default value is 10).
By default, the Zenodo API will return only the latest versions of a record. It is possible to retrieve all versions of records by specifying ``all_versions = FALSE``.
<a name="ZenodoRecord-getrecordbyconceptdoi"/>
##### 4.8.2 Get Record By Concept DOI
It is possible to interrogate and get a Zenodo record with its concept DOI (generic DOI common to all versions of a record):
```
my_rec <- zenodo$getRecordByConceptDOI("<my_concept_doi>")
```
<a name="ZenodoRecord-getrecordbydoi"/>
##### 4.8.3 Get Record By DOI
It is possible to interrogate and get a Zenodo record with its DOI (record version-specific DOI):
```
my_rec <- zenodo$getRecordByDOI("<my_doi>")
```
<a name="ZenodoRecord-getrecordbyid"/>
##### 4.8.4 Get Record By Zenodo ID
It is possible to interrogate and get a Zenodo record with its internal ID:
```
my_rec <- zenodo$getRecordById(id)
```
<a name="ZenodoRecord-download"/>
#### 4.9 Download files from Zenodo records
[zen4R](https://doi.org/10.5281/zenodo.2547036) offers methods to download files Zenodo published records.
Being published records, the latter and their files are accessible without any user token using `zenodo <- ZenodoManager$new(logger = "INFO")`. Files can be then downloaded either from a Zenodo `record` object (fetched with `getRecordByDOI`):
```r
rec <- zenodo$getRecordByDOI("10.5281/zenodo.3378733")
files <- rec$listFiles(pretty = TRUE)
#create a folder where to download my files
dir.create("download_zenodo")
#download files
rec$downloadFiles(path = "download_zenodo")
downloaded_files <- list.files("download_zenodo")
```
or using the shortcut function `download_zenodo`:
```r
#create a folder where to download my files
dir.create("download_zenodo")
#download files with shortcut function 'download_zenodo'
download_zenodo(path = "download_zenodo", "10.5281/zenodo.3378733")
downloaded_files <- list.files("download_zenodo")
```
Download can be also be done in parallel with `parallel` package, depending on the plateform. See below examples:
* For both Unix/Win OS (using clusters)
```r
library(parallel)
#download files as parallel using a cluster approach (for both Unix/Win systems)
download_zenodo("10.5281/zenodo.2547036", parallel = TRUE, parallel_handler = parLapply, cl = makeCluster(2))
```
* For Unix OS (using `mclapply `)
```r
#download files as parallel using mclapply (for Unix systems)
download_zenodo("10.5281/zenodo.2547036", parallel = TRUE, parallel_handler = mclapply, mc.cores = 2)
```
<a name="package_issues"/>
### 5. Issue reporting
***
Issues can be reported at https://github.com/eblondel/zen4R/issues
| /scratch/gouwar.j/cran-all/cranData/zen4R/vignettes/zen4R.Rmd |
getAllOrganizations <- function(){
curl = getCurlHandle()
stopPaging <- FALSE
result <- list()
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging == FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, .ZendeskEnv$data$organizations, "?page=" ,i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging <- TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$organizations))
final.result<-do.call("rbind", pre.result)
orgs.df <- data.frame(final.result)
orgs.df <- unlistDataFrame(orgs.df)
return(orgs.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getAllOrganizations.R |
getAllSatisfactionRatings <- function(){
curl = getCurlHandle()
stopPaging <- FALSE
result <- list()
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging == FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, .ZendeskEnv$data$satisfaction_ratings, "?page=" ,i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging <- TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$satisfaction_ratings))
final.result<-do.call("rbind", pre.result)
satisfaction_ratings.df <- data.frame(final.result)
satisfaction_ratings.df <- unlistDataFrame(satisfaction_ratings.df)
return(satisfaction_ratings.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getAllSatisfactionRatings.R |
getAllTicketMetrics <- function(){
curl <- getCurlHandle()
result <- list()
stopPaging <- FALSE
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging==FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, .ZendeskEnv$data$ticket_metrics, "?page=", i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging = TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$ticket_metrics))
final.result<-do.call("rbind", pre.result)
ticket_metrics.df <- data.frame(final.result)
ticket_metrics.df <- unlistDataFrame(ticket_metrics.df)
return(ticket_metrics.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getAllTicketMetrics.R |
getAllTickets <- function(){
curl = getCurlHandle()
stopPaging <- FALSE
result <- list()
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging == FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, .ZendeskEnv$data$tickets, "?page=" ,i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging <- TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$tickets))
final.result<-do.call("rbind", pre.result)
tickets.df <- data.frame(final.result)
tickets.df <- unlistDataFrame(tickets.df)
return(tickets.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getAllTickets.R |
getAllUsers <- function(){
curl <- getCurlHandle()
result <- list()
stopPaging <- FALSE
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging==FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, .ZendeskEnv$data$users, "?page=", i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging = TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$users))
final.result<-do.call("rbind", pre.result)
users.df <- data.frame(final.result)
users.df <- unlistDataFrame(users.df)
return(users.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getAllUsers.R |
getTicket <- function(ticket.id){
curl = getCurlHandle()
stopPaging <- FALSE
result <- list()
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging == FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, gsub(".json", "", .ZendeskEnv$data$tickets), "/", ticket.id, ".json?page=" ,i, sep=""), curl=curl,
ssl.verifypeer=FALSE, .opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging <- TRUE
}
i <- i + 1
}
## Transform the JSON data to a data.frame
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x))
final.result<-do.call("rbind", pre.result)
ticket.df <- data.frame(final.result)
ticket.df <- unlistDataFrame(ticket.df)
return(ticket.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getTicket.R |
getTicketAudits <- function(ticket.id){
curl = getCurlHandle()
stopPaging <- FALSE
result <- list()
i <- 1
## Need to page through the results since only 100 are returned at a time
while(stopPaging == FALSE){
result[[i]]<-getURL(paste(.ZendeskEnv$data$url, gsub(".json", "", .ZendeskEnv$data$tickets), "/", ticket.id, .ZendeskEnv$data$audits, "?page=" ,i, sep=""), curl=curl, ssl.verifypeer=FALSE,
.opts=list(userpwd=(paste(.ZendeskEnv$data$username, .ZendeskEnv$data$password, sep=":"))))
if(is.null(fromJSON(result[[i]])$next_page)){
stopPaging <- TRUE
}
i <- i + 1
}
json.data <- lapply(unlist(result), fromJSON)
pre.result <- lapply(json.data, function(x) do.call("rbind", x$audits))
final.result<-do.call("rbind", pre.result)
audits.df <- data.frame(final.result)
audits.df <- unlistDataFrame(audits.df)
return(audits.df)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/getTicketAudits.R |
zendesk <- function(username, password, url){
if(!is.null(username) & !is.null(password) & !is.null(url)){
.ZendeskEnv$data$username <- username
.ZendeskEnv$data$password <- password
.ZendeskEnv$data$url <- gsub("\\/$","", url)
}
else{
warning("Username, Password and URL must be provided in order to access your organization's data")
}
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/zendesk.R |
.ZendeskEnv <- new.env()
.ZendeskEnv$data <- list()
.onLoad <- function(libname, pkgname){
if(is.null(.ZendeskEnv$data) == FALSE){
.ZendeskEnv$data <- list(
username <- NULL,
password <- NULL,
url <- NULL,
users = "/api/v2/users.json",
tickets = "/api/v2/tickets.json",
audits = "/audits.json",
organizations = "/api/v2/organizations.json",
ticket_metrics = "/api/v2/ticket_metrics.json",
satisfaction_ratings = "/api/v2/satisfaction_ratings.json"
)
}
}
unlistDataFrame <-
function(dataframe){
n <- dim(dataframe)[1]
dim.df <- dim(dataframe)[2]
## Not sure why vectorized version of this doesn't work
## apply(dataframe, 2, function(x) { if (length(unlist(x)) == n) unlist(x)} )
for(i in 1:dim.df){
if(length(unlist(dataframe[,i])) == n){
dataframe[,i] <- unlist(dataframe[,i])
}
if(length(unlist(dataframe[,i])) < n){
dataframe[,i] <- as.character(dataframe[,i])
}
}
return (dataframe)
}
| /scratch/gouwar.j/cran-all/cranData/zendeskR/R/zzz.R |
## Layout tools for zenplot()
##' @title Auxiliary function for adjusting a bounding box
##' @param lastturn last turn
##' @param coordslastBB coordinates of the last bounding box
##' @param w width
##' @param h height
##' @return Coordinates of the adjusted bounding box
##' @author Wayne Oldford
adjust_bb <- function(lastturn, coordslastBB, w, h)
{
stopifnot(lastturn %in% c("d", "u", "r", "l"),
names(coordslastBB) == c("left", "right", "bottom", "top"),
w >= 0, h >= 0)
switch(lastturn,
"l" = {
c(coordslastBB["left"] - w,
coordslastBB["left"],
coordslastBB["bottom"],
coordslastBB["top"])
},
"r" = {
c(coordslastBB["right"],
coordslastBB["right"] + w,
coordslastBB["bottom"],
coordslastBB["top"])
},
"d" = {
c(coordslastBB["left"],
coordslastBB["right"],
coordslastBB["bottom"] - h,
coordslastBB["bottom"])
},
"u" = {
c(coordslastBB["left"],
coordslastBB["right"],
coordslastBB["top"],
coordslastBB["top"] + h)
},
stop("Wrong 'turns'"))
}
##' @title Compute the layout of the zen plot
##' @param turns turns (character vector consisting if "u", "d", "l", "r")
##' @param n2dplots the number of 2d plots (faces of the hypercube to be laid out)
##' @param first1d logical indicating whether the first 1d plot should be plotted
##' @param last1d logical indicating whether the last 1d plot should be plotted
##' @param width1d width of 1d plots
##' @param width2d width of 2d plots
##' @return list containing
##' 1) the plot orientations (c("h", "s", "v", "s", ...))
##' 2) the plot dimensions (1d plot, 2d plot, 1d plot, ...)
##' 3) the variable numbers plotted (an (nPlots, 2)-matrix)
##' 4) the total width of the layout
##' 5) the total height of the layout
##' 6) coordinates of the bounding boxes
##' @author Marius Hofert and Wayne Oldford
get_layout <- function(turns, n2dplots, first1d = TRUE, last1d = TRUE, width1d = 1, width2d = 10)
{
l <- as.numeric(!first1d) + as.numeric(!last1d) # 0 (first1d = last1d = TRUE), 1 (precisely one TRUE) or 2 (first1d = last1d = FALSE)
stopifnot(n2dplots >= 0, width1d > 0, width2d > 0)
indices <- 1:(n2dplots+1)
turn_checker(turns = turns, n2dplots = n2dplots, first1d = first1d, last1d = last1d)
dimensions <- c(rep(1:2, n2dplots), 1) # plot dimensions (1d plot, 2d plot, 1d plot, ...)
if(!first1d) dimensions <- dimensions[-1]
if(!last1d) dimensions <- dimensions[-length(dimensions)]
nPlots <- length(dimensions) # number of plots; >= 1 (checked)
orientations <- rep("s", nPlots) # plot orientations ("s"=square, "h"=horizontal, "v"=vertical)
## 1) Determine positions of bounding boxes (in terms of default width and
## height units); for each plot, start at zero
coordsBB <- matrix(0, nrow = nPlots, ncol = 4,
dimnames = list(NULL, c("left", "right", "bottom", "top"))) # (nPlots, 4)-matrix
## Now we have to build the variable selections and their information
vars <- matrix(0, nrow=nPlots, ncol=2, dimnames=list(NULL, c("x", "y"))) # (nPlots, 2)-matrix
## 2) Loop over all plots starting from the 2nd
## 2.1) Deal with first plot
if (dimensions[1]==1) {
lastVar <- 1
curVar <- lastVar
vars[1,] <- indices[c(1, 1)]
if (turns[1] %in% c("u", "d")) {
orientations[1] <- "h"
coordsBB[1, "right"] <- width2d
coordsBB[1, "top"] <- width1d
} else if(turns[1] %in% c("l", "r")) {
orientations[1] <- "v"
coordsBB[1, "right"] <- width1d
coordsBB[1, "top"] <- width2d
} else stop("Wrong 'turns'")
} else {
lastVar <- 1
curVar <- 2
vars[1,] <- indices[c(1, 2)]
lastVar <- curVar
coordsBB[1, "right"] <- width2d
coordsBB[1, "top"] <- width2d
}
## 2.2) Actual loop
for(i in 1+seq_len(nPlots-1)) { # 2,3,...,nPlots
if(dimensions[i] == 1) { # current plot is a 1d plot
vars[i,] <- indices[rep(curVar, 2)] # determine 1d plot variables
coordsBB[i,] <-
switch(turns[i], # determine 1d plot bounding box
"l" = {
orientations[i]="v"
adjust_bb(turns[i-1], coordslastBB=coordsBB[i-1,],
w=width1d, h=width2d)
},
"r" = {
orientations[i]="v"
adjust_bb(turns[i-1], coordslastBB=coordsBB[i-1,],
w=width1d, h=width2d)
},
"d" = {
orientations[i]="h"
adjust_bb(turns[i-1], coordslastBB=coordsBB[i-1,],
w=width2d, h=width1d)
},
"u" = {
orientations[i]="h"
adjust_bb(turns[i-1], coordslastBB=coordsBB[i-1,],
w=width2d, h=width1d)
},
stop("Wrong 'turns' for 1d plot"))
} else { # current plot is a 2d plot
curVar <- curVar + 1
vars[i,] <- indices[switch(turns[i], # determine 2d plot variables
"l" = {
c(lastVar, curVar)
},
"r" = {
c(lastVar, curVar)
},
"d" = {
c(curVar, lastVar)
},
"u" = {
c(curVar, lastVar)
},
stop("Wrong 'turns' for 2d plot"))]
coordsBB[i,] <- adjust_bb(turns[i-1], coordslastBB=coordsBB[i-1,],
w=width2d, h=width2d) # determine 2d plot bounding box
lastVar <- curVar
}
}
## Return
layoutWidth <- diff(range(coordsBB[,c( "left", "right")])) # total width
layoutHeight <- diff(range(coordsBB[,c("bottom", "top")])) # total height
list(orientations = orientations, # vector of plot orientations ("s"=square, "h"=horizontal, "v"=vertical)
dimensions = dimensions, # plot dimensions (1d plot, 2d plot, 1d plot, ...)
vars = vars, # (nPlots, 2)-matrix of variables
layoutWidth = layoutWidth, layoutHeight = layoutHeight, # total width and height
boundingBoxes = coordsBB) # bounding boxes
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/getlayout.R |
## Move/turns/path tools for zenplot()
##' @title Determine the new position when moving from the current position
##' in a given direction
##' @param curpos current position (i, j) in the occupancy matrix
##' @param dir direction in which we move ("d", "u", "r" or "l")
##' @param method choice of method ("in.occupancy" means the (current/new)
##' position is given in terms of (row, column) indices in the
##' occupancy matrix; "in.plane" means the directions are
##' interpreted as in the (x,y)-plane).
##' @return new position in the occupancy matrix
##' @author Marius Hofert and Wayne Oldford
move <- function(curpos, dir, method = c("in.occupancy", "in.plane"))
{
method <- match.arg(method)
curpos +
if (method == "in.plane") {
switch(dir,
"d" = { c( 0, -1) },
"u" = { c( 0, 1) },
"r" = { c( 1, 0) },
"l" = { c(-1, 0) },
stop("Wrong 'dir'"))
} else {
switch(dir,
"d" = { c( 1, 0) },
"u" = { c(-1, 0) },
"r" = { c( 0, 1) },
"l" = { c( 0, -1) },
stop("Wrong 'dir'"))
}
}
##' @title Compute turns for zigzag
##' @param nPlots total number of plots
##' @param n2dcols number of columns of 2d plots (>= 1)
##' @param method character string indicating which zigzag method to use
##' @return turns
##' @author Marius Hofert and Wayne Oldford
get_zigzag_turns <- function(nPlots, n2dcols,
method = c("tidy", "double.zigzag", "single.zigzag"))
{
## Main idea: Determine the pattern which repeats rowblock-wise
## (after going to the right and then back to the left)
stopifnot(nPlots >= 4, # smaller nPlots relate to special cases dealt with in get_path()
n2dcols >= 2)
method <- match.arg(method)
## 1) Define the horizontal 2d pattern of turns
h2dpattern <- rep(c("r", "l"), each = 2*(n2dcols-1)) # r,r,..., l,l,... for 2d plots
## 2) Define the vertical 2d subpattern
v2dsubpattern <- if(method == "single.zigzag") rep("d", n2dcols-1) else {
if(n2dcols <= 2) "d" else c(rep_len(c("d", "u" ), n2dcols-3), "d", "d") # up/down for 2d plots for one row (length = n2dcols - 1; so, e.g. only from right to left)
}
## 3) Define the vertical 2d pattern
v2dpattern <- rep(v2dsubpattern, times = 2) # up/down for 2d plots for one block of rows (r,r,..., l,l,...)
## 4) Merge the vertical 2d pattern into the horizontal 2d pattern
h2dpattern[2*seq_along(v2dpattern)] <- v2dpattern # merge the ups/downs into h2dpattern
## 5) Repeat the merged 2d pattern to account for 1d plots
overallpattern <- rep(h2dpattern, each = 2) # bring in 1d plots (by repeating each direction twice)
## 6) Repeat the overall pattern according to the total number of (1d or 2d) plots
c("d", rep_len(overallpattern, nPlots-1)) # attach the first 1d plot separately and repeat the repeat pattern as often as required
}
##' @title Determine the next position to move to and the turn out of there
##' @param plotNo current plot number
##' @param nPlots total number of plots
##' @param curpath the current path
##' @return a list containing the next position to move to (nextpos) and the turn
##' out of there (nextout); Interpretation:
##' nextpos: position of plot number plotNo+1 in the (non-trimmed) occupancy matrix
##' nextout: turn out of nextpos
##' @author Marius Hofert and Wayne Oldford
##' @note - This assumes that the last plot is a 1d plot!
##' - It also assumes that first1d = TRUE; will be adapted later in get_path()
##' in case first1d = FALSE.
##' - We start in (1, 2) and also have an additional last column in the occupancy
##' matrix to have the first and last column left in case we end up there with
##' the last 1d plot; this cannot happen for 'zigzag' but for 'tidy'.
next_move_tidy <- function(plotNo, nPlots, curpath)
{
stopifnot(plotNo >= 1, nPlots >= 4, # smaller nPlots relate to special cases dealt with in get_path()
is.list(curpath))
nPlotsLeft <- nPlots - plotNo # number of plots left
if(nPlotsLeft <= 0)
stop("Wrong number of plots left.") # next_move_tidy() should not be called in this case
## 1) Deal with special cases first
if(plotNo==1) return(list(nextpos=c(2, 2), nextout="r")) # 1st plot (1d); next move/turn is "r"
if(plotNo==2) return(list(nextpos=c(2, 3), nextout="r")) # 2nd plot (2d); next move/turn is "r"
if(plotNo==3) # 3rd plot (1d); next move/turn is either up (only if there's only 1 1d plot left) or down
return(list(nextpos=c(2, 4), nextout=if(nPlotsLeft <= 2) "u" else "d"))
## 2) Now plotNo >= 4 and there are >= 1 plots left
curpos <- curpath$positions[plotNo,] # current position
curin <- curpath$turns[plotNo-1] # turn into the current position
curout <- curpath$turns[plotNo] # turn out of the current position
nextpos <- move(curpos, curout) # next position to move to
## 3) If plotNo is even (2d plot)
## Note: This case also applies if nPlotsLeft==1
if(plotNo %%2 == 0)
return(list(nextpos=nextpos, nextout=curout))
## Now we are in the case plotNo is >= 5, odd (1d plot) and there are >= 2 plots left
## 4) Determine the current horizontal moving direction.
## If the current 1d plot is vertical (or: horizontal), the horizontal direction is the
## turn into the current (or: last) position.
## => We simply consider the turn into the current position and the
## one before to determine the horizontal moving direction.
rinlast2 <- "r" %in% curpath$turns[(plotNo-2):(plotNo-1)]
linlast2 <- "l" %in% curpath$turns[(plotNo-2):(plotNo-1)]
if((rinlast2 + linlast2) != 1) # defensive programming
stop("Algorithm to determine horizontal moving direction is wrong. This should not happen.")
horizdir <- if(rinlast2) "r" else "l" # current horizontal moving direction
## Determine the distance to the margin of the occupancy matrix in the horizontal moving direction
ncolOcc <- ncol(curpath$occupancy)
dist <- if(horizdir=="r") ncolOcc-curpos[2] else curpos[2]-1
stopifnot(dist >= 0) # defensive programming
## 5) We are sitting at a 1d plot and have to determine how to leave
## the next 2d plot
posExists <- function(pos, occupancy) # aux function for checking the existence of a position in the occupancy matrix
(1 <= pos[1] && pos[1] <= nrow(occupancy)) &&
(1 <= pos[2] && pos[2] <= ncol(occupancy))
nextout <- if(curout %in% c("d", "u")) { # 5.1)
## 5.1) The 1d plot is horizontal (curout "u" or "d")
if(dist == 0) stop("dist == 0. This should not happen.")
## If we have at most 2 plots left, decide where to put the last 1d plot
if(nPlotsLeft <= 2) { # 5.1.1)
## Check the location of the 2d plot which comes after the next 2d plot
## in opposite horizontal moving direction.
pos2check <- c(curpos[1] + if(curout=="u") -1 else 1, curpos[2] + if(horizdir=="r") -2 else 2)
exists <- posExists(pos2check, occupancy = curpath$occupancy)
## If it does not exist (can only happen if curout="d" in which case
## the occupancy matrix is missing a new row), then put the
## last 1d plot in opposite horizontal moving direction if we are near
## the margin (otherwise we would occupy an additional column) and put it
## in the horizontal moving direction otherwise (if we are 'inside' the
## occupancy matrix)
if(!exists) { # we will be in a new row (curout must be "d" in this case)
stopifnot(curout=="d") # defensive programming
if(dist <= 2) {
if(horizdir == "r") "l" else "r"
} else {
horizdir
}
} else { # exists
## If this position exists, then change the horizontal moving direction
## if and only if it is not occupied (otherwise we can't go there)
if(curpath$occupancy[pos2check[1], pos2check[2]] == "") { # not occupied
if(horizdir == "r") "l" else "r"
} else {
horizdir
}
}
} else { # 5.1.2) nPlotsLeft >= 3 (=> at least two more 2d plots)
## Change the horizontal moving direction if and only if we are at
## the boundary (clear).
if(dist <= 2) {
if(horizdir == "r") "l" else "r"
} else {
horizdir
}
}
} else { # 5.2) curout "l" or "r"
## 5.2) The 1d plot is vertical (curout "l" or "r")
if(curpath$turns[plotNo-2] %in% c("l", "r")) # defensive programming; how we entered last 2d plot must be l or r
stop("Last 2d plot was entered in the wrong direction. This should not happen.")
if(dist <= 1) {
stop("dist <= 1. This should not happen.") # ... as we don't call next_move_tidy() for the last 1d plot
} else { # dist >= 2; note that dist==2 and dist==3 are possible
## 5.2.1) Auxiliary function to determine how many plots fit in the next U-turn
UturnLength <- function(curpos, horizdir, occupancy) {
## Check whether 1 or 2 plot(s) fit in
pos2check <- c(curpos[1]-2, curpos[2] + if(horizdir=="r") 1 else -1)
exists <- posExists(pos2check, occupancy=occupancy)
if(exists && (occupancy[pos2check[1], pos2check[2]] != "")) return(1)
if(!exists) return(2) # ... we can't put in more plots
## Check whether 4 plots fit in
pos2check <- pos2check + c(0, if(horizdir=="r") 2 else -2)
exists <- posExists(pos2check, occupancy=occupancy)
if(!exists || (exists && (occupancy[pos2check[1], pos2check[2]] != "")))
return(4) # ... we can't put in more plots
## Check whether 6 plots fit in
pos2check <- pos2check + c(2, 0)
exists <- posExists(pos2check, occupancy=occupancy)
if(!exists || (exists && (occupancy[pos2check[1], pos2check[2]] != "")))
return(6) # ... we can't put in more plots
## Check whether 8 or >= 10 plots fit in
pos2check <- pos2check + c(0, if(horizdir=="r") 2 else -2)
exists <- posExists(pos2check, occupancy=occupancy)
if(!exists || (exists && (occupancy[pos2check[1], pos2check[2]] != "")))
return(8) else return(10) # here means "at least 10"
}
## Determine the number of plots along the U-turn starting from the current position
Ulen <- UturnLength(curpos, horizdir = horizdir, occupancy = curpath$occupancy)
## 5.2.2) If we are in the second row or there are more plots left than
## can fit into a U-turn, go down, else go up.
## Note: if Ulen >= 10, we can always take the U-turn, so we can always go up
if(curpos[1] <= 2 || (Ulen < 10 && nPlotsLeft > Ulen)) "d" else "u"
}
}
## 6) Return
list(nextpos = nextpos, nextout = nextout) # nextout = turn out of next position
}
##' @title Computing the path according to the provided method
##' @param turns The turns
##' @param n2dcols The number of columns of 2d plots (>= 1) or one of "letter", "square",
##' "A4", "golden", "legal". Note that n2dcols is ignored if turns is not NULL.
##' @param n2dplots The number of 2d plots to be laid out
##' @param method A character string indicating the method according to which the
##' path is built
##' @param first1d A logical indicating whether the first 1d plot should be plotted
##' @param last1d A logical indicating whether the last 1d plot should be plotted
##' @return the path, a list containing the turns, the positions (indices in the
##' occupancy matrix) and the the occupancy matrix
##' @author Marius Hofert and Wayne Oldford
get_path <- function(turns = NULL, n2dcols = c("letter", "square", "A4", "golden", "legal"),
n2dplots, method = c("tidy", "double.zigzag", "single.zigzag", "rectangular"),
first1d = TRUE, last1d = TRUE)
{
## 1) Deal with the case that turns have been given (we need to construct
## the positions in the occupancy matrix and the occupancy matrix itself)
if(!is.null(turns)) {
## 1.1) Initialization
hlim <- c(0, 0) # horizontal limits covered so far
vlim <- c(0, 0) # vertical limits covered so far
positions <- matrix(0, nrow=length(turns), ncol=2,
dimnames=list(NULL, c("x", "y"))) # matrix of positions
loc <- c(0, 0) # where we are at the moment (start)
## 1.2) Loop
if(length(turns) > 1) { # if length(turns)==1, we only have one 1d plot (nothing to do as positions is already initialized with 0)
for(i in 2:length(turns)) { # loop over all turns
loc <- move(loc, dir=turns[i-1]) # move to the next location according to turns
positions[i,] <- loc # update positions
if(loc[1] < hlim[1]) {
hlim[1] <- loc[1] # extend the lower bound of hlim if necessary
} else if(loc[1] > hlim[2]) {
hlim[2] <- loc[1] # extend the upper bound of hlim if necessary
}
if(loc[2] < vlim[1]) {
vlim[1] <- loc[2] # extend the lower bound of vlim if necessary
} else if(loc[2] > vlim[2]) {
vlim[2] <- loc[2] # extend the upper bound of vlim if necessary
}
}
}
## 1.3) Shift
min.pos <- apply(positions, 2, min) # get minimal visited row/column position
positions <- sweep(positions, 2, min.pos) + 1 # substract these and add (1,1)
## 1.4) Compute the occupancy matrix
occupancy <- matrix("", nrow=max(positions[,"x"]), ncol=max(positions[,"y"])) # occupancy matrix; note: already trimmed by construction
for(i in 1:nrow(positions)) # loop over positions and fill occupancy matrix accordingly
occupancy[positions[i,1], positions[i,2]] <- switch(turns[i],
"l" = { "l" },
"r" = { "r" },
"d" = { "d" },
"u" = { "u" },
stop("Wrong 'turns'"))
## (Early) return
return(list(turns = turns, positions = positions, occupancy = occupancy)) # return here; avoids huge 'else' below
}
## 2) Now consider the case where turns has not been given => construct the path
## Checking
stopifnot(n2dplots >= 0)
if(is.character(n2dcols)) n2dcols <- n2dcols_aux(n2dplots, method = n2dcols)
stopifnot(length(n2dcols) == 1, n2dcols >= 1)
if(n2dplots >= 2 && n2dcols < 2)
stop("If n2dplots >= 2, n2dcols must be >= 2.")
method <- match.arg(method)
## 2.1) Deal with method = "rectangular" first
if(method == "rectangular") {
nPlots <- 2 * n2dplots + 1 - !first1d - !last1d
## Determine the number or rows required
n2drows <- ceiling(n2dplots/n2dcols)
## Determine 'turns'
turns <- unlist(lapply(rep(c("r", "l"), length.out = n2drows),
function(t) c("d", rep(t, 2*(n2dcols-1)), "d"))) # correct for a *full last* row if first1d == TRUE and last1d == FALSE
if(!first1d) turns <- turns[-1] # remove first element
if(last1d) turns <- c(turns, "d") # append last element
turns <- turns[seq_len(nPlots)] # grab out those we need
## Determine 'positions'
positions <- matrix(, nrow = nPlots, ncol = 2, dimnames = list(NULL, c("x", "y"))) # positions
if(nPlots >= 1) positions[1,] <- c(1, 1) # first plot
if(nPlots >= 2) {
for(plotNo in 2:nPlots) {
turnOOcur <- turns[plotNo-1] # turn out of last position
if(turnOOcur == "r") {
positions[plotNo,] <- positions[plotNo-1,] + c(0,1)
} else if(turnOOcur == "l") {
positions[plotNo,] <- positions[plotNo-1,] + c(0,-1)
} else if(turnOOcur == "d") {
positions[plotNo,] <- positions[plotNo-1,] + c(1,0)
} else stop("Wrong turn in 'rectangular' method. This should not happen.")
}
}
## Determine occupancy matrix
occupancy <- matrix(0, nrow = positions[nPlots,1], ncol = min(max(positions[,2]), 2*n2dcols-1)) # positions
for(i in 1:nPlots) {
occupancy[positions[i,1], positions[i,2]] <- switch(turns[i],
"l" = { "l" },
"r" = { "r" },
"d" = { "d" },
"u" = { "u" }, # should not happen here
stop("Wrong 'turns'"))
}
## Return
return(list(turns = turns, positions = positions, occupancy = occupancy))
}
## 2.2) We start by dealing with three special cases (the same for all methods)
nPlots <- 2 * n2dplots + 1 # total number of plots (1d and 2d; assumes first1d = TRUE; last1d = TRUE (will be trimmed off below if necessary))
path <- if(nPlots <= 3) {
switch(nPlots,
{ # nPlots = 1
turns <- "d"
positions <- matrix(c(1,1), ncol=2, dimnames=list(NULL, c("x", "y")))
occupancy <- matrix("d", nrow=1, ncol=1)
list(turns=turns, positions=positions, occupancy=occupancy)
},
{ # nPlots = 2
turns <- c("d", "r")
positions <- matrix(c(1,1, 2,1), ncol=2, byrow=TRUE,
dimnames=list(NULL, c("x", "y")))
occupancy <- matrix(c("d", "r"), nrow=2, ncol=1)
list(turns=turns, positions=positions, occupancy=occupancy)
},
{ # nPlots = 3
turns <- c("d", "r", "r")
positions <- matrix(c(1,1, 2,1, 2,2), ncol=2, byrow=TRUE,
dimnames=list(NULL, c("x", "y")))
occupancy <- matrix(c("d","", "r","r"), nrow=2, ncol=2, byrow=TRUE)
list(turns=turns, positions=positions, occupancy=occupancy)
},
stop("Wrong 'nPlots'"))
} else {
## nPlots >= 4 (repeating order depends on n2dcols)
turns <- character(nPlots) # how we leave every plot (1d or 2d)
switch(method,
"double.zigzag" =, "single.zigzag" = { # 2.2.1)
## Main idea: Determine all turns right away, then build positions and
## occupancy matrix all from the turns
turns <- get_zigzag_turns(nPlots, n2dcols=n2dcols, method=method)
## Build positions and occupancy matrix
## Setup
ncolOcc <- 2*n2dcols-1 # number of columns in the occupancy matrix
occupancy <- matrix("", nrow=1, ncol=ncolOcc) # occupancy matrix
positions <- matrix(0, nrow=nPlots, ncol=2, dimnames=list(NULL, c("x", "y"))) # positions
## Init
curpos <- c(1, 1) # current position
positions[1,] <- curpos # occupy (row, col)
occupancy[curpos[1], curpos[2]] <- turns[1]
## Loop over all remaining plots
maxrowOcc <- 1
for(plotNo in 2:nPlots) {
## Update position
nextpos <- move(curpos, dir=turns[plotNo-1])
positions[plotNo,] <- nextpos # occupy location (row, col)
curpos <- nextpos
if(curpos[1] > maxrowOcc) { # expand occupancy matrix by one row
occupancy <- rbind(occupancy, rep("", ncolOcc))
maxrowOcc <- maxrowOcc + 1
}
## Update occupancy matrix
occupancy[nextpos[1], nextpos[2]] <- turns[plotNo]
}
## Trim last columns of "" from occupancy matrix
occupancy <- occupancy[,seq_len(max(positions[,2])), drop=FALSE]
## Build path
list(turns=turns, positions=positions, occupancy=occupancy)
},
"tidy" = { # 2.2.2)
## Main idea: Build turns, positions and occupancy as we go along
## Setup
turns <- character(nPlots) # vector of turns out of current position
ncolOcc <- 2*n2dcols+1 # number of columns in the occupancy matrix (2*n2dcols-1 + left/right one more)
occupancy <- matrix("", nrow=1, ncol=ncolOcc) # occupancy matrix
positions <- matrix(0, nrow=nPlots, ncol=2, dimnames=list(NULL, c("x", "y"))) # positions
## Init
turns[1] <- "d" # turn out of current position
positions[1,] <- c(1, 2) # occupy (row, col)
occupancy[1, 2] <- "d" # initialize occupancy matrix there
## Loop over all remaining plots
maxrowOcc <- 1
for(plotNo in 2:nPlots) {
## Next move
nextmove <- next_move_tidy(plotNo-1, nPlots=nPlots,
curpath=list(turns=turns,
positions=positions,
occupancy=occupancy))
## Update turn
turns[plotNo] <- nextmove$nextout # nextout = turn out of next position
## Update position
nextpos <- nextmove$nextpos
positions[plotNo,] <- nextpos # occupy location (row, col)
if(nextpos[1] > maxrowOcc) { # expand occupancy matrix by one row
occupancy <- rbind(occupancy, rep("", ncolOcc))
maxrowOcc <- maxrowOcc + 1
}
## Update occupancy matrix
occupancy[nextpos[1], nextpos[2]] <-
switch(turns[plotNo], # update occupancy matrix
"l" = { "l" },
"r" = { "r" },
"d" = { "d" },
"u" = { "u" },
stop("Wrong 'turns' at plotNo ", plotNo))
}
## Trim last columns of 0s from occupancy matrix if necessary
occupancy <- occupancy[,seq_len(max(positions[,2])), drop=FALSE]
## Trim first column of 0s and adjust positions if necessary
if(all(occupancy[,1]=="")) { # first column
occupancy <- occupancy[,-1]
positions[,2] <- positions[,2] - 1
}
## Build path
list(turns=turns, positions=positions, occupancy=occupancy)
},
stop("Wrong 'method'"))
}
## Trim path if necessary
## Idea: Take corresponding (first/last) turn to determine where to trim the
## occupancy matrix and the positions.
if(!first1d) {
## Trim turns
first1d.turn.out <- path$turns[1] # get turn out of first 1d plot
turns <- path$turns[-1] # trim
## Trim occupancy matrix
occupancy <- path$occupancy
rm <- positions[1,] # position to be removed (= replaced by 0)
occupancy[rm[1], rm[2]] <- "" # remove position
switch(first1d.turn.out,
"l" = { # check whether we can trim last column
jj <- ncol(occupancy)
if(all(occupancy[,jj] == ""))
occupancy <- occupancy[,-jj, drop = FALSE] # trim; no shift in positions necessary!
},
"r" = { # check whether we can trim first column
if(all(occupancy[,1] == "")) {
occupancy <- occupancy[,-1, drop = FALSE] # trim
path$positions[,2] <- path$positions[,2] - 1 # shift all positions
}
},
"d" = { # check whether we can trim first row
if(all(occupancy[1,] == "")) {
occupancy <- occupancy[-1,, drop = FALSE] # trim
path$positions[,1] <- path$positions[,1] - 1 # shift all positions
}
},
"u" = { # check whether we can trim last row
ii <- nrow(occupancy)
if(all(occupancy[ii,] == ""))
occupancy <- occupancy[-ii,, drop = FALSE] # trim; no shift in positions necessary!
}, stop("Wrong 'first1d.turn.out'."))
## Trim positions
positions <- path$positions[-1,, drop = FALSE] # trim
## Define (trimmed) path
path <- list(turns = turns, positions = positions, occupancy = occupancy)
}
if(!last1d) {
## Trim turns
n <- length(path$turns)
last1d.turn.out <- path$turns[n] # get turn out of last 1d plot
turns <- path$turns[-n] # trim
## Trim occupancy matrix
occupancy <- path$occupancy
rm <- positions[n,] # position to be removed (= replaced by 0)
occupancy[rm[1], rm[2]] <- "" # remove position
switch(last1d.turn.out,
"l" = { # check whether we can trim first column
if(all(occupancy[,1] == "")) {
occupancy <- occupancy[,-1, drop = FALSE] # trim
path$positions[,2] <- path$positions[,2] - 1 # shift all positions
}
},
"r" = { # check whether we can trim last column
jj <- ncol(occupancy)
if(all(occupancy[,jj] == ""))
occupancy <- occupancy[,-jj, drop = FALSE] # trim; no shift in positions necessary!
},
"d" = { # check whether we can trim last row
ii <- nrow(occupancy)
if(all(occupancy[ii,] == ""))
occupancy <- occupancy[-ii,, drop = FALSE] # trim; no shift in positions necessary!
},
"u" = { # check whether we can trim first row
if(all(occupancy[1,] == "")) {
occupancy <- occupancy[-1,, drop = FALSE] # trim
path$positions[,1] <- path$positions[,1] - 1 # shift all positions
}
}, stop("Wrong 'last1d.turn.out'."))
## Trim positions
positions <- path$positions[-n,, drop = FALSE] # trim
## Define (trimmed) path
path <- list(turns = turns, positions = positions, occupancy = occupancy)
}
## Return the path
path
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/getpath.R |
## Default 1d plot functions based on graphics
##' @title Rug plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name rug_1d_graphics
##' @aliases rug_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param length length of the rugs
##' @param width line width of the rugs
##' @param col color of the rugs
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to segments()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
rug_1d_graphics <- function(zargs,
loc = 0.5, length = 0.5, width = 1, col = par("fg"),
add = FALSE, plot... = NULL, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x) # for segments()
horizontal <- r$horizontal
lim <- r$xlim
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d" || turn.out == "l") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(add) usr <- par("usr")
if(horizontal) {
xlim <- lim
ylim <- 0:1
x0 <- x
y0 <- loc - length/2
x1 <- x
y1 <- loc + length/2
if(add) opar <- par(usr = c(usr[1:2], 0, 1)) # force y-coordinates to be [0,1]
} else {
xlim <- 0:1
ylim <- lim
x0 <- loc - length/2
y0 <- x
x1 <- loc + length/2
y1 <- x
if(add) opar <- par(usr = c(0, 1, usr[3:4])) # force x-coordinates to be [0,1]
}
## Plotting
if(add) {
on.exit(par(opar))
} else {
plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
}
if(length(x) > 0)
segments(x0 = x0, y0 = y0, x1 = x1, y1 = y1,
col = col, lwd = width, ...)
}
##' @title Dot plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name points_1d_graphics
##' @aliases points_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param cex character expansion factor
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
points_1d_graphics <- function(zargs,
loc = 0.5, cex = 0.4,
add = FALSE, plot... = NULL, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x) # for points()
horizontal <- r$horizontal
lim <- r$xlim
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d" || turn.out == "l") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(length(loc) == 1) loc <- rep(loc, length(x))
if(add) usr <- par("usr")
if(horizontal) {
xlim <- lim
ylim <- 0:1
x <- x
y <- loc
if(add) opar <- par(usr = c(usr[1:2], 0, 1)) # force y-coordinates to be [0,1]
} else {
ylim <- lim
xlim <- 0:1
y <- x
x <- loc
if(add) opar <- par(usr = c(0, 1, usr[3:4])) # force x-coordinates to be [0,1]
}
## Plotting
if(add) {
on.exit(par(opar))
} else {
plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
}
points(x = x, y = y, cex = cex, ...)
}
##' @title Jittered dot plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name jitter_1d_graphics
##' @aliases jitter_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param offset number in [0,0.5] determining how far off the center
##' the jittered points reach maximally
##' @param cex character expansion factor
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
jitter_1d_graphics <- function(zargs,
loc = 0.5, offset = 0.25, cex = 0.4,
add = FALSE, plot... = NULL, ...)
{
r <- extract_1d(zargs)
x <- r$x
stopifnot(0 <= offset, offset <= 0.5, 0 <= loc, loc <= 1, offset <= min(loc, 1-loc))
loc. <- loc + runif(length(x), min = -offset, max = offset)
points_1d_graphics(zargs, loc = loc., cex = cex, add = add, plot... = plot..., ...)
}
##' @title Histogram as 1d plot using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name hist_1d_graphics
##' @aliases hist_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param breaks see ?hist; the default is 20 equi-width bins covering the data range
##' @param length.out number of break points if breaks = NULL
##' @param col vector of colors for the bars or bar components; see ?barplot
##' @param axes logicial indicating whether axes should be drawn
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to barplot()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
hist_1d_graphics <- function(zargs,
breaks = NULL, length.out = 21, col = NULL,
axes = FALSE, add = TRUE,
plot... = NULL, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
horizontal <- r$horizontal
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
lim <- r$xlim
if(all(is.na(x))) {
## Empty plot
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
} else {
if(is.null(breaks))
breaks <- seq(from = lim[1], to = lim[2], length.out = length.out)
binInfo <- hist(x, breaks = breaks, plot = FALSE)
binBoundaries <- binInfo$breaks
widths <- diff(binBoundaries)
heights <- binInfo$density
if(turn.out == "d" || turn.out == "l") heights <- -heights
if(horizontal) {
xlim <- lim - lim[1] # c(0, sum(widths))
ylim <- range(0, heights)
} else {
xlim <- range(0, heights)
ylim <- lim - lim[1] # c(0, sum(widths))
}
## Plotting
plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
barplot(heights, width = widths, space = 0, horiz = !horizontal,
main = "", xlab = "", col = col, border = col, add = add, axes = axes, ...)
}
}
##' @title Density plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name density_1d_graphics
##' @aliases density_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param density... list of arguments for density()
##' @param offset number in [0, 0.5] determining how far away the density stays
##' from the plot margins (for creating space between the two)
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to polygon()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
density_1d_graphics <- function(zargs,
density... = NULL, offset = 0.08,
add = FALSE, plot... = NULL, ...)
{
r <- extract_1d(zargs)
x <- r$x[!is.na(r$x)] # omit missing data
horizontal <- r$horizontal
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(length(x) == 0) {
if(!add) {
## Empty plot
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
}
} else {
## Determine density values
stopifnot(0 <= offset, offset <= 0.5)
dens <- do.call(density, args = c(list(x), density...))
xvals <- dens$x
keepers <- (min(x) <= xvals) & (xvals <= max(x)) # keep those within the range of the data
x. <- xvals[keepers]
y. <- dens$y[keepers]
if(turn.out == "d" || turn.out == "l") y. <- -y.
if(horizontal) {
xlim <- range(x.)
ylim <- range(0, y.)
x <- c(xlim[1], x., xlim[2])
y <- c(0, y., 0)
## Scaling (f(y) = a * y + b with f(0) = b = offset * ylim[2] and
## f(ylim[2]) = a * ylim[2] + b = (1-offset) * ylim[2])
y <- (1-2*offset) * y + offset * if(turn.out == "d") ylim[1] else ylim[2] # scale to [offset, 1-offset] * ylim[2]
} else {
xlim <- range(0, y.)
ylim <- range(x.)
x <- c(0, y., 0)
y <- c(ylim[1], x., ylim[2])
## Scaling
x <- (1-2*offset) * x + offset * if(turn.out == "l") xlim[1] else xlim[2] # scale to [offset, 1-offset] * xlim[2]
}
## Plotting
if(add) {
usr <- par("usr")
opar <- par(usr = c(xlim, ylim)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
} else {
plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
}
polygon(x = x, y = y, ...)
}
}
##' @title Box plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name boxplot_1d_graphics
##' @aliases boxplot_1d_graphics
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param cex The character expansion factor
##' @param range A numerical value which determines how far the plot whiskers extend.
##' If NULL, the whiskers (range) grows with sample size.
##' @param axes A logicial indicating whether axes should be drawn
##' @param add A logical indicating whether this plot should be added to the last one
##' @param ... Additional arguments passed to boxplot()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
boxplot_1d_graphics <- function(zargs,
cex = 0.4, range = NULL, axes = FALSE,
add = FALSE, ...)
{
r <- extract_1d(zargs)
x <- r$x
horizontal <- r$horizontal
if(is.null(range)) { # choose 'range' depending on sample size
n <- length(x)
q25 <- qnorm(0.25)
iqr <- qnorm(0.75) - q25
range <- (q25 - qnorm(0.35/(2*n)))/iqr
}
boxplot(x, horizontal = horizontal, range = range, cex = cex,
add = add, axes = axes, ...)
}
##' @title Arrow plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name arrow_1d_graphics
##' @aliases arrow_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param angle angle in [0, 180]
##' @param length length of the arrow in [0,1] from tip to base
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to segments()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_1d_graphics <- function(zargs,
loc = c(0.5, 0.5), angle = 60, length = 0.6,
add = FALSE, plot... = NULL, ...)
{
check_zargs(zargs, "num", "turns", "width1d", "width2d")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
width1d <- zargs$width1d
width2d <- zargs$width2d
arrow <- zenarrow(turn.out, angle = angle, length = length,
coord.scale = width1d / width2d) # scaling according to aspect ratio
## Note: To see why coord.scale is like this, notice that we need
## width1d/width2d for data in [0,1]^2, for example (=> unit for 1d
## plots is by the factor width2d/width1d smaller)
arr <- loc + arrow
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
segments(x0 = rep(arr[1,2], 2), y0 = rep(arr[2,2], 2),
x1 = c(arr[1,1], arr[1,3]), y1 = c(arr[2,1], arr[2,3]), ...)
}
##' @title Rectangle plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name rect_1d_graphics
##' @aliases rect_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param width width of the rectangle (when viewed in walking direction)
##' @param height height of the rectangle (when viewed in walking direction)
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to lines()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_1d_graphics <- function(zargs,
loc = c(0.5, 0.5), width = 1, height = 1,
add = FALSE, plot... = NULL, ...)
{
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
if(!horizontal) {
tmp <- width
width <- height
height <- tmp
}
x <- c(loc[1] - width/2, loc[1] + width/2)
y <- c(loc[2] - height/2, loc[2] + height/2)
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
rect(xleft = x[1], ybottom = y[1], xright = x[2], ytop = y[2], ...)
}
##' @title Line plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name lines_1d_graphics
##' @aliases lines_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param length length of the line (in [0,1])
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to lines()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
lines_1d_graphics <- function(zargs,
loc = c(0.5, 0.5), length = 1,
add = FALSE, plot... = NULL, ...)
{
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
if(horizontal) {
x <- c(loc[1] - length/2, loc[1] + length/2)
y <- rep(loc[2], 2)
} else {
x <- rep(loc[1], 2)
y <- c(loc[2] - length/2, loc[2] + length/2)
}
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
lines(x, y = y, ...) # uses x, y
}
##' @title Label plot in 1d using R's base graphics
##' @family default 1d plot functions using R's base graphics
##' @family default 1d plot functions
##' @name label_1d_graphics
##' @aliases label_1d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param label label to be used
##' @param box logical indicating whether a box is to be drawn.
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to text() and box()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
label_1d_graphics <- function(zargs,
loc = c(0.5, 0.5), label = NULL, box = FALSE,
add = FALSE, plot... = NULL, ...)
{
r <- extract_1d(zargs)
horizontal <- r$horizontal
if(is.null(label)) label <- names(r$x) # combined group and variable label
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
srt <- if(horizontal) {
0 # note: we don't turn label upside down
} else {
if(turn.out == "r") -90 else 90
}
## Plotting
## Note: par("usr") gives x1, x2, y1, y2; this *includes* some marginal space
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot; the same if not adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
text(x = loc[1], y = loc[2], labels = label, srt = srt, ...)
if(box) box(...) # plot the box
}
##' @title Layout plot in 1d
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ... additional arguments passed to label_1d_graphics()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
layout_1d_graphics <- function(zargs, ...)
label_1d_graphics(zargs, box = TRUE, ...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot1dgraphics.R |
## Default 1d plot functions based on grid
##' @title Rug plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name rug_1d_grid
##' @aliases rug_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param length length of the rugs
##' @param width line width of the rugs
##' @param col default color of the rectangles/rugs
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
##' @note The choice of width and height is to leave the rugs enough space to not
##' touch points (so to avoid points and rugs overplotting).
rug_1d_grid <- function(zargs,
loc = 0.5, length = 0.5, width = 1e-3, col = par("fg"),
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
horizontal <- r$horizontal
lim <- r$xlim
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d" || turn.out == "l") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(horizontal) {
xlim <- lim
ylim <- 0:1
x <- x
y <- loc
height <- length
width <- width
} else {
xlim <- 0:1
ylim <- lim
y <- x
x <- loc
height <- width
width <- length
}
## Plotting
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
res <- rectGrob(x = x, y = y, width = width, height = height,
default.units = "native",
name = "rug_1d", gp = gpar(fill = col, col = col, ...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Dot plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name points_1d_grid
##' @aliases points_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param pch plotting symbol
##' @param size size of the plotting symbol
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
##' @note The default point size was chosen to match the default of graphics
points_1d_grid <- function(zargs,
loc = 0.5, pch = 21, size = 0.02,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
horizontal <- r$horizontal
lim <- r$xlim
check_zargs(zargs, "num", "turns", "ispace", "width1d", "width2d")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d" || turn.out == "l") loc <- 1-loc # when walking downwards, change both left/right and up/down
width1d <- zargs$width1d
width2d <- zargs$width2d
if(length(loc) == 1) loc <- rep(loc, length(x))
if(horizontal) {
xlim <- lim
ylim <- 0:1
x <- x
y <- loc
size <- size
} else {
ylim <- lim
xlim <- 0:1
y <- x
x <- loc
size <- size * width2d/width1d
}
## Plotting
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
res <- pointsGrob(x = x, y = y, pch = pch, size = unit(size, units = "npc"),
default.units = "native",
name = "points_1d", gp = gpar(...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Jittered dot plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name jitter_1d_grid
##' @aliases jitter_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc location in [0,1]; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param offset number in [0,0.5] determining how far off the center
##' the jittered points reach maximally
##' @param pch plotting symbol
##' @param size size of the plotting symbol
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note The default point size was chosen to match the default of graphics
##' @export
jitter_1d_grid <- function(zargs,
loc = 0.5, offset = 0.25, pch = 21, size = 0.02,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- r$x
stopifnot(0 <= offset, offset <= 0.5, 0 <= loc, loc <= 1, offset <= min(loc, 1-loc))
loc. <- loc + runif(length(x), min = -offset, max = offset)
points_1d_grid(zargs, loc = loc., pch = pch, size = size, draw = draw, ...)
}
##' @title Histogram in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name hist_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param breaks see ?hist; the default is 20 equi-width bins covering the data range
##' @param length.out number of break points if breaks = NULL
##' @param col colour of the histogram bar interiors, unless fill is specified, then
##' this is the colour of the border
##' @param fill logical passed to the underlying rectGrob()
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
hist_1d_grid <- function(zargs,
breaks = NULL, length.out = 21, col = NULL, fill = NULL,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
horizontal <- r$horizontal
check_zargs(zargs, "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
lim <- r$xlim
res <- if(all(is.na(x))) {
nullGrob()
} else {
## Colors
if(is.null(fill)) {
fill <- if(is.null(col)) "grey" else "black"
}
if(is.null(col)) col <- "black"
## Range, counts, breaks
if(is.null(breaks))
breaks <- seq(from = lim[1], to = lim[2], length.out = length.out)
binInfo <- hist(x, breaks = breaks, plot = FALSE)
binBoundaries <- binInfo$breaks
widths <- diff(binBoundaries)
heights <- binInfo$density
if(turn.out == "d" || turn.out == "l") heights <- -heights
if(horizontal) {
xlim <- lim
ylim <- range(0, heights)
} else {
xlim <- range(0, heights)
ylim <- lim
}
## Build the bins
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
binGrobs <- lapply(1:length(heights), function(i) {
left <- binBoundaries[i]
right <- binBoundaries[i+1]
height <- heights[i]
rectGrob(x = if(horizontal) left else 0,
y = if(horizontal) 0 else left,
width = if(horizontal) (right-left) else height,
height = if(horizontal) height else (right-left),
just = c("left", "bottom"), default.units = "native",
name = paste("hist_1d", "bin",i, sep = "_"),
gp = gpar(fill = fill, col = col, ...), vp = vp)
})
gTree(children = do.call(gList, binGrobs))
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Density plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name density_1d_grid
##' @aliases density_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param density... list of arguments for density()
##' @param offset numerical value in \deqn{[0, 0.5]} used to offset
##' the density within the height 1 box in which it appears
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
density_1d_grid <- function(zargs,
density... = NULL, offset = 0.08,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- r$x[!is.na(r$x)] # omit missing data
horizontal <- r$horizontal
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
lim <- r$xlim
res <- if(length(x) == 0) {
## Empty plot
nullGrob()
} else {
## Determine density values
stopifnot(0 <= offset, offset <= 0.5)
dens <- do.call(density, args = c(list(x), density...))
xvals <- dens$x
keepers <- (min(x) <= xvals) & (xvals <= max(x)) # keep those within the range of the data
x. <- xvals[keepers]
y. <- dens$y[keepers]
if(turn.out == "d" || turn.out == "l") y. <- -y.
if(horizontal) {
xlim <- range(x.)
ylim <- range(0, y.)
x <- c(xlim[1], x., xlim[2])
y <- c(0, y., 0)
## Scaling (f(y) = a * y + b with f(0) = b = offset * ylim[2] and
## f(ylim[2]) = a * ylim[2] + b = (1-offset) * ylim[2])
y <- (1-2*offset) * y + offset * if(turn.out == "d") ylim[1] else ylim[2]
# scale to [offset, 1-offset] * ylim[2]
} else {
xlim <- range(0, y.)
ylim <- range(x.)
x <- c(0, y., 0)
y <- c(ylim[1], x., ylim[2])
## Scaling
x <- (1-2*offset) * x + offset * if(turn.out == "l") xlim[1] else xlim[2] # scale to [offset, 1-offset] * xlim[2]
}
## Plotting
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
polygonGrob(x = x, y = y, name = "density_1d",
default.units = "native",
gp = gpar(...), vp = vp)
}
## Plotting
if(draw) grid.draw(res)
invisible(res)
}
##' @title Boxplot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name boxplot_1d_grid
##' @aliases boxplot_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param pch plot symbol
##' @param size size of the plot symbol
##' @param col color
##' @param lwd graphical parameter line width for whiskers and median
##' @param bpwidth width of boxplot on scale of default.units
##' @param range numerical value used to determine how far the plot whiskers extend. If
##' NULL, the whiskers (range) grows with sample size.
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return gTree grob containing the boxplot components as grobs
##' @author Marius Hofert and Wayne Oldford
##' @export
boxplot_1d_grid <- function(zargs,
pch = 21, size = 0.02,
col = NULL, lwd = 2, bpwidth = 0.5, range = NULL,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
horizontal <- r$horizontal
lim <- r$xlim
check_zargs(zargs, "width1d", "width2d", "ispace")
width1d <- zargs$width1d
width2d <- zargs$width2d
res <- if(all(is.na(x))) {
nullGrob()
} else {
## Range and color
if(is.null(range)) { # choose 'range' depending on sample size
n <- length(x)
q25 <- qnorm(0.25)
iqr <- qnorm(0.75) - q25
range <- (q25 - qnorm(0.35/(2*n)))/iqr
}
if(is.null(col)) col <- "grey" # hcl(h = 210, alpha = 0.5)
medCol <- if(col == "black") "white" else "black"
## Summary statistics
med <- median(x, na.rm = TRUE)
Q1 <- quantile(x, 0.25, na.rm = TRUE)
Q3 <- quantile(x, 0.75, na.rm = TRUE)
IQR <- Q3 - Q1
upper.fence <- Q3 + (range * IQR)
lower.fence <- Q1 - (range * IQR)
upper.adjacent.value <- max(x[x <= upper.fence])
lower.adjacent.value <- min(x[x >= lower.fence])
## upper.outliers <- x[x>upper.adjacent.value]
## lower.outliers <- x[x <lower.adjacent.value]
outliers <- x[(x < lower.adjacent.value) | (x > upper.adjacent.value)]
existOutliers <- length(outliers) != 0
## Draw the boxplot
if(horizontal) {
## Build the viewport
vp <- vport(zargs$ispace, xlim = lim)
## Build the box
highbox <- rectGrob(x = med, width = Q3-med, height = bpwidth,
default.units = "native",
just = c("left", "center"),
gp = gpar(fill = col, col = col, ...), vp = vp)
medLine <- linesGrob(x = c(med, med), y = c(0.5-bpwidth/2, 0.5+bpwidth/2),
default.units = "native", gp = gpar(fill = medCol,
col = medCol, lwd = lwd, ...),
vp = vp)
lowbox <- rectGrob(x = med, width = med-Q1, height = bpwidth,
default.units = "native", just = c("right", "center"),
gp = gpar(fill = col, col = col, ...), vp = vp)
## Build the whiskers
highadjacent <- linesGrob(x = c(upper.adjacent.value,upper.adjacent.value),
y = c(0.5 - bpwidth/5, 0.5 + bpwidth/5),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
highwhisker <- linesGrob(x = c(Q3,upper.adjacent.value),
y = c(0.5, 0.5),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
lowadjacent <- linesGrob(x = c(lower.adjacent.value,lower.adjacent.value),
y = c(0.5 - bpwidth/5, 0.5 + bpwidth/5),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
lowwhisker <- linesGrob(x = c(Q1,lower.adjacent.value),
y = c(0.5, 0.5),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
## Gather the outliers (if any)
if (existOutliers)
outlierpoints <- pointsGrob(x = outliers, y = rep(0.5, length(outliers)),
pch = pch, size = unit(size, units = "npc"),
default.units = "native",
gp = gpar(fill = col, col = col, ...),
vp = vp)
} else { # !horizontal
## Build the viewport
vp <- vport(zargs$ispace, ylim = lim)
## Build the box
highbox <- rectGrob(y = med, height = Q3-med, width = bpwidth,
default.units = "native", just = c("center", "bottom"),
gp = gpar(fill = col, col = col, ...), vp = vp)
medLine <- linesGrob(x = c(0.5-bpwidth/2, 0.5+bpwidth/2),
y = c(med, med), default.units = "native",
gp = gpar(fill = medCol, col = medCol, lwd = lwd, ...), vp = vp)
lowbox <- rectGrob(y = med, height = med-Q1, width = bpwidth,
default.units = "native",
just = c("center", "top"), gp = gpar(fill = col, col = col, ...),
vp = vp)
## Build the whiskers
highadjacent <- linesGrob(x = c(0.5 - bpwidth/5, 0.5 + bpwidth/5),
y = c(upper.adjacent.value,upper.adjacent.value),
default.units = "native",
gp = gpar(fill = col, col = col,lwd = lwd, ...), vp = vp)
highwhisker <- linesGrob(x = c(0.5, 0.5),
y = c(Q3,upper.adjacent.value),
default.units = "native",
gp = gpar(fill = col, col = col,lwd = lwd, ...), vp = vp)
lowadjacent <- linesGrob(x = c(0.5 - bpwidth/5, 0.5 + bpwidth/5),
y = c(lower.adjacent.value,lower.adjacent.value),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
lowwhisker <- linesGrob(x = c(0.5, 0.5),
y = c(Q1,lower.adjacent.value),
default.units = "native",
gp = gpar(fill = col, col = col, lwd = lwd, ...), vp = vp)
## Gather the outliers (if any)
if(existOutliers)
outlierpoints <- pointsGrob(x = rep(0.5, length(outliers)), y = outliers,
pch = pch, size = unit(size * width2d/width1d, units = "npc"),
default.units = "native",
gp = gpar(fill = col, col = col, ...),
vp = vp)
}
## Put it all together
boxplotGrobs <- if(existOutliers)
gList(lowadjacent, lowwhisker, lowbox, highbox,
## medPoint, # med must come after the boxes
medLine, highwhisker, highadjacent, outlierpoints)
else
gList(lowadjacent, lowwhisker, lowbox, highbox,
## medPoint, # med must come after the boxes
medLine, highwhisker, highadjacent)
gTree(children = boxplotGrobs, name = "boxplot_1d")
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Arrow plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name arrow_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param angle angle from the shaft to the edge of the arrow head
##' @param length length of the arrow in [0,1] from tip to base
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_1d_grid <- function(zargs,
loc = c(0.5, 0.5), angle = 60, length = 0.6,
draw = FALSE, ...)
{
check_zargs(zargs, "num", "turns", "width1d", "width2d", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
width1d <- zargs$width1d
width2d <- zargs$width2d
arrow <- zenarrow(turn.out, angle = angle, length = length,
coord.scale = width1d / width2d)
arr <- loc + arrow
## Plotting
vp <- vport(zargs$ispace)
res <- linesGrob(x = arr[1,], y = arr[2,], default.units = "npc",
name = "arrow_1d", gp = gpar(...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Rectangle plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name rect_1d_grid
##' @aliases rect_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location of the rectangle
##' @param width width of the rectangle (when viewed in walking direction)
##' @param height height of the rectangle (when viewed in walking direction)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_1d_grid <- function(zargs,
loc = c(0.5, 0.5), width = 1, height = 1,
draw = FALSE, ...)
{
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
if(!horizontal) {
tmp <- width
width <- height
height <- tmp
}
## Plotting
vp <- vport(zargs$ispace)
res <- rectGrob(x = loc[1], y = loc[2], width = width, height = height,
default.units = "npc",
name = "rect_1d", gp = gpar(...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Lines plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name lines_1d_grid
##' @aliases lines_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param length length of the line (in [0,1])
##' @param arrow list describing the arrow head
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
lines_1d_grid <- function(zargs,
loc = c(0.5, 0.5), length = 1, arrow = NULL,
draw = FALSE, ...)
{
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
horizontal <- turn.out %in% c("d", "u") # ... quicker than via extract_1d()
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
if(horizontal) {
x <- c(loc[1] - length/2, loc[1] + length/2)
y <- rep(loc[2], 2)
} else {
x <- rep(loc[1], 2)
y <- c(loc[2] - length/2, loc[2] + length/2)
}
## Plotting
vp <- vport(zargs$ispace)
res <- linesGrob(x = x, y = y, arrow = arrow,
default.units = "npc",
name = "lines_1d", gp = gpar(...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Label plot in 1d using the grid package
##' @family default 1d plot functions using the grid package
##' @family default 1d plot functions
##' @name label_1d_grid
##' @aliases label_1d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param label label to be used
##' @param cex character expansion factor
##' @param box logical indicating whether a box should be drawn around
##' the text
##' @param box.width width of the box
##' @param box.height height of the box
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
label_1d_grid <- function(zargs,
loc = c(0.5, 0.5), label = NULL, cex = 0.66,
box = FALSE, box.width = 1, box.height = 1,
draw = FALSE, ...)
{
r <- extract_1d(zargs)
horizontal <- r$horizontal
if(is.null(label)) label <- names(r$x) # combined group and variable label
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num] # turn out of current position
if(turn.out == "d") loc <- 1-loc # when walking downwards, change both left/right and up/down
if(turn.out == "r") { # when walking to the right, coordinates change and 2nd is flipped
loc <- rev(loc)
loc[2] <- 1-loc[2]
}
if(turn.out == "l") { # when walking to the left, coordinates change and 1st is flipped
loc <- rev(loc)
loc[1] <- 1-loc[1]
}
rot <- if(horizontal) {
0 # note: we don't turn label upside down
} else {
if(turn.out == "r") -90 else 90
}
## Plotting
vp <- vport(zargs$ispace)
gText <- textGrob(label = label,
x = loc[1], y = loc[2], rot = rot,
default.units = "npc",
name = "label_1d", gp = gpar(cex = cex, ...), vp = vp)
res <- if(box) {
gBox <- rectGrob(x = 0.5, y = 0.5,
width = box.width, height = box.height, # => plotting outside of viewport (space has been reserved by default ispace)
default.units = "npc",
name = "box_2d", gp = gpar(fill = 0, ...), vp = vp)
gTree(children = gList(gBox, gText)) # note: first box
} else {
gTree(children = gList(gText))
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Layout plot in 1d using the grid package
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ... additional arguments passed to label_1d_grid()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
layout_1d_grid <- function(zargs, ...)
label_1d_grid(zargs, box = TRUE, ...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot1dgrid.R |
## Default 1d plot functions based on loon
##' @title Rug plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name rug_1d_loon
##' @aliases rug_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param ... Additional parameters passed to loon::l_plot()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @note Just calls points_1d_loon with glyph = "osquare" to preserve linking
rug_1d_loon <- function(zargs, ...)
points_1d_loon(zargs, glyph = "square", ...)
##' @title Dot plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name points_1d_loon
##' @aliases points_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param linkingKey List of IDs to link on
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are
##' displayed
##' @param glyph The plot glyph
##' @param itemLabel A vector of strings to serve as the item labels
##' @param showItemLabels Logical determing whether item labels display on mouse
##' hover
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_plot()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
points_1d_loon <- function(zargs,
linkingGroup = NULL, linkingKey = NULL,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, glyph = "ocircle",
itemLabel = NULL, showItemLabels = TRUE,
parent = NULL, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
xlim <- r$xlim
horizontal <- r$horizontal
## Check for linkingGroup
## TODO: not sure we should do this here, or simply (as before) rely
## on linkingGroup being passed by zenplot.
## Alternatively linkingGroup could default to `none`
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Remove NAs
ldata <- na_omit_loon(x = x, linkingKey = linkingKey, itemLabel = itemLabel)
## Main
x <- ldata$x
linkingKey <- ldata$linkingKey
itemLabel <- ldata$itemLabel
check_zargs(zargs, "ispace")
if(horizontal) {
baseplot <- loon::l_plot(x = x, y = rep(0, length(x)),
linkingGroup = linkingGroup,
linkingKey = linkingKey,
showLabels = FALSE,
showScales = showScales,
showGuides = showGuides,
glyph = glyph,
itemLabel = itemLabel,
showItemLabels = showItemLabels,
parent = parent,
...)
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim)
} else {
baseplot <- loon::l_plot(x = rep(0, length(x)), y = x,
linkingGroup = linkingGroup,
showLabels = FALSE,
showScales = showScales,
showGuides = showGuides,
glyph = glyph,
itemLabel = itemLabel,
showItemLabels = showItemLabels,
parent = parent,
...)
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
ylim = xlim)
}
baseplot
}
##' @title Jittered dot plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name jitter_1d_loon
##' @aliases jitter_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines
##' are displayed
##' @param glyph Glyph to be used for points, default is the open circle:
##' "ocircle"
##' @param itemLabel A vector of strings to serve as the item labels
##' @param showItemLabels Logical determing whether item labels display on mouse
##' hover
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_plot()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
jitter_1d_loon <- function(zargs,
linkingGroup = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
glyph = "ocircle", itemLabel = NULL,
showItemLabels = TRUE, parent = NULL, ...)
{
r <- extract_1d(zargs)
x <- as.matrix(r$x)
x <- na.omit(x)
xlim <- r$xlim
horizontal <- r$horizontal
if(is.null(itemLabel)) {
if(!is.null(rownames(x))) {
itemLabel <- rownames(x)
} else {
itemLabel <- sapply(1:length(x),
function (i) {paste0("point", i)})
}
}
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
check_zargs(zargs, "ispace")
if(horizontal) {
baseplot <- loon::l_plot(x = x, y = runif(length(x)),
linkingGroup = linkingGroup,
showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
glyph = glyph,
itemLabel = itemLabel,
showItemLabels = showItemLabels,
parent = parent,
...)
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim)
} else {
baseplot <- loon::l_plot(x = runif(length(x)), y = x,
linkingGroup = linkingGroup,
showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
glyph = glyph,
itemLabel = itemLabel,
showItemLabels = showItemLabels,
parent = parent,
...)
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
ylim = xlim)
}
baseplot
}
##' @title Histogram in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name hist_1d_loon
##' @aliases hist_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param breaks Argument passed to hist() to get information on bins. Default
##' is 20 equi-width bins covering the range of x
##' @param color colour of the histogram bar interiors, unless fill is specified,
##' then this is the colour of the border
##' @param fill colour of the histogram bar interior if given
##' @param showStackedColors Logical determining whether
##' to show the individual point colours stacked in the histogram
##' @param showBinHandle Logical to show a handle to adjust bins
##' @param showLabels Logical determining whether axis labels are displayed
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are
##' displayed
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_hist()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
hist_1d_loon <- function(zargs,
breaks = NULL, color = NULL, fill = NULL,
showStackedColors = TRUE,
showBinHandle = FALSE, showLabels = FALSE,
linkingGroup = NULL, showScales = FALSE,
showGuides = FALSE, parent = NULL, ...)
{
## Extracting the information
r <- extract_1d(zargs)
x <- as.matrix(r$x)
xlim <- r$xlim
horizontal <- r$horizontal
loonInfo <- na_omit_loon(x = x)
x <- loonInfo$x
linkingKey <- loonInfo$linkingKey
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Main
if(all(is.na(x))) {
h <- loon::l_hist(linkingGroup = linkingGroup)
} else {
if(is.null(fill)) {
if(is.null(color)) {
colorFill <- "grey"
colorOutline <- "black"
} else {
colorFill <- color
colorOutline <- "black"
}
} else {
colorFill <- fill
if(is.null(color)) colourOutline <- "black"
}
xRange <- range(x)
if(is.null(breaks))
breaks <- seq(from = xRange[1], to = xRange[2], length.out = 21)
binInfo <- hist(x, breaks = breaks, plot = FALSE)
binBoundaries <- binInfo$breaks
h <- loon::l_hist(x = x,
yshows = 'density',
origin = binBoundaries[1],
binwidth = abs(diff(binBoundaries[1:2])),
linkingGroup = linkingGroup,
linkingKey = linkingKey,
swapAxes = !horizontal,
showBinHandle = showBinHandle,
showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
showStackedColors = showStackedColors,
colorFill = colorFill,
colorOutline = colorOutline,
parent = parent,
...)
}
## Scale
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = h,
ispace = zargs$ispace,
xlim = xlim)
## Return
h
}
##' @title Density plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name density_1d_loon
##' @aliases density_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param density.args A list of arguments for density()
##' @param method A character specifying the type of density used
##' @param lwd Line width used only when linewidth = NULL, value of 1 used
##' otherwise.
##' @param linewidth Line width of outline for density polygons (highest
##' priority)
##' @param color Colour used to fill the density when fill is NULL and to
##' outline the density when linecolor is NULL, foreground colour used
##' otherwise.
##' @param fill Colour used to fill the density polygon
##' @param linecolor Colour used for the outline of the density
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are
##' displayed
##' @param baseplot If non-null the base plot on which the plot should be
##' layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_layer()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
density_1d_loon <- function(zargs,
density.args = list(), method = c("single", "double"),
lwd = NULL, linewidth = NULL, color = NULL,
fill = NULL, linecolor = NULL, linkingGroup = NULL,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, baseplot = NULL, parent = NULL, ...)
{
## Extracting the information
r <- extract_1d(zargs)
x <- as.matrix(r$x)
x <- na_omit_loon(x)$x
xlim <- r$xlim
horizontal <- r$horizontal
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Main
if(all(is.na(x))) {
if (is.null(baseplot)) baseplot <- loon::l_plot(linkingGroup = linkingGroup)
} else {
dens <- do.call(density, args = c(list(x), density.args))
xvals <- dens$x
keepers <- xvals >= min(x) & xvals <= max(x)
xvals <- xvals[keepers]
xrange <- range(xvals)
##xvals <- (xvals - min(xrange))/diff(xrange)
yvals <- dens$y[keepers]
method <- match.arg(method)
switch(method,
"single" = {
##yvals <- yvals/max(yvals)
x <- c(min(xvals), xvals, max(xvals))
y <- c(0, yvals, 0)
},
"double" = {
x <- rep(c(min(xvals), xvals, max(xvals)), 2)
yvals <- c(c(0, -yvals, 0), c(0, yvals, 0))
yrange <- range(yvals)
y <- yvals # (yvals - min(yrange))/diff(yrange)
},
stop("Wrong 'method'"))
## Get the base plot if not supplied
if(is.null(baseplot)) {
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
}
## Sort out colours
if(is.null(fill)) {
if(is.null(color)) fill <- "grey50" else fill <- color
} # fill has a value, on to linecolor
if(is.null(linecolor)) {
if(is.null(color)) linecolor <- baseplot['foreground'] else linecolor <- color
} # linecolor has a value
## Sort out line widths
if(is.null(linewidth)) {
if(is.null(lwd)) {
## use linewidth
linewidth <- 1
} else { # use lwd
linewidth <- lwd
}
}
densityPoly <- loon::l_layer_polygon(baseplot,
x = x,
y = y,
color = fill,
linecolor = linecolor,
linewidth = linewidth,
...)
## loon::l_scaleto_layer(baseplot, densityPoly)
}
if (!horizontal) baseplot['swapAxes'] <- TRUE
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
x = x, y = y,
xlim = xlim)
baseplot
}
##' @title Boxplot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name boxplot_1d_loon
##' @aliases boxplot_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param color colour for boxplot
##' @param linecolor Colour used for the lines to draw the boxplot
##' @param lwd The parameter line width for whiskers and median and box
##' boundaries
##' @param range numerical value used to determine how far the plot whiskers
##' extend. If NULL, the whiskers (range) grows with sample size.
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines
##' are displayed
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to gpar()
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
boxplot_1d_loon <- function(zargs,
color = NULL, linecolor = NULL, lwd = 2,
range = NULL, showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, linkingGroup = NULL,
baseplot = NULL, parent, ...)
{
## Extracting the information
r <- extract_1d(zargs)
x <- as.matrix(r$x)
xlim <- r$xlim
horizontal <- r$horizontal
loonInfo <- na_omit_loon(x)
x <- loonInfo$x
linkingKey <- loonInfo$linkingKey
itemLabel <- loonInfo$itemLabel
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
if(is.null(range)) { # choose 'range' depending on sample size
n <- length(x)
q25 <- qnorm(0.25)
iqr <- qnorm(0.75) - q25
range <- (q25 - qnorm(0.35/(2*n)))/iqr
}
if(is.null(color)) color <- "grey"
medianCol <- if(color == "black") "grey90" else "black"
if (is.null(linecolor)) linecolor <- color
## Summary statistics
median <- median(x, na.rm = TRUE)
Q1 <- quantile(x, 0.25, na.rm = TRUE)
Q3 <- quantile(x, 0.75, na.rm = TRUE)
IQR <- Q3 - Q1
upper.fence <- Q3 + (range * IQR)
lower.fence <- Q1 - (range * IQR)
upper.adjacent.value <- max(x[x <= upper.fence])
lower.adjacent.value <- min(x[x >= lower.fence])
## upper.outliers <- x[x > upper.adjacent.value]
## lower.outliers <- x[x < lower.adjacent.value]
outlying <- (x < lower.adjacent.value) | (x > upper.adjacent.value)
outlierLabels <- itemLabel[outlying]
outlierLinkingKey <- linkingKey[outlying]
outliers <- x[outlying]
nOutliers <- sum(outlying)
existOutliers <- nOutliers != 0
## Get the base plot if not supplied
if(is.null(baseplot)) {
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
parent = parent)
}
## Build order matters to get the layering right.
## Build the whiskers
highadjacent <- loon::l_layer_line(baseplot,
x = c(upper.adjacent.value, upper.adjacent.value),
y = c(0.25, 0.75),
label = "Upper adjacent value",
color = linecolor,
linewidth = lwd,
...)
highwhisker <- loon::l_layer_line(baseplot,
x = c(Q3,upper.adjacent.value),
y = c(0.5, 0.5),
label = "Upper whisker",
color = linecolor,
linewidth = lwd,
...)
lowadjacent <- loon::l_layer_line(baseplot,
x = c(lower.adjacent.value,lower.adjacent.value),
y = c(0.25, 0.75),
label = "Lower adjacent value",
color = linecolor,
linewidth = lwd,
...)
lowwhisker <- loon::l_layer_line(baseplot,
x = c(Q1,lower.adjacent.value),
y = c(0.5, 0.5),
label = "Lower whisker",
color = linecolor,
linewidth = lwd,
...)
## Build the box
highbox <- loon::l_layer_rectangle(baseplot,
x = c(median, Q3),
y = c(0, 1),
label = "upper half of middle 50%",
color = color,
linecolor = linecolor,
linewidth = lwd,
...)
lowbox <- loon::l_layer_rectangle(baseplot,
x = c(median, Q1),
y = c(0, 1),
label = "lower half of middle 50%",
color = color,
linecolor = linecolor,
linewidth = lwd,
...)
medianLine <- loon::l_layer_line(baseplot,
x = c(median, median),
y = c(0, 1),
label = "Median line",
color = medianCol,
linewidth = lwd,
...)
## Gather the outliers (if any)
if (existOutliers){
if (is.null(itemLabel)){
outlierIndices <- which (x %in% outliers)
if (!is.null(rownames(x))) {
outlierLabels <- rownames(x)[outlierIndices]
} else
{outlierLabels <- sapply(outlierIndices,
function(i){
paste0("point",i)
})
}
} else outlierLabels <- itemLabel
outlierpoints <- loon::l_layer_points(baseplot,
x = outliers,
y = rep(0.5, nOutliers),
label = itemLabel,
color = color,
...)
}
## Scale
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim)
if (!horizontal) baseplot['swapAxes'] <- TRUE
## Return
baseplot
}
##' @title Arrow plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name arrow_1d_loon
##' @aliases arrow_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc The (x,y) location of the center of the arrow
##' @param length The length of the arrow
##' @param angle The angle from the shaft to the edge of the arrow head
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are
##' displayed
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_layer_line(...)
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_1d_loon <- function(zargs,
loc = c(0.5, 0.5), length = 0.6, angle = NULL,
linkingGroup = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
baseplot = NULL, parent = NULL, ...)
{
check_zargs(zargs, "width1d", "width2d")
width1d <- zargs$width1d
width2d <- zargs$width2d
if(is.null(angle)) angle <- 30 * width1d/width2d
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
arrow_2d_loon(zargs,
loc = loc, length = length, angle = angle,
linkingGroup = linkingGroup,
showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
baseplot = baseplot,
parent = parent,
...)
}
##' @title Rectangle plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name rect_1d_loon
##' @aliases rect_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc.x x-location of rectangle
##' @param loc.y y-location of rectangle
##' @param color Colour of the rectangle outline
##' @param fill Colour of the rectangle interior
##' @param lwd line width for rectangle outline
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot (ignored)
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines
##' are displayed
##' @param baseplot If non-NULL the base plot on which the plot should be
##' layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_layer_text(...)
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_1d_loon <- function(zargs,
loc.x = NULL, loc.y = NULL, color = NULL,
fill = NULL, lwd = 1,
linkingGroup = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
baseplot = NULL, parent = NULL, ...)
{
r <- extract_1d(zargs)
horizontal <- r$horizontal
xlim <- r$xlim
x <- as.matrix(r$x)
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Get the base plot if not supplied
if(is.null(baseplot)) {
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
}
if(is.null(color)) color <- baseplot['foreground']
if(is.null(fill)) fill <- baseplot['background']
## Get rectangle info now
label <- paste("Rectangle:", colnames(x))
if (is.null(loc.x)) loc.x <- 0:1
## if (is.null(loc.x)) loc.x <- c(baseplot['panX'] +
## (0.1) * baseplot['deltaX']/baseplot['zoomX'],
## baseplot['panX'] +
## (0.9) * (baseplot['deltaX']/baseplot['zoomX']))
## c(baseplot['panX'],
## baseplot['panX'] +
## (baseplot['deltaX']/baseplot['zoomX']))
## #0:1
if (is.null(loc.y)) loc.y <- 0:1
## if (is.null(loc.y)) loc.y <- c(baseplot['panY'] +
## (0.2) * (baseplot['deltaY']/baseplot['zoomY']),
## baseplot['panY'] +
## (0.8) * (baseplot['deltaY']/baseplot['zoomY']))
## c(baseplot['panY'],
## baseplot['panY'] +
## (baseplot['deltaY']/baseplot['zoomY']))
## #0:1
## Build the box
loon::l_layer_rectangle(baseplot,
x = loc.x,
y = loc.y,
label = label,
color = fill,
linecolor = color,
linewidth = lwd,
...)
if (!horizontal) baseplot['swapAxes'] <- TRUE
## Scale
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
x = loc.x, y = loc.y,
xlim = xlim)
## Return
baseplot
}
##' @title Lines plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name lines_1d_loon
##' @aliases lines_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc.x x-coordinates of the points on the line
##' @param loc.y y-coordinates of the pointson the line
##' @param color Colour of the line
##' @param lwd line width
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot (ignored)
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are
##' displayed
##' @param baseplot If non-null the base plot on which the plot should be
##' layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_layer_text(...)
##' @return A loon loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
lines_1d_loon <- function(zargs,
loc.x = NULL, loc.y = NULL,
color = NULL, lwd = 1,
linkingGroup = NULL,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, baseplot = NULL,
parent = NULL, ...)
{
r <- extract_1d(zargs)
horizontal <- r$horizontal
x <- as.matrix(r$x)
ldata <- na_omit_loon(x)
xlim <- r$xlim
x <- ldata$x
if(length(x) == 0) x <- c(0,1)
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
if(is.null(loc.x)) loc.x <- range(x)
if(is.null(loc.y)) loc.y <- c(0.5, 0.5)
## Get the base plot if not supplied
if(is.null(baseplot)) {
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
parent = parent)
}
if(is.null(color)) color <- baseplot['foreground']
loon::l_layer_line(widget = baseplot, x = loc.x, y = loc.y,
color = color, linewidth = lwd, ...)
if (!horizontal) baseplot['swapAxes'] <- TRUE
## Scale
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
x = loc.x, y = loc.y,
xlim = xlim)
## Return
baseplot
}
##' @title Label plot in 1d using the interactive loon package
##' @family default 1d plot functions using the interactive loon package
##' @family default 1d plot functions
##' @name label_1d_loon
##' @aliases label_1d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc.x x-location of the label
##' @param loc.y y-location of the label
##' @param label The label to be used
##' @param rot The rotation of the label
##' @param size The font size
##' @param box A \code{\link{logical}} indicating whether the label is to be enclosed
##' in a box.
##' @param color Color of the label (and of box when \code{box = TRUE}).
##' @param linkingGroup A string specifying the initial group of plots to be
##' linked to this plot
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines
##' are displayed
##' @param baseplot If non-null the base plot on which the plot should be
##' layered
##' @param parent The tk parent for this loon plot widget
##' @param ... Additional parameters passed to loon::l_layer_text(...)
##' @return A loon::l_plot(...)
##' @author Marius Hofert and Wayne Oldford
##' @export
label_1d_loon <- function(zargs,
loc.x = NULL, loc.y = NULL, label = NULL,
rot = NULL, size = 8, box = FALSE, color = NULL,
linkingGroup = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
baseplot = NULL, parent = NULL, ...)
{
r <- extract_1d(zargs)
horizontal <- r$horizontal
x <- as.matrix(r$x)
if(is.null(loc.y)) loc.y <- 0.5
if(is.null(loc.x)) {loc.x <- 0.5}
if(is.null(label)) label <- colnames(x)
if(is.null(rot)) rot <- if (horizontal) 0 else 90
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
parent = parent)
if(is.null(color)) color <- baseplot['foreground']
loon::l_layer_text(baseplot, text = label,
x = loc.x,
y = loc.y,
angle = rot,
size = size,
color = color,
...)
if (box) {
rect_1d_loon(zargs,
color = color,
baseplot = baseplot, parent = parent,
index="end", ...)
}
if (!horizontal) baseplot['swapAxes'] <- TRUE
## Scale
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = c(0,1), ylim = c(0,1))
## Return
baseplot
}
##' @title Layout plot in 1d using the interactive loon package
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param ... Additional arguments passed to label_1d_loon()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
layout_1d_loon <- function(zargs, ...)
label_1d_loon(zargs, box = TRUE, ...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot1dloon.R |
## Default 2d plot functions based on graphics
##' @title Plot of labels indicating adjacent groups using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name group_2d_graphics
##' @aliases group_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param glabs group labels being indexed by the plot variables
##' (and thus of length as the number of variables);
##' if NULL then they are determined with extract_2d()
##' @param sep group label separator
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param add logical indicating whether this plot should be added to the last one
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to text()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @note For performance reasons (avoiding having to call extract_2d() twice),
##' 'glabs' is an extra argument
##' @export
group_2d_graphics <- function(zargs,
glabs = NULL, sep = "\n", loc = c(0.5, 0.5),
add = FALSE, plot... = NULL, ...)
{
check_zargs(zargs, "turns", "vars", "num")
turns <- zargs$turns
vars <- zargs$vars
num <- zargs$num
ii <- range(vars[num,]) # variable index
ii <- if(turns[num-1] == "u" || turns[num] == "u") rev(ii) else ii
if(is.null(glabs)) {
glabs <- extract_2d(zargs)$glabs
} else {
len.groups <- length(unlist(zargs$x, recursive = FALSE))
if(length(glabs) != len.groups)
stop("length(glabs) has to equal the number ",len.groups," of variables in all groups together; consider rep()")
}
labs <- paste0(glabs[ii], collapse = sep) # labels (in the correct order for displaying the group change)
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot; the same if not adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
text(x = loc[1], y = loc[2], labels = labs, ...)
}
##' @title Point plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name points_2d_graphics
##' @aliases points_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param cex character expansion factor
##' @param box logical indicating whether a box should be drawn
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
points_2d_graphics <- function(zargs,
cex = 0.4, box = FALSE,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- as.matrix(r$x) # for points()
y <- as.matrix(r$y)
same.group <- r$same.group
if(same.group) {
if(!add) plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
points(x = x, y = y, cex = cex, ...)
if(box) box(...) # plot the box
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Quantile-quantile plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name qq_2d_graphics
##' @aliases qq_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param do.line logical indicating whether a line is drawn (through both
##' empirical c(0.25, 0.75)-quantiles)
##' @param lines... additional arguments passed to lines()
##' @param cex character expansion factor
##' @param box logical indicating whether a box should be drawn
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to qqplot()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @note line iff both margins are of the same *type*
##' @export
qq_2d_graphics <- function(zargs,
do.line = TRUE, lines... = NULL, cex = 0.4, box = FALSE,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- as.matrix(r$x) # for points()
y <- as.matrix(r$y)
same.group <- r$same.group
if(same.group) {
if(!add) plot_region(xlim = xlim, ylim = ylim, plot... = plot...) # plot region; uses xlim, ylim
## Calculation (see qqplot())
sx <- sort(x)
sy <- sort(y)
lenx <- length(sx)
leny <- length(sy)
if (leny < lenx)
sx <- approx(1L:lenx, sx, n = leny)$y
if (leny > lenx)
sy <- approx(1L:leny, sy, n = lenx)$y
## Plot
points(x = sx, y = sy, cex = cex, ...) # Q-Q plot
if(do.line) {
qx <- quantile(x, probs = c(0.25, 0.75), na.rm = TRUE, names = FALSE)
qy <- quantile(y, probs = c(0.25, 0.75), na.rm = TRUE, names = FALSE)
slope <- diff(qy) / diff(qx)
intercept <- qy[1] - qx[1] * slope
do.call(abline, c(list(a = intercept, b = slope), lines...))
}
if(box) box(...) # plot the box
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Density plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name density_2d_graphics
##' @aliases density_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ngrids number of grid points in each dimension.
##' Can be scalar or a length-2 integer vector.
##' @param drawlabels logical indicating whether the contours should be labelled
##' @param axes logicial indicating whether axes should be drawn
##' @param box logical indicating whether a box should be drawn
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
density_2d_graphics <- function(zargs,
ngrids = 25, drawlabels = FALSE,
axes = FALSE, box = FALSE,
add = FALSE, group... = NULL, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- r$x
y <- r$y
same.group <- r$same.group
if(same.group) {
data <- na.omit(cbind(x, y))
dens <- kde2d(data[,1], data[,2], n = ngrids, lims = c(xlim, ylim))
contour(dens$x, dens$y, dens$z, drawlabels = drawlabels,
axes = axes, add = add, ...)
if(box) box(...) # plot the box
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Axes arrows in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name axes_2d_graphics
##' @aliases axes_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param length length of the arrow head
##' @param eps distance by which the axes are moved away from the plot region
##' @param code integer code determining the kind of arrows to be drawn; see ?arrows
##' @param xpd logical or NA, determining the region with respect to which clipping
##' takes place; see ?par
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @note Inspired by https://stat.ethz.ch/pipermail/r-help/2004-October/059525.html
##' @export
axes_2d_graphics <- function(zargs,
length = 0.1, eps = 0.04, code = 2, xpd = NA,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
same.group <- r$same.group
if(same.group) {
if(!add) plot_region(xlim = xlim, ylim = ylim, plot... = plot...)
epsx <- eps * diff(xlim)
epsy <- eps * diff(ylim)
arrows(xlim[1]-epsx, ylim[1]-epsy, xlim[2]+epsx, ylim[1]-epsy,
length = length, code = code, xpd = xpd, ...) # x axis
arrows(xlim[1]-epsx, ylim[1]-epsy, xlim[1]-epsx, ylim[2]+epsy,
length = length, code = code, xpd = xpd, ...) # y axis
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Arrow plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name arrow_2d_graphics
##' @aliases arrow_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location (in (0,1)^2) of the center of the arrow
##' @param angle angle from the shaft to the edge of the arrow head
##' @param length length of the arrow in [0,1] from tip to base
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to points()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_2d_graphics <- function(zargs,
loc = c(0.5, 0.5), angle = 60, length = 0.2,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
check_zargs(zargs, "num", "turns")
turn.out <- zargs$turns[zargs$num]
if(same.group) {
arrow <- zenarrow(turn.out, angle = angle, length = length,
coord.scale = 1) # scaling according to aspect ratio
arr <- loc + arrow
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
segments(x0 = rep(arr[1,2], 2), y0 = rep(arr[2,2], 2),
x1 = c(arr[1,1], arr[1,3]), y1 = c(arr[2,1], arr[2,3]), ...)
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Rectangle plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name rect_2d_graphics
##' @aliases rect_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location (in (0,1)^2) of the center of the rectangle
##' @param width width of the rectangle as a fraction of 1
##' @param height height of the rectangle as a fraction of 1
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to rect()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_2d_graphics <- function(zargs,
loc = c(0.5, 0.5), width = 1, height = 1,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
if(same.group) {
x <- c(loc[1] - width/2, loc[1] + width/2)
y <- c(loc[2] - height/2, loc[2] + height/2)
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
rect(xleft = x[1], ybottom = y[1], xright = x[2], ytop = y[2], ...)
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Label plot in 2d using R's base graphics
##' @family default 2d plot functions using R's base graphics
##' @family default 2d plot functions
##' @name label_2d_graphics
##' @aliases label_2d_graphics
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location (in (0,1)^2) of the center of the rectangle
##' @param label label to be used
##' @param adj x (and optionally y) adjustment of the label
##' @param box logical indicating whether a box should be drawn
##' @param add logical indicating whether this plot should be added to the last one
##' @param group... list of arguments passed to group_2d_graphics (or NULL)
##' @param plot... additional arguments passed to plot_region()
##' @param ... additional arguments passed to rect()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
label_2d_graphics <- function(zargs,
loc = c(0.98, 0.05), label = NULL, adj = 1:0, box = FALSE,
add = FALSE, group... = NULL, plot... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
vlabs <- r$vlabs
check_zargs(zargs, "vars", "num")
vars <- zargs$vars
num <- zargs$num
if(same.group) {
xlab <- vlabs[vars[num, 1]]
ylab <- vlabs[vars[num, 2]]
if(is.null(label)) label <- paste0("(",xlab,", ",ylab,")")
## Plotting
opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates (easier when adding to a plot)
on.exit(par(opar))
if(!add) plot_region(xlim = 0:1, ylim = 0:1, plot... = plot...) # plot region; uses xlim, ylim
text(x = loc[1], y = loc[2], labels = label, adj = adj, ...)
if(box) box(...) # plot the box
} else {
args <- c(list(zargs = zargs, add = add), group...)
do.call(group_2d_graphics, args)
}
}
##' @title Layout plot in 2d
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ... additional arguments passed to label_2d_graphics()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @note Here we also pass '...' to group_2d_grid() (to easily adjust
##' font size etc.)
layout_2d_graphics <- function(zargs, ...)
label_2d_graphics(zargs, loc = c(0.5, 0.5), adj = rep(0.5, 2), # centered
box = TRUE, group... = list(...), ...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot2dgraphics.R |
## Default 2d plot functions based on grid
##' @title Plot of labels indicating adjacent groups using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name group_2d_grid
##' @aliases group_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param glabs group labels being indexed by the plot variables
##' (and thus of length as the number of variables);
##' if NULL then they are determined with extract_2d()
##' @param sep group label separator
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert
##' @note For performance reasons (avoiding having to call extract_2d() twice),
##' 'glabs' is an extra argument
##' @export
group_2d_grid <- function(zargs,
glabs = NULL, sep = "\n", loc = c(0.5, 0.5),
draw = FALSE, ...)
{
check_zargs(zargs, "turns", "vars", "num", "ispace")
turns <- zargs$turns
vars <- zargs$vars
num <- zargs$num
ii <- range(vars[num,]) # variable index
ii <- if(turns[num-1] == "u" || turns[num] == "u") rev(ii) else ii
if(is.null(glabs)) {
glabs <- extract_2d(zargs)$glabs
} else {
len.groups <- length(unlist(zargs$x, recursive = FALSE))
if(length(glabs) != len.groups)
stop("length(glabs) has to equal the number ",len.groups," of variables in all groups together; consider rep()")
}
labs <- paste0(glabs[ii], collapse = sep) # labels (in the correct order for displaying the group change)
## Plotting
vp <- vport(zargs$ispace)
res <- textGrob(label = labs, x = loc[1], y = loc[2],
default.units = "npc",
name = "group_2d", gp = gpar(...), vp = vp)
if(draw) grid.draw(res)
invisible(res)
}
##' @title Point plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name points_2d_grid
##' @aliases points_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param type line type
##' @param pch plot symbol
##' @param size size of the plot symbol
##' @param box logical indicating whether a box should be drawn
##' @param box.width width of the box
##' @param box.height height of the box
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note - We use names depending on the 'type' here since otherwise, if one calls it
##' once for 'p' and once for 'l', only one of them is plotted
##' - The default point size was chosen to match the default of graphics
##' @export
points_2d_grid <- function(zargs,
type = c("p", "l", "o"), pch = NULL, size = 0.02,
box = FALSE, box.width = 1, box.height = 1,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- as.matrix(r$x) # for pointsGrob()
y <- as.matrix(r$y)
same.group <- r$same.group
check_zargs(zargs, "ispace")
res <- if(same.group) {
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
if(box)
gBox <- rectGrob(x = 0.5, y = 0.5,
width = box.width, height = box.height, # => plotting outside of viewport (space has been reserved by default ispace)
just = "centre", default.units = "npc",
name = "box_2d", gp = gpar(...), vp = vp)
type <- match.arg(type)
switch(type,
"p" = {
if(is.null(pch)) pch <- 21
gPoints <- pointsGrob(x = x, y = y, pch = pch,
size = unit(size, units = "npc"),
default.units = "native",
name = "points_2d", gp = gpar(...), vp = vp)
if(box) { # create a single grob
gTree(children = gList(gBox, gPoints)) # note: first box
} else {
gTree(children = gList(gPoints))
}
},
"l" = {
gLines <- linesGrob(x = x, y = y,
default.units = "native",
name = "lines_2d", gp = gpar(...), vp = vp)
if(box) { # create a single grob
gTree(children = gList(gBox, gLines)) # note: first box
} else {
gTree(children = gList(gLines))
}
},
"o" = {
if(is.null(pch)) pch <- 20
gLines <- linesGrob(x = x, y = y,
default.units = "native",
name = "lines_2d", gp = gpar(...), vp = vp)
gPoints <- pointsGrob(x = x, y = y, pch = pch,
size = unit(size, units = "npc"),
default.units = "native",
name = "points_2d", gp = gpar(...), vp = vp)
if(box) { # create a single grob
gTree(children = gList(gBox, gLines, gPoints)) # note: first box
} else {
gTree(children = gList(gLines, gPoints))
}
},
stop("Wrong 'type'"))
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Quantile-quantile plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name qq_2d_grid
##' @aliases qq_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param do.line logical indicating whether a line is drawn (through both
##' empirical c(0.25, 0.75)-quantiles)
##' @param lines... additional arguments passed to lines()
##' @param pch plot symbol
##' @param size size of the plot symbol
##' @param box logical indicating whether a box should be drawn
##' @param box.width width of the box
##' @param box.height height of the box
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note - line iff both margins are of the same *type*
##' - The default point size was chosen to match the default of graphics
##' @export
qq_2d_grid <- function(zargs,
do.line = TRUE, lines... = NULL, pch = NULL, size = 0.02,
box = FALSE, box.width = 1, box.height = 1,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- r$x
y <- r$y
same.group <- r$same.group
check_zargs(zargs, "ispace")
res <- if(same.group) {
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim)
## Calculation (see qqplot())
sx <- sort(x)
sy <- sort(y)
lenx <- length(sx)
leny <- length(sy)
if (leny < lenx)
sx <- approx(1L:lenx, sx, n = leny)$y
if (leny > lenx)
sy <- approx(1L:leny, sy, n = lenx)$y
## Plot
if(is.null(pch)) pch <- 21
gPoints <- pointsGrob(x = sx, y = sy, pch = pch,
size = unit(size, units = "npc"),
default.units = "native",
name = "points_2d", gp = gpar(...), vp = vp) # Q-Q plot
groblist <- list(gPoints)
if(do.line) {
qx <- quantile(x, probs = c(0.25, 0.75), na.rm = TRUE, names = FALSE)
qy <- quantile(y, probs = c(0.25, 0.75), na.rm = TRUE, names = FALSE)
slope <- diff(qy) / diff(qx)
intercept <- qy[1] - qx[1] * slope
## We can't just plot that as there is no abline() in grid. Evaluating
## the line at xlim and corresponding y-values slope * xvals + intercept
## could lie very well outside the plot region.
## We solve this here *brute force*
xvals <- seq(xlim[1], xlim[2], length.out = 1024)
yvals <- slope * xvals + intercept
ok <- (xlim[1] <= xvals) & (xvals <= xlim[2]) &
(ylim[1] <= yvals) & (yvals <= ylim[2])
vals <- cbind(xvals, yvals)[ok, ]
x0.x1 <- c(vals[1,1], vals[nrow(vals),1])
y0.y1 <- c(vals[1,2], vals[nrow(vals),2])
gLines <- linesGrob(x = x0.x1, y = y0.y1,
default.units = "native", name = "lines_2d",
gp = gpar(...), vp = vp) # Q-Q line
groblist <- c(list(gLines), groblist) # append to list
}
if(box) {
gBox <- rectGrob(x = 0.5, y = 0.5,
width = box.width, height = box.height, # => plotting outside of viewport (space has been reserved by default ispace)
just = "centre", default.units = "npc",
name = "box_2d", gp = gpar(...), vp = vp)
groblist <- c(list(gBox), groblist) # append to list
}
gTree(children = do.call(gList, groblist))
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Density plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name density_2d_grid
##' @aliases density_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ngrids number of grid points in each direction. Can be scalar or
##' a length-2 integer vector.
##' @param ccol vector (which is then recycled to the appropriate length)
##' giving the color of the contours
##' @param clwd vector (which is then recycled to the appropriate length)
##' giving the line widths of the contours
##' @param clty vector (which is then recycled to the appropriate length)
##' giving the line types of the contours
##' @param box logical indicating whether a box should be drawn
##' @param box.width width of the box
##' @param box.height height of the box
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note - We use names depending on the 'type' here since otherwise, if one calls it
##' once for 'p' and once for 'l', only one of them is plotted
##' - The default point size was chosen to match the default of graphics
##' @author Marius Hofert and Wayne Oldford
##' @export
density_2d_grid <- function(zargs,
ngrids = 25, ccol = NULL, clwd = 1, clty = 1,
box = FALSE, box.width = 1, box.height = 1,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- r$x
y <- r$y
same.group <- r$same.group
check_zargs(zargs, "ispace")
res <- if(same.group) {
data <- na.omit(data.frame(x, y))
colnames(data) <- c("x", "y")
dens <- kde2d(data$x, data$y, n = ngrids, lims = c(xlim, ylim))
contours <- contourLines(dens$x, dens$y, dens$z)
levels <- sapply(contours, function(contour) contour$level) # list of contour levels
nLevels <- length(levels) # number of levels
uniqueLevels <- unique(levels) # unique levels (there could be more than one level curve with the same level)
nuLevels <- length(uniqueLevels)
if(is.null(ccol)) { # default grey scale colors
basecol <- c("grey80", "grey0")
palette <- colorRampPalette(basecol, space = "Lab")
ccol <- palette(nuLevels) # different color for each 1d plot
}
ccol <- rep_len(ccol, nuLevels)
clwd <- rep_len(clwd, nuLevels)
clty <- rep_len(clty, nuLevels)
## Match the levels in the unique levels
ccol. <- numeric(nLevels)
clwd. <- numeric(nLevels)
clty. <- numeric(nLevels)
for (i in 1:nuLevels) {
idx <- (1:nLevels)[levels == uniqueLevels[i]]
ccol.[idx] <- ccol[i]
clwd.[idx] <- clwd[i]
clty.[idx] <- clty[i]
}
## Plotting
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim, x = x, y = y)
if(box)
gBox <- rectGrob(x = 0.5, y = 0.5,
width = box.width, height = box.height, # => plotting outside of viewport (space has been reserved by default ispace)
just = "centre", default.units = "npc",
name = "box_2d", gp = gpar(...), vp = vp)
contourGrobs <- lapply(1:length(contours), # go over all contours
function(i) {
contour <- contours[[i]]
linesGrob(x = contour$x, y = contour$y,
gp = gpar(col = ccol.[i],
lwd = clwd.[i], lty = clty.[i], ...),
default.units = "native",
name = paste0("contour_",i), # note: have to be different!
vp = vp)
})
if(box) { # create a single grob
gTree(children = do.call(gList, args = c(contourGrobs, list(gBox))))
} else {
gTree(children = do.call(gList, args = contourGrobs))
}
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Axes arrow using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name axes_2d_grid
##' @aliases axes_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param angle angle of the arrow head (see ?arrow)
##' @param length length of the arrow in [0,1] from tip to base
##' @param type type of the arrow head (see ?arrow)
##' @param eps distance by which the axes are moved away from the plot region
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note Inspired by https://stat.ethz.ch/pipermail/r-help/2004-October/059525.html
##' @export
axes_2d_grid <- function(zargs,
angle = 30, length = unit(0.05, "npc"), type = "open", eps = 0.02,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
x <- r$x
y <- r$y
same.group <- r$same.group
check_zargs(zargs, "ispace")
res <- if(same.group) {
vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim, x = x, y = y)
x.grob <- linesGrob(x = unit(c(-eps, 1+eps), "npc"),
y = unit(c(-eps, -eps), "npc"),
arrow = arrow(angle = angle, length = length,
ends = "last", type = type),
name = "x_axis_2d",
gp = gpar(...), vp = vp) # x axis
y.grob <- linesGrob(x = unit(c(-eps, -eps), "npc"),
y = unit(c(-eps, 1+eps), "npc"),
arrow = arrow(angle = angle, length = length,
ends = "last", type = type),
name = "y_axis_2d",
gp = gpar(...), vp = vp) # y axis
gTree(children = gList(x.grob, y.grob)) # create a single grob
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Arrow plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name arrow_2d_grid
##' @aliases arrow_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location of the center of the arrow
##' @param angle angle from the shaft to the edge of the arrow head
##' @param length length of the arrow in [0,1] from tip to base
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_2d_grid <- function(zargs,
loc = c(0.5, 0.5), angle = 60, length = 0.2,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
check_zargs(zargs, "num", "turns", "ispace")
turn.out <- zargs$turns[zargs$num]
res <- if(same.group) {
vp <- vport(zargs$ispace)
arrow <- zenarrow(turn.out, angle = angle, length = length,
coord.scale = 1)
arr <- loc + arrow
## Plotting
linesGrob(x = arr[1,], y = arr[2,], default.units = "npc",
name = "arrow_2d", gp = gpar(...), vp = vp)
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Rectangle plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name rect_2d_grid
##' @aliases rect_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location of the rectangle
##' @param width rectangle width as a fraction of 1
##' @param height rectangle height as a fraction of 1
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_2d_grid <- function(zargs,
loc = c(0.5, 0.5), width = 1, height = 1,
group... = list(cex = 0.66), draw = FALSE, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
check_zargs(zargs, "ispace")
res <- if(same.group) {
vp <- vport(zargs$ispace)
rectGrob(x = loc[1], y = loc[2], width = width, height = height,
default.units = "npc", name = "rect_2d",
gp = gpar(...), vp = vp)
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Label plot in 2d using the grid package
##' @family default 2d plot functions using the grid package
##' @family default 2d plot functions
##' @name label_2d_grid
##' @aliases label_2d_grid
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param loc (x,y)-location in [0,1]^2; 0 corresponds to left, 1 to right (in
##' the direction of the path)
##' @param label label to be used
##' @param cex character expansion factor
##' @param just (x,y)-justification of the label
##' @param rot rotation of the label
##' @param box logical indicating whether a box should be drawn
##' @param box.width width of the box
##' @param box.height height of the box
##' @param group... list of arguments passed to group_2d_grid (or NULL)
##' @param draw logical indicating whether drawing should take place
##' @param ... additional arguments passed to gpar()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
label_2d_grid <- function(zargs,
loc = c(0.98, 0.05), label = NULL, cex = 0.66,
just = c("right", "bottom"), rot = 0,
box = FALSE, box.width = 1, box.height = 1,
group... = list(cex = cex), draw = FALSE, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
vlabs <- r$vlabs
check_zargs(zargs, "vars", "num", "ispace")
vars <- zargs$vars
num <- zargs$num
res <- if(same.group) {
xlab <- vlabs[vars[num, 1]]
ylab <- vlabs[vars[num, 2]]
if(is.null(label)) label <- paste0("(",xlab,", ",ylab,")")
vp <- vport(zargs$ispace)
gText <- textGrob(label = label,
x = loc[1], y = loc[2], just = just, rot = rot,
default.units = "npc",
name = "label_2d", gp = gpar(cex = cex, ...), vp = vp)
if(box) {
gBox <- rectGrob(x = 0.5, y = 0.5,
width = box.width, height = box.height, # => plotting outside of viewport (space has been reserved by default ispace)
default.units = "npc",
name = "box_2d", gp = gpar(...), vp = vp)
gTree(children = gList(gBox, gText)) # note: first box
} else {
gTree(children = gList(gText))
}
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_grid, args)
}
if(draw) grid.draw(res)
invisible(res)
}
##' @title Layout plot in 2d using the grid package
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param ... additional arguments passed to label_2d_grid()
##' @return grob (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @note Here we also pass '...' to group_2d_grid() (to easily adjust
##' font size etc.)
layout_2d_grid <- function(zargs, ...)
label_2d_grid(zargs, loc = c(0.5, 0.5),
just = "centre", box = TRUE, group... = list(...),
...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot2dgrid.R |
## Default 2d plot functions based on loon
##' @title Plot of labels indicating adjacent groups using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name group_2d_loon
##' @aliases group_2d_loon
##' @param zargs argument list as passed from \code{\link{zenplot}()}
##' @param glabs group labels being indexed by the plot variables
##' (and thus of length as the number of variables);
##' if NULL then they are determined with extract_2d()
##' @param sep group label separator
##' @param size plot size
##' @param rot rotation
##' @param baseplot If non-NULL the base plot on which the plot should be
##' layered
##' @param parent tk parent for this loon plot widget
##' @param ... Additional arguments passed to text()
##' @return invisible()
##' @author Marius Hofert & Wayne Oldford
##' @note For performance reasons (avoiding having to call extract_2d() twice),
##' 'glabs' is an extra argument
##' @export
group_2d_loon <- function(zargs,
glabs = NULL, sep = "\n", size = 8, rot = 0,
baseplot = NULL, parent = NULL, ...)
{
check_zargs(zargs, "turns", "vars", "num")
turns <- zargs$turns
vars <- zargs$vars
num <- zargs$num
xlim <- 0:1
ylim <- 0:1
ii <- c(min(vars[num,]), max(vars[num,])) # variable index
ii <- if(turns[num-1] == "u" || turns[num] == "u") rev(ii) else ii
if(is.null(glabs)) {
glabs <- extract_2d(zargs)$glabs
} else {
len.groups <- length(unlist(zargs$x, recursive = FALSE))
if(length(glabs) != len.groups)
stop("length(glabs) has to equal the number ",len.groups," of variables in all groups together; consider rep()")
}
labs <- paste0(glabs[ii], collapse = "\n") # labels (in the correct order for displaying the group change)
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = FALSE,
showScales = FALSE,
showGuides = FALSE,
parent = parent)
loon::l_layer_text(baseplot, text = labs,
x = xlim[1] + 0.5 * diff(xlim), y = ylim[1] + 0.5 * diff(ylim),
angle = rot, size = size, ...)
baseplot
}
##' @title Point plot in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name points_2d_loon
##' @aliases points_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param linkingGroup The initial linking group
##' @param linkingKey List of IDs to link on
##' @param glyph String determining the glyph type to be displayed for points, default is an open circle: "ocircle"
##' @param itemLabel A vector of strings to serve as the item label
##' @param showItemLabels Logical determing whether item labels display on mouse hover
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional arguments passed to loon::l_plot()
##' @return A loon plot
##' @author Marius Hofert and Wayne Oldford
##' @export
points_2d_loon <- function(zargs,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, linkingGroup = NULL,
linkingKey = NULL, glyph = "ocircle",
itemLabel = NULL, showItemLabels = TRUE,
parent = NULL, group... = NULL, ...)
{
r <- extract_2d(zargs)
x <- as.matrix(r$x)
y <- as.matrix(r$y)
xlim <- r$xlim
ylim <- r$ylim
same.group <- r$same.group
check_zargs(zargs, "ispace")
if(same.group) {
## Check for linkingGroup
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Remove NAs
ldata <- na_omit_loon(x, y, linkingKey, itemLabel)
## TODO fix box or not: if(box) box() # plot the box
## Do the plot
baseplot <- loon::l_plot(x = ldata$x, y = ldata$y,
linkingGroup = linkingGroup,
linkingKey = ldata$linkingKey,
showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
glyph = glyph,
itemLabel = ldata$itemLabel,
showItemLabels = showItemLabels,
parent = parent, ...)
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim, ylim = ylim)
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Density plot in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name density_2d_loon
##' @aliases density_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param ngrids Number of grid points in each direction. Can be scalar or
##' a length-2 integer vector.
##' @param ccol A vector (which is then recycled to the appropriate length)
##' giving the color of the contours
##' @param color Colour used fill if ccol is NULL, a grey palette is used otherwise.
##' @param clwd A vector (which is then recycled to the appropriate length)
##' giving the line widths of the contours
##' @param lwd Line width used only when clwd = NULL
##' @param linewidth Line width used when both clwd and lwd are NULL, value of 1 used otherwise.
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param linkingGroup The initial linking group
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional parameters passed to loon::l_layer_line()
##' @return invisible()
##' @author Marius Hofert and Wayne Oldford
##' @export
density_2d_loon <- function(zargs, ngrids = 25,
ccol = NULL, color = NULL, clwd = NULL, lwd = NULL,
linewidth = 1, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
linkingGroup = NULL,
baseplot = NULL, parent = NULL, group... = NULL, ...)
{
r <- extract_2d(zargs)
x <- as.matrix(r$x)
y <- as.matrix(r$y)
xlim <- r$xlim
ylim <- r$ylim
same.group <- r$same.group
if(same.group) {
## Check for linkingGroup
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Remove NAs
data <- na_omit_loon(x, y)
## TODO fix box or not: if(box) box() # plot the box
## Do the plot
dens <- kde2d(data$x, data$y, n = ngrids)
contours <- contourLines(dens$x, dens$y, dens$z)
levels <- sapply(contours, function(contour) contour$level) # list of contour levels
nLevels <- length(levels) # number of levels
uniqueLevels <- unique(levels) # unique levels (there could be more than one level curve with the same level)
nuLevels <- length(uniqueLevels)
## Sort out colours
if(is.null(ccol)) {
if(is.null(color)) {
## Use pallette of default grey scale colors
basecol <- c("grey80", "grey0")
palette <- colorRampPalette(basecol, space = "Lab")
ccol <- palette(nuLevels) # different color for each 1d plot
} else {
ccol <- color
}
}
ccol <- rep_len(ccol, nuLevels)
ccol. <- numeric(nLevels)
## Sort out line widths
if(is.null(clwd)) {
if(is.null(lwd)) {
clwd <- linewidth
} else {
clwd <- lwd
}
}
clwd <- rep_len(clwd, nuLevels)
clwd. <- numeric(nLevels)
## clty <- rep_len(clty, nuLevels) # could sort these out too using "dash"
## Match the levels in the unique levels
## clty. <- numeric(nLevels)
## Repeat as needed
for (i in 1:nuLevels) {
idx <- (1:nLevels)[levels == uniqueLevels [i]]
ccol.[idx] <- ccol[i]
clwd.[idx] <- clwd[i]
## clty.[idx] <- clty[i]
}
## Set up the base plot if needed
if (is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
parent = parent)
## Define the contours
lapply(1:length(contours), # go over all contours
function(i){
contour <- contours[[i]]
loon::l_layer_line(baseplot,
x = contour$x,
y = contour$y,
color = ccol.[i],
linewidth = clwd.[i],
label = paste("density =",levels[i]),
## lty = clty.[i],
...)
})
## Deal with ispace
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim, ylim = ylim)
## Return
baseplot
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Axes arrows in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name axes_2d_loon
##' @aliases axes_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param angle The angle of the arrow head
##' @param length The length of the arrow head
##' @param eps The distance by which the axes are moved away from the plot region
##' @param linkingGroup The initial linking group
##' @param color Colour used fill if ccol is NULL, a grey palette is used otherwise.
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional arguments passed to loon::l_plot()
##' @return the loon plot
##' @author Marius Hofert and Wayne Oldford
##' @note Inspired by https://stat.ethz.ch/pipermail/r-help/2004-October/059525.html
##' @export
axes_2d_loon <- function(zargs,
angle = 30, length = 0.05, eps = 0.02,
linkingGroup = NULL, color = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
baseplot = NULL, parent = NULL,
group... = NULL, ...)
{
r <- extract_2d(zargs)
xlim <- r$xlim
ylim <- r$ylim
same.group <- r$same.group
## Check for linkingGroup
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
## Main
if(same.group) {
epsx <- eps * diff(xlim)
epsy <- eps * diff(ylim)
exrange <- xlim + epsx * c(-1, 1)
eyrange <- ylim + epsy * c(-1, 1)
## Get the base plot if not supplied
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
if(is.null(color)) color <- baseplot['foreground']
## Draw the horizontal axis
za <- zenarrow("r", length = length, angle = angle)
maxza <- apply(za, 1, max)
maxza[2] <- 0
arrHead <- c(exrange[2], eyrange[1]) + za - maxza
x_line <- loon::l_layer_line(widget = baseplot,
x = exrange, y = rep(eyrange[1],2),
label = "Horizontal axis line",
color = color, index = "end", ...)
x_arrowhead <- loon::l_layer_line(widget = baseplot,
x = arrHead[1,], y = arrHead[2,],
label = "Horizontal axis arrowhead",
color = color, index = "end", ...)
## First create the group layer
x_arrow <- loon::l_layer_group(widget = baseplot,
label = "Horizontal axis arrow",
index = "end")
## Demote the two pieces into the x_arrow
loon::l_layer_demote(baseplot, x_arrowhead)
loon::l_layer_demote(baseplot, x_line)
## Draw the vertical axis
za <- zenarrow("u", length = length, angle = angle)
maxza <- apply(za, 1, max)
maxza[1] <- 0
arrHead <- c(exrange[1], eyrange[2]) + za - maxza
y_line <- loon::l_layer_line(widget = baseplot,
x = rep(exrange[1],2), y = eyrange,
label = "Vertical axis line",
color = color,
index = "end", ...)
y_arrowhead <- loon::l_layer_line(widget = baseplot,
x = arrHead[1,], y = arrHead[2,],
label = "Vertical axis arrowhead",
color = color,
index = "end", ...)
## First create the group layer
y_arrow <- loon::l_layer_group(widget = baseplot,
label = "Vertical axis arrow",
index = "end")
## Demote the two pieces into the x_arrow
loon::l_layer_demote(baseplot, y_arrowhead)
loon::l_layer_demote(baseplot, y_line)
## All together
axes <- loon::l_layer_group(widget = baseplot,
label = "Axis arrows",
index = "end")
loon::l_layer_demote(baseplot, y_arrow)
loon::l_layer_demote(baseplot, x_arrow)
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = xlim, ylim = ylim)
## Return
baseplot
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Arrow plot in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name arrow_2d_loon
##' @aliases arrow_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc The (x,y) location of the center of the arrow
##' @param length The length of the arrow
##' @param angle The angle from the shaft to the edge of the arrow head
##' @param linkingGroup The initial linking group
##' @param color The color
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional parameters passed to loon::l_layer_line()
##' @return the plot (invisibly)
##' @author Marius Hofert and Wayne Oldford
##' @export
arrow_2d_loon <- function(zargs,
loc = rep(0.5, 2), length = 0.2, angle = 30,
linkingGroup = NULL, color = NULL,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, baseplot = NULL, parent = NULL,
group... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
turns <- zargs$turns
num <- zargs$num
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
if(same.group) {
arr <- loc + zenarrow(turns[num], length = length, angle = angle)
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
if(is.null(color))
color <- baseplot['foreground']
loon::l_layer_line(widget = baseplot, x = arr[1,], y = arr[2,], color = color, ...)
baseplot
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Rectangle plot in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name rect_2d_loon
##' @aliases rect_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc.x x-location of rectangle
##' @param loc.y y-location of rectangle
##' @param color Colour of the rectangle outline
##' @param fill Colour of the rectangle interior
##' @param lwd line width for rectangle outline
##' @param linkingGroup The initial linking group (ignored)
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional parameters passed to loon::l_layer_text(...)
##' @return The base loon::l_plot with the added text layer
##' @author Marius Hofert and Wayne Oldford
##' @export
rect_2d_loon <- function(zargs, loc.x = NULL, loc.y = NULL, color = NULL,
fill = NULL, lwd = 1, linkingGroup = NULL,
showLabels = FALSE, showScales = FALSE,
showGuides = FALSE, baseplot = NULL,
parent = NULL, group... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
res <- if(same.group) {
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
if(is.null(color)) color <- baseplot['foreground']
if(is.null(fill)) fill <- baseplot['background']
label <- paste("Rectangle:", colnames(r$x))
if (is.null(loc.x)) loc.x <- 0:1
if (is.null(loc.y)) loc.y <- 0:1
loon::l_layer_rectangle(baseplot,
x = loc.x,
y = loc.y,
label = label,
color = fill,
linecolor = color,
linewidth = lwd,
...)
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace)
baseplot
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Label plot in 2d using the interactive loon package
##' @family default 2d plot functions using the interactive loon package
##' @family default 2d plot functions
##' @name label_2d_loon
##' @aliases label_2d_loon
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param loc The location of the label
##' @param label The label to be used
##' @param rot The rotation of the label
##' @param size The font size
##' @param box A \code{\link{logical}} indicating whether the label is to be enclosed
##' in a box.
##' @param color Color of the label (and of box when \code{box = TRUE}).
##' @param linkingGroup The initial linking group
##' @param showLabels Logical determining whether axis labels are displayed
##' @param showScales Logical determining whether scales are displayed
##' @param showGuides Logical determining whether the background guidelines are displayed
##' @param baseplot If non-null the base plot on which the plot should be layered
##' @param parent The tk parent for this loon plot widget
##' @param group... A list of arguments passed to group_2d_loon (or NULL)
##' @param ... Additional parameters passed to loon::l_layer_text(...)
##' @return The base loon::l_plot with the added text layer
##' @author Marius Hofert and Wayne Oldford
##' @export
label_2d_loon <- function(zargs,
loc = NULL, label = NULL, rot = 0, size = 8,
box = FALSE, color = NULL,
linkingGroup = NULL, showLabels = FALSE,
showScales = FALSE, showGuides = FALSE,
baseplot = NULL, parent = NULL,
group... = NULL, ...)
{
r <- extract_2d(zargs)
same.group <- r$same.group
vlabs <- r$vlabs
vars <- zargs$vars
num <- zargs$num
## Check for linkingGroup
if (is.null(linkingGroup))
linkingGroup <- paste0("zenplot parent =", parent$ID)
if(same.group) {
## TODO fix box or not: if(box) box() # plot the box
## Do the plot
if(is.null(baseplot))
baseplot <- loon::l_plot(showLabels = showLabels,
showScales = showScales,
showGuides = showGuides,
linkingGroup = linkingGroup,
parent = parent)
xlab <- vlabs[vars[num, 1]]
ylab <- vlabs[vars[num, 2]]
if(is.null(color)) color <- baseplot['foreground']
if(is.null(label)) label <- paste0("(",xlab,", ",ylab,")")
if (is.null(loc)) loc <- c(0.50, 0.25)
loon::l_layer_text(baseplot, text = label,
x = loc[1], y = loc[2], angle = rot, size = size,
color = color, ...)
if (box) {
rect_2d_loon(zargs,
color = color,
baseplot = baseplot, parent = parent,
index="end", ...)
}
check_zargs(zargs, "ispace")
l_ispace_config(baseplot = baseplot,
ispace = zargs$ispace,
xlim = c(0,1), ylim = c(0,1))
baseplot
} else {
args <- c(list(zargs = zargs), group...)
do.call(group_2d_loon, args)
}
}
##' @title Layout plot in 2d using the interactive loon package
##' @param zargs The argument list as passed from \code{\link{zenplot}()}
##' @param ... Additional arguments passed to label_2d_grid()
##' @return A loon plot
##' @author Marius Hofert and Wayne Oldford
##' @note Here we also pass '...' to group_2d_loon() (to easily adjust
##' font size etc.)
layout_2d_loon <- function(zargs, ...)
label_2d_loon(zargs, loc = c(0.5, 0.5),
box = TRUE, group... = list(...), ...)
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/plot2dloon.R |
### Graphical tools ############################################################
##' @title Defining an arrow
##' @family graphical tools
##' @param turn The direction in which the arrow will point ("l", "r", "d", "u")
##' @param length The length of the arrow in [0,1] from tip to base
##' @param angle The angle
##' @param coord.scale Scale the coordinates of the arrow
##' @return A 3-column matrix containing the (x,y) coordinates of the left
##' edge end point, the arrow head and the right edge end point
##' @author Marius Hofert
##' @export
zenarrow <- function(turn, angle = 80, length = 1, coord.scale = 1)
{
stopifnot(0 <= angle, angle <= 180)
th <- angle * pi / 180 # convert from angle to radians
## Determine head and two edges (center = (0,0)) of an arrow pointing 'right'
## Arrow head
head <- c(length * 0.5, 0) # arrow head
## Left edge (in direction of the arrow)
th2 <- th/2 # half the angle
left <- c(length * (-0.5), coord.scale * length * tan(th2)) # end point of left edge of the arrow head
## => first component ('width') is 1 * length; the unit of the second
## component is the same as the first (Cartesian coordinate system)
## Right edge (in direction of the arrow)
right <- c(left[1], -left[2]) # end point of right edge of the arrow head
## Now turn the base arrow appropriately
rot <- switch(turn,
"l" = { pi },
"r" = { 0 },
"d" = { 3*pi/2 },
"u" = { pi/2 },
stop("Wrong 'turn'"))
rot.mat <- matrix(c(cos(rot), -sin(rot), sin(rot), cos(rot)),
nrow = 2, ncol = 2, byrow = TRUE)
left <- rot.mat %*% left
right <- rot.mat %*% right
head <- rot.mat %*% head
## Return
cbind(left = left, head = head, right = right) # (2, 3)-matrix
}
##' @title Check whether functions (plot*d to zenplot()) exist
##' @param x arguments plot1d or plot2d of zenplot()
##' @return logical indicating whether x exists
##' @author Marius Hofert
##' @note Check first whether it's a function (have to rely on it being able to be evaluated,
##' cannot do more checks then) or, if a string, whether it exists
##' @export
plot_exists <- function(x) is.function(x) || existsFunction(x)
##' @title Function to set up the plot region for graphics plots
##' @family graphical tools
##' @description Auxiliary function for setting up the plot region
##' of 1d and 2d graphics plots.
##' @details This is an auxiliary function used by the
##' provided \pkg{graphics}-related 1d and 2d plots.
##' @usage plot_region(xlim, ylim, plot... = NULL)
##' @param xlim x-axis limits
##' @param ylim y-axis limits
##' @param plot... arguments passed to the underlying \code{\link{plot}()}
##' @return \code{\link{invisible}()}
##' @author Marius Hofert
##' @keywords dplot
##' @export
plot_region <- function(xlim, ylim, plot... = NULL)
{
if(is.null(plot...)) {
plot(NA, xlim = xlim, ylim = ylim, type = "n", ann = FALSE, axes = FALSE, log = "")
} else {
fun <- function(...) plot(NA, xlim = xlim, ylim = ylim, ...)
do.call(fun, plot...)
}
}
##' @title Viewport Constructing Function for Grid Functions
##' @family graphical tools
##' @name vport
##' @description Auxiliary function for constructing viewports
##' for 1d and 2d (default) plots.
##' @details This is an auxiliary function used by the provided
##' \pkg{grid}-related 1d and 2d plots.
##' @param ispace inner space (in \eqn{[0,1]}))
##' @param xlim x-axis limits; if \code{NULL}, the data limits are used.
##' @param ylim y-axis limits; if \code{NULL}, the data limits are used.
##' @param x x data (only used if \code{is.null(xlim)});
##' if \code{NULL}, \code{0:1} is used.
##' @param y y data (only used if \code{is.null(ylim)}); if \code{NULL}, \code{0:1} is used.
##' @param ... additional arguments passed to the underlying \code{\link{viewport}()}.
##' @return The \code{\link{viewport}}.
##' @keywords dplot
##' @usage vport(ispace, xlim = NULL, ylim = NULL, x = NULL, y = NULL, ...)
##' @author Marius Hofert
##' @note Ideas from dataViewport() and extendrange()
##' Omitted check:
##' if(length(ispace) != 4) ispace <- rep(ispace, length.out = 4)
##' stopifnot(0 <= ispace, ispace <= 1)
##' @export
vport <- function(ispace, xlim = NULL, ylim = NULL, x = NULL, y = NULL, ...)
{
if(is.null(xlim) && is.null(ylim) && is.null(x) && is.null(y)) {
## Non-data viewport
viewport(x = unit(ispace[2], "npc"),
y = unit(ispace[1], "npc"),
just = c("left", "bottom"),
width = unit(1-sum(ispace[c(2,4)]), "npc"),
height = unit(1-sum(ispace[c(1,3)]), "npc"))
} else {
## Data viewport
ran.x <- if(is.null(xlim)) {
if(is.null(x)) x <- 0:1
range(x, na.rm = TRUE)
} else xlim
ran.y <- if(is.null(ylim)) {
if(is.null(y)) y <- 0:1
range(y, na.rm = TRUE)
} else ylim
viewport(xscale = ran.x + c(-ispace[2], ispace[4]) * diff(ran.x),
yscale = ran.y + c(-ispace[1], ispace[3]) * diff(ran.y), ...)
}
}
## Functions to check whether a plot is a plot in one (histogram) or two variables
## These functions should actually be in 'loon'
l_is_plot <- function (plot) grepl("plot", plot)
l_is_hist <- function (plot) grepl("hist", plot)
##' @title Helper function to remove NAs for loon plots
##' @family graphical tools
##' @param x The vector of x values (required)
##' @param y The vector of y values (optional) of the same length as x;
##' if NULL then it's ignored.
##' @param linkingKey The vector of keys used to define links between points,
##' of the same length as x; if NULL it will be 0:(length(x)-1).
##' @param itemLabel The vector of labels for the points,
##' of the same length as x; if NULL it will be constructed.
##' @return A list(x, y, linkingKey, itemLabel) where any NA in x or y will
##' have been omitted from all
##' @author R. W. Oldford
##' @export
na_omit_loon <- function(x, y = NULL, linkingKey = NULL, itemLabel = NULL)
{
if (missing(x)) stop("x must be provided")
## Check for linkingKey
stopifnot(length(x) > 0)
if (is.null(linkingKey)) linkingKey <- 0:(length(x)-1) # default 0:(n-1)
## Check NA
notNA <- !is.na(x)
if (!is.null(y)) {
notNA <- notNA & !is.na(y)
y <- y[notNA,,drop = FALSE]
}
x <- x[notNA,,drop = FALSE]
linkingKey <- linkingKey[notNA]
## Fix up itemLabel
if(is.null(itemLabel)) {
itemLabel <- rownames(x)
if(is.null(itemLabel)) {
itemLabel <- sapply(linkingKey, function (key) paste0("point", key))
} else itemLabel <- itemLabel[notNA]
}
## Return
list(x = x, # if (is.null(x)) NULL else list(x),
y = y, # if (is.null(y)) NULL else list(y),
linkingKey = linkingKey, itemLabel = itemLabel)
}
##' @title Configuring a loon plot to accommodate ispace
##' @family graphical tools
##' @param baseplot The plot to be modified
##' @param ispace The inner space (in [0,1])
##' @param x The x data
##' @param y The y data
##' @param xlim The x-axis limits; if NULL, the data limits are used
##' @param ylim The y-axis limits; if NULL, the data limits are used
##' @param ... Additional arguments passed to loon::l_configure
##' @return The baseplot
##' @author R. W. Oldford
##' @export
l_ispace_config <- function(baseplot, ispace = NULL,
x = NULL, y = NULL, xlim = NULL, ylim = NULL, ...)
{
if (is.null(ispace)) ispace <- rep(0.2, 4)
if(length(ispace) != 4) ispace <- rep(ispace, length.out = 4)
stopifnot(0 <= ispace, ispace <= 1)
## x values
if (is.null(x)) x <- baseplot['x']
xrange <- if(is.null(xlim)) {
if (is.null(x)| length(x) == 0) x <- 0:1
range(x, na.rm = TRUE)
} else xlim
if (diff(xrange) == 0) {
xrange <- xrange + c(-1,1)
}
deltaXrange <- diff(xrange) * (1 + sum(ispace[c(2,4)]))
xLeft <- xrange[1] - ispace[2] * diff(xrange)
## y values
if (l_is_plot(baseplot)) {
if (is.null(y)) y <- baseplot['y']
yrange <- if(is.null(ylim)) {
if (is.null(y)| length(y) == 0) y <- 0:1
range(y, na.rm = TRUE)
} else ylim
} else
yrange <- c(baseplot['panY'],
baseplot['panY'] + baseplot['deltaY']/baseplot['zoomY'])
if (diff(yrange) == 0) yrange <- yrange + c(-1,1)
deltaYrange <- diff(yrange) * (1 + sum(ispace[c(1,3)]))
yBottom <- yrange[1] - ispace[1] * diff(yrange)
## The configuration
loon::l_configure(baseplot,
panX = xLeft, panY = yBottom,
zoomX = baseplot['deltaX']/ deltaXrange,
zoomY = baseplot['deltaY']/ deltaYrange, ...)
## Return
baseplot
}
### Technical tools ############################################################
##' @title Converting an Occupancy Matrix
##' @description Convert an occupancy matrix to matrix with different symbols.
##' @family zenplot technical tools
##' @param x an occupancy \code{\link{matrix}} consisting of the
##' \code{\link{character}} \code{""} (unoccupied), \code{"l"} (left),
##' \code{"r"} (right), \code{"d"} (down) or \code{"u"} (up) as returned by
##' \code{\link{zenplot}()}.
##' @param to a \code{\link{vector}} of symbols to which \code{""},
##' \code{"l"}, \code{"r"}, \code{"d"} and \code{"u"}
##' should be mapped.
##' @return \code{\link{matrix}} as the occupancy matrix but with entries replaced
##' by those in \code{to}.
##' @author Marius Hofert
##' @export
##' @examples
##' ## Generate some data
##' n <- 1000 # sample size
##' d <- 20 # dimension
##' set.seed(271) # set seed (for reproducibility)
##' x <- matrix(rnorm(n * d), ncol = d) # i.i.d. N(0,1) data
##'
##' ## Extract the occupancy matrix from a zenplot
##' res <- zenplot(x)
##' (occ <- res[["path"]][["occupancy"]])
##'
##' ## Convert the occupancy matrix
##' convert_occupancy(occ)
##' @keywords utilities
##'
convert_occupancy <- function(x, to = c("", "<", ">", "v", "^"))
{
stopifnot(x %in% c("", "l", "r", "d", "u"), length(to) == 5)
new.vals <- to[ match(x, table = c("", "l", "r", "d", "u")) ]
if(is.matrix(x)) {
matrix(new.vals, ncol = ncol(x))
} else {
new.vals
}
}
##' @title Auxiliary Function for Constructing Default n2dcols
##' @family zenplot technical tools
##' @param n2dplots The number of variates (= nfaces)
##' @param method One of "letter", "square", "A4", "golden", "legal"
##' @return An odd integer for n2dcols
##' @author Wayne Oldford
##' @export
n2dcols_aux <- function(n2dplots, method = c("letter", "square", "A4", "golden", "legal"))
{
method <- match.arg(method)
scaling <- switch(method,
"golden" = (1 + sqrt(5))/2,
"square" = 1,
"letter" = 11/8.5,
"legal" = 14/8.5,
"A4" = sqrt(2),
stop("Wrong 'method'"))
n2dcols <- max(3,
## - n2dcol is never less than 3
## - n2dplots = (ncols - 1) * nrows (one column is essentially missing
## due to missing plots at alternating sides at the left/right border)
round(0.5 * (1 + sqrt( 1 + 4 * n2dplots / scaling)))
## This used to be (but no justification known):
## round(0.5 * (1 + sqrt( 1 + 4 * (n2dplots - 1) / scaling)))
)
if ((n2dcols %% 2) == 0) n2dcols + 1 else n2dcols # the default should be odd
}
##' @title Check the Turns (Number/Type)
##' @family zenplot technical tools
##' @param turns The turns
##' @param n2dplots The number of 2d plots
##' @param first1d A logical indicating whether the first 1d plot should be plotted
##' @param last1d A logical indicating whether the last 1d plot should be plotted
##' @return TRUE (unless it fails)
##' @author Marius Hofert
##' @export
turn_checker <- function(turns, n2dplots, first1d, last1d)
{
## Check the type of the turns
if(!is.character(turns) || !all(turns %in% c("d", "u", "r", "l")))
stop("'turns' not all in 'd', 'u', 'r' or 'l'")
## Check the length of the turns
nturns <- length(turns)
l <- as.numeric(!first1d) + as.numeric(!last1d) # 0 (first1d = last1d = TRUE), 1 (precisely one FALSE) or 2 (first1d = last1d = FALSE)
if(nturns != 2 * n2dplots - l + 1)
stop("Number of turns (= ",nturns,") is unequal to 2 * 'n2dplots' - ",l," + 1 = ",2*n2dplots-l+1)
TRUE
}
##' @title Check Argument for Being a Vector, Matrix, Data Frame or a List of such
##' @family zenplot technical tools
##' @param x A vector, matrix, data.frame or list of such
##' @return A logical indicating whether x is of the above type
##' @author Marius Hofert
##' @export
is.standard <- function(x) {
if(!is.vector(x, mode = "list")) { # has to be a vector, matrix or data.frame
is.vector(x) || is.matrix(x) || is.data.frame(x)
} else { # recursion
all(vapply(x, is.standard, NA))
}
}
##' @title Determine the number of columns if is.standard(x)
##' @family zenplot technical tools
##' @param x A numeric vector, matrix, data.frame or a list of such.
##' @return The number of data columns of 'x'
##' @author Marius Hofert
##' @export
num_cols <- function(x)
{
if(!is.standard(x))
stop("'x' must be a vector, matrix, data.frame, or a list of such.")
if(is.vector(x, mode = "list")) {
sum(sapply(x, num_cols))
} else { # 'x' must be a vector, matrix or data.frame
if(is.vector(x) || is.data.frame(x)) x <- as.matrix(x)
ncol(x)
}
}
### Tools for constructing your own plot1d and plot2d functions ################
##' @title Plot Indices of the Current Plot
##' @family tools for constructing your own plot1d and plot2d functions
##' @description Determining the indices of the x and y variables of the current plot
##' @details This is an auxiliary function useful, for example, when writing
##' user-provided 1d and 2d plot functions.
##' @keywords datagen
##' @usage plot_indices(zargs)
##' @param zargs argument list as passed from \code{\link{zenplot}()}.
##' This must at least contain \code{vars} and \code{num}; see
##' \code{\link{zenplot}()} for an explanation of these variables..
##' @return A \code{numeric(2)} containing the indices of the x and y variables to
##' be plotted in the current plot (the plot with number \code{num}). If
##' the current plot is a 2d plot, the same variable is used twice.
##' @author Marius Hofert
##' @note This is exported so that one doesn't always have to figure
##' out whether the variables (axes) in the current plot need
##' to be switched manually.
##' @export
plot_indices <- function(zargs)
zargs$vars[zargs$num,] # access 2-column matrix of plot variables at current plot number
##' @title Auxiliary function for burst()
##' @family tools for constructing your own plot1d and plot2d functions
##' @param x A vector, matrix or data.frame (or a (pure) list, but that we don't use here)
##' @param labs The variable labels:
##' - if NULL, no labels are used
##' - if of length 1, use this label and append 1:ncol(x)
##' but only if x doesn't have any column names (otherwise use the latter)
##' - if of length ncol(x), use that
##' but only if x doesn't have any column names (otherwise use the latter)
##' @return 'x' as a list of named columns
##' @author Marius Hofert
##' @note - Performance critical (no checks here)
##' - Data frames always have default names. They are possibly
##' ugly but we have to use them here as we cannot
##' determine whether they were assigned automatically or
##' on purpose.
##' @export
burst_aux <- function(x, labs = "V")
{
## Construct labels
if(is.vector(x)) x <- as.matrix(x)
nc <- ncol(x)
if(is.null(labs)) {
labs. <- rep("", nc) # no names
} else {
labs. <- colnames(x)
if(is.null(labs.)) { # ... then construct the labels
labs. <- if(length(labs) == 1) {
paste0(labs, seq_len(nc)) # construct labels
} else labs # must be of the right length then
}
}
## Split 'x' and use correct labels
x <- if(is.matrix(x)) {
.Call(col_split, x)
} else { # works for data.frame (= lists of columns; and (general) lists)
unclass(x)
}
names(x) <- labs. # put labels in
x # return
}
##' @title Splitting an Input Object into a List of Columns
##' @family tools for constructing your own plot1d and plot2d functions
##' @description Splits a (numeric/logical/character) vector, matrix,
##' data.frame or a list of such into a list of columns, with corresponding
##' group and variable information as well as labels.
##' This is an auxiliary function for checking and converting the data argument of zenplot().
##' @usage burst(x, labs = list())
##' @param x A \code{\link{numeric}} \code{\link{vector}}, \code{\link{matrix}},
##' \code{\link{data.frame}} or, for \code{burst()}, a \code{\link{list}} of such.
##' @param labs Either \code{\link{NULL}}
##' (in which case neither group nor variable labels are used or computed) or
##' a list with components
##'
##' \code{group} - the group label basename or labels for the groups
##' (or \code{\link{NULL}} for no group labels)
##'
##' \code{var} - the variable label basename or labels for the variables
##' (or \code{\link{NULL}} for no variable labels)
##'
##' \code{sep} - the string used as the separator between group and
##' variable labels
##'
##' \code{group2d} - a \code{\link{logical}} indicating whether labels of
##' \code{group_2d_*()} plots are affected by \code{group = NULL} (or printed anyway)
##'
##' If any of these components is not given, it is set to the defaults as described in
##' \code{\link{zenplot}()}.
##' Note that if at least one (group or variable) label is given in \code{x},
##' then those (original) labels will be used.
##' If labs = NULL, neither group nor variable labels are used.
##'
##' @return A \code{\link{list}} with components
##'
##' \code{xcols} - a list containing the column vectors of \code{x}
##'
##' \code{groups} - the group number for each column of \code{x}
##'
##' \code{vars} - the variable number (within each group) for each column of \code{x}
##'
##' \code{glabs} - the group label for each column of \code{x}
##'
##' \code{labs} - the group and variable labels for each column of \code{x}
##' @examples
##' ## Unnamed list of (some named, some unnamed) valid components
##' A <- matrix(1:12, ncol = 3)
##' x <- list(A, 1:4, as.data.frame(A))
##'
##' burst(x, labs = list(group = "G", var = "V", sep = ", "))
##' burst(x) # the same defaults as above
##' burst(x, labs = list(sep = " ")) # only changing the separator
##' ## Note: - No group labels are given in 'x' and thus they are constructed
##' ## in the above call
##' ## - The variable names are only constructed if not given
##'
##' burst(x, labs = list(group = ""))
##' burst(x, labs = list(group = NULL, group2d = TRUE)) # no group labels
##' ## Note: There's no effect of 'group2d = TRUE' visible here as
##' ## 'x' doesn't contain group labels
##'
##' burst(x, labs = list(group = NULL)) # no group labels unless groups change
##' burst(x, labs = list(var = NULL)) # no variable labels
##' burst(x, labs = list(group = NULL, var = NULL)) # neither one
##' burst(x, labs = NULL) # similarly, without any labels at all
##'
##' ## Named list
##' x <- list(mat = A, vec = 1:4, df = as.data.frame(A))
##' burst(x)
##' ## Note: - The given group labels are used
##' ## - The variable names are only constructed if not given
##'
##' burst(x, labs = list(group = NULL, group2d = TRUE)) # no group labels
##' burst(x, labs = list(group = NULL)) # no group labels unless groups change
##' ## Note: Now the effect of 'group2d' is visible.
##'
##' ## Partially named list
##' x <- list(mat = A, vec = 1:4, as.data.frame(A))
##' burst(x)
##' burst(x, labs = list(group = NULL, group2d = TRUE)) # no group labels
##' burst(x, labs = list(group = NULL)) # no group labels unless groups change
##' burst(x, labs = list(var = NULL)) # no variable labels
##' burst(x, labs = list(group = NULL, var = NULL)) # only group labels and only if groups change
##' burst(x, labs = NULL) # neither group nor variable labels
##' @keywords datagen
##' @author Marius Hofert
##' @note Performance critical
##' @export
burst <- function(x, labs = list())
{
## Checks
if(!is.standard(x))
stop("'x' must be a vector, matrix, data.frame, or a list of such.\nIf not, consider writing your own 'plot1d' and 'plot2d'.")
if(!is.null(labs)) {
## With this construction, the user gets the following defaults
## even when (s)he only specifies less than the three components
nms <- names(labs)
if(all(is.na(pmatch("group", table = nms, duplicates.ok = TRUE))))
labs$group <- "G"
if(all(is.na(pmatch("var", table = nms, duplicates.ok = TRUE))))
labs$var <- "V"
if(all(is.na(pmatch("sep", table = nms, duplicates.ok = TRUE))))
labs$sep <- ", "
if(all(is.na(pmatch("group2d", table = nms, duplicates.ok = TRUE))))
labs$group2d <- FALSE
}
## Distinguish the cases
if(is.vector(x, mode = "list")) { # proper list (and not a data.frame)
ngrps <- length(x) # number of groups (=number of sublists)
if(ngrps == 0) stop("'x' has to have positive length.")
## Burst all groups
x. <- x # dummy for calling burst_aux() on
names(x.) <- NULL # remove names for burst as these group names show up in variable names otherwise
col.lst <- lapply(x., burst_aux, labs = if(is.null(labs)) NULL else labs[["var"]])
xcols <- unlist(col.lst, recursive = FALSE) # x as a list of columns
gsizes <- vapply(col.lst, length, NA_real_) # group sizes
groups <- rep(1:ngrps, times = gsizes) # group numbers
vars <- unlist(lapply(gsizes, seq_len), use.names = FALSE) # variable numbers
vlabs <- if(is.null(labs)) NULL else names(xcols) # variable labels; unlist(lapply(col.lst, FUN = names), use.names = FALSE)
## Build group labels
## - If is.null(labs[["group"]]) and labs[["group2d"]] = TRUE, omit group labels
## - If no group labels are given at all, construct them;
## - If some group labels are given, use (only) them and omit the others
glabs <- if(is.null(labs)) {
NULL
} else if(is.null(labs[["group"]]) && labs[["group2d"]]) {
r <- rep("", ngrps)
r[groups] # expand
} else {
nms <- names(x) # use the names of 'x' as group labs, or, if NULL, build them
r <- if(is.null(nms)) {
labs.group <- labs[["group"]]
if(length(labs.group) == 1) { # if of length 1, append number
paste0(labs.group, 1:ngrps)
} else { # otherwise, use that
## stopifnot(length(labs.group) == ngrps)
labs.group
}
} else nms
r[groups] # expand
}
## Build joint labels used for 'x' only (unless is.null(labs))
if(!is.null(labs)) {
is.null.labs.group <- is.null(labs[["group"]])
is.null.labs.var <- is.null(labs[["var"]])
labs <- if(is.null.labs.group && is.null.labs.var) {
character(length(xcols)) # no labels
} else { # if at least one is given (not both NULL)
if(is.null.labs.group) { # only use var labels
vlabs
} else if(is.null.labs.var) { # only use group labels
glabs
} else { # use both labels
trimws(paste(glabs, vlabs, sep = labs[["sep"]]))
}
}
names(xcols) <- labs # use these group and variable labels as labels of the columns
}
} else { ## if(is.vector(x) || is.matrix(x) || is.data.frame(x)) {
xcols <- burst_aux(x, labs = if(is.null(labs)) NULL else labs[["var"]]) # columns with names
l <- length(xcols)
groups <- rep(1, l)
vars <- seq_len(l)
glabs <- NULL
vlabs <- names(xcols)
} ## else stop("Wrong 'x'.")
## Return result
list(xcols = xcols, # list of columns (with 'full labels' = group and variable labels)
groups = groups, # group numbers
vars = vars, # variable numbers
glabs = glabs, # group labels (NULL unless 'x' is a list)
vlabs = vlabs) # variable labels
}
##' @title A list of columns
##' @param x A list of columns
##' @return A list where each column is converted to data (range() works,
##' can be plotted, etc.)
##' @author Marius Hofert
##' @note See plot.default -> xy.coords()
##' @export
as_numeric <- function(x)
lapply(x, function(x.) {
if (is.language(x.)) {
if (inherits(x., "formula") && length(x.) == 3) {
x. <- eval(x.[[2L]], environment(x.))
} else stop("Invalid first argument.")
} else if (is.matrix(x.) || is.data.frame(x.)) {
x. <- data.matrix(x.)[,1]
} else {
if (is.factor(x.)) x. <- as.numeric(x.)
}
if (inherits(x., "POSIXt")) x. <- as.POSIXct(x.)
as.double(x.)
})
##' @title Checking whether certain arguments appear in zargs
##' @family tools for constructing your own plot1d and plot2d functions
##' @param zargs The argument list as passed from zenplot()
##' @param ... The arguments to be checked for presence in zargs
##' @return A logical indicating whether some arguments are missing in zargs
##' @author Marius Hofert
##' @export
check_zargs <- function(zargs, ...)
{
args <- list(...)
miss <- args[which(!(args %in% names(zargs)))]
missSome <- length(miss) > 0
if(missSome)
stop("Missing arguments ",paste(sQuote(miss), collapse = ", "),
". Consider providing your own functions.")
missSome
}
##' @title Extracting information for our default/provided plot1d()
##' @family tools for constructing your own plot1d and plot2d functions
##' @family data extraction functions to build plots
##' @family default 1d plot functions
##' @param zargs The argument list as passed from \code{\link{zenplot}()}.
##' This must at least contain \code{x}, \code{orientations},
##' \code{vars}, \code{num}, \code{lim} and \code{labs};
##' see \code{\link{zenplot}()} for an explanation of these variables.
##' @return A list \code{\link{list}} with
##' \describe{
##' \item{\code{x}:}{the data to be plotted in the 1d plot}
##' \item{\code{xcols}:}{a list with all columns of \code{x}}
##' \item{\code{groups}:}{the group numbers for each column of \code{x}}
##' \item{\code{vars}:}{the variable numbers for each column of \code{x}}
##' \item{\code{glabs}:}{the group labels for each column of \code{x}}
##' \item{\code{vlabs}:}{the variable labels for each column of \code{x}}
##' \item{\code{horizontal}:}{a \code{\link{logical}} indicating
##' whether the plot is horizontal or vertical, and}
##' \item{\code{xlim}:}{the axis limits.}
##' }
##'
##' @details This is an auxiliary function called on \code{zargs} within any
##' 1d plotting function (e.g. \code{\link{hist_1d_grid}},
##' \code{\link{density_1d_graphics}}, or \code{\link{points_1d_loon}})
##' to extract the 1d data from \code{zargs} needed for plotting.
##' For performance reasons, no checking of the input object is done.
##' @examples
##' ## This function is used within the default (any user defined)
##' ## 1d plots
##' my_1d_plot <- function(zargs, your_name = "Bob", ...) {
##' data_1d <- extract_1d(zargs)
##' msg <- paste("Components of zargs available",
##' "to construct a 1d plot for ",
##' your_name)
##' print(msg)
##' ## just print the names of the data components
##' ## which you might want to use in your plot
##' print(names(data_1d))
##' ## You might have to draw your 1d plot differently depending
##' ## upon whether it is to appear horizontally or vertically
##' if (data_1d$horizontal) {
##' print("This plot would be horizontal")
##' } else {
##' print("This one would be vertical")
##' }
##' ## You can plot whatever you want using the information in
##' ## could use any of these to construct any 1d plot you want
##' ## using R's graphics or any of zemplot's built in 1d plots.
##' ##
##' ## For example, here we use zenplot's base graphics functions
##' ## First a histogram
##' hist_1d_graphics(zargs, ...)
##' ## to which we add the variable label
##' label_1d_graphics(zargs, add = TRUE, col = "red", ...)
##' ## similar functions could be called for the other packages.
##' ## You can print the source of anyone of the default functions
##' ## to get some idea of managing details.
##' }
##'
##' ## And now try it out
##' zenplot(iris[,1:3], plot1d = my_1d_plot)
##'
##' @author Marius Hofert and Wayne Oldford
##' @note Performance critical
##' @export
extract_1d <- function(zargs)
{
## Checks
check_zargs(zargs, "x", "orientations", "vars", "num", "lim", "labs")
## Extract quantities
x <- zargs$x
orientations <- zargs$orientations
vars <- zargs$vars
lim <- zargs$lim
labs <- zargs$labs
num <- zargs$num
## Burst x and cache result
if(!exists("burst.x", envir = .zenplots_burst_envir) || num == 1) {
xburst <- burst(x, labs = labs) # burst 'x' (=> xcols (with glabs + vlabs), groups, vars, glabs, vlabs)...
assign("burst.x", xburst, envir = .zenplots_burst_envir) # ... and cache it
} else {
xburst <- get("burst.x", envir = .zenplots_burst_envir) # get it...
if(num == nrow(vars)) rm("burst.x", envir = .zenplots_burst_envir) # ... but remove it again after the last plot
## Note: This rm() is only for the case when extract_*d() is called separately.
## In general, 'burst.x' is removed from .zenplots_burst_envir in zenplot()
## as extract_*d() might not be called on last plot (e.g., if plot1d is
## user-provided and does not call extract_*d() or if last1d = FALSE etc.)
}
## Pick out the plot variable index
ix <- vars[num,1] # index of x
## Pick out the data
xcols <- xburst$xcols
xcols. <- as_numeric(xcols) # possibly transform all columns so that range() etc. works
x. <- data.frame(xcols.[[ix]]) # (possibly transformed) data x to be plotted
## => Conversion to data.frame allows for column names to be passed through
names(x.) <- names(xcols[ix])
## Determine whether the plot is horizontal
horizontal <- orientations[num] == "h"
## Determine xlim, ylim
lim.method <- if(is.numeric(lim) && length(lim) == 2) "fixed" else lim
finite_range <- function(z) range(z[sapply(z, is.finite)]) # see https://stackoverflow.com/questions/8173094/how-to-check-a-data-frame-for-any-non-finite
switch(lim.method,
"fixed" = {
xlim <- lim
},
"individual" = {
xlim <- if(all(is.na(x.))) 0:1 else finite_range(x.) # adapted from plot.default()
},
"groupwise" = {
if(is.list(x) && !is.data.frame(x)) { # multiple groups
x.. <- unlist(xcols.[xburst$groups == xburst$groups[ix]]) # all x's belonging to the current group
xlim <- if(all(is.na(x..))) 0:1 else finite_range(x..)
} else { # no groups = only one group = global
ax <- vars[,1] # all x indices
axd <- unlist(xcols.[ax]) # all x data; need the unlisted version here for is.finite()
xlim <- if(all(is.na(axd))) 0:1 else finite_range(axd)
}
},
"global" = {
ax <- vars[,1] # all x indices
axd <- unlist(xcols.[ax]) # all x's; need the unlisted version here for is.finite()
xlim <- if(all(is.na(axd))) 0:1 else finite_range(axd)
},
stop("Wrong 'lim.method'."))
## Return
c(x = list(x.), # this way we keep the column labels
xburst, # components returned by burst(): xcols (with glabs + vlabs), groups, vars, glabs, vlabs
horizontal = list(horizontal),
list(xlim = xlim))
}
##' @title Extracting information for our default/provided plot2d()
##' @family tools for constructing your own plot1d and plot2d functions
##' @family data extraction functions to build plots
##' @family default 2d plot functions
##' @param zargs The argument list as passed from \code{\link{zenplot}()}.
##' This must at least contain \code{x}, \code{vars}, \code{num}, \code{lim} and
##' \code{labs} (for \code{extract_2d()}); see \code{\link{zenplot}()}
##' for an explanation of these variables.
##' @return A list \code{\link{list}} with
##' \describe{
##' \item{\code{x} and \code{y}:}{the data to be plotted in the 2d plot}
##' \item{\code{xcols}:}{a list with all columns of \code{x}}
##' \item{\code{groups}:}{the group numbers for each column of \code{x}}
##' \item{\code{vars}:}{the variable numbers for each column of \code{x}}
##' \item{\code{glabs}:}{the group labels for each column of \code{x}}
##' \item{\code{vlabs}:}{the variable labels for each column of \code{x}}
##' \item{\code{xlim} and \code{ylim}:}{the x-axis and y-axis limits, and}
##' \item{\code{same.group}:}{a \code{\link{logical}} indicating
##' whether the x and y variables belong to the same group.}
##' }
##'
##' @details This is an auxiliary function called on \code{zargs} within any
##' 1d plotting function (e.g. \code{\link{hist_1d_grid}},
##' \code{\link{density_1d_graphics}}, or \code{\link{points_1d_loon}})
##' to extract the 1d data from \code{zargs} needed for plotting.
##' For performance reasons, no checking of the input object is done.
##' @examples
##' ## This function is used within the default (any user defined)
##' ## 2d plot functions
##' ##
##' my_2d_plot <- function(zargs, your_name = "BillyBob", ...) {
##' data_2d <- extract_2d(zargs)
##' msg <- paste("Components of zargs available",
##' "to construct a 2d plot for ",
##' your_name)
##' print(msg)
##' ## just print the names of the data components
##' ## which you might want to use in your plot
##' print(names(data_2d))
##'
##' ## You can plot whatever you want using the information in
##' ## could use any of these to construct any 1d plot you want
##' ## using R's graphics or any of zemplot's built in 1d plots.
##' ##
##' ## For example, here we could use
##' ## use zenplot's base graphics functions
##' ## First a scatterplot
##' points_2d_graphics(zargs, ...)
##' ## to which we overlay density contours
##' density_2d_graphics(zargs, add = TRUE, col = "steelblue", ...)
##' ## similar functions could be called for the other packages.
##' ## You can print the source of anyone of the default functions
##' ## to get some idea of managing details.
##' }
##'
##' ## And now try it out
##' zenplot(iris, plot2d = my_2d_plot)
##' @author Marius Hofert and Wayne Oldford
##' @note Performance critical
##' @export
extract_2d <- function(zargs)
{
## Checks
check_zargs(zargs, "x", "vars", "num", "lim", "labs")
## Extract quantities (all but num; see below)
x <- zargs$x
vars <- zargs$vars
lim <- zargs$lim
labs <- zargs$labs
num <- zargs$num
## Burst x and cache result
if(!exists("burst.x", envir = .zenplots_burst_envir) || num == 1) {
xburst <- burst(x, labs = labs) # burst 'x' (=> xcols (with glabs + vlabs), groups, vars, glabs, vlabs)...
assign("burst.x", xburst, envir = .zenplots_burst_envir) # ... and cache it
} else {
xburst <- get("burst.x", envir = .zenplots_burst_envir) # get it...
if(num == nrow(vars)) rm("burst.x", envir = .zenplots_burst_envir) # ... but remove it again after the last plot
## Note: This rm() is only for the case when extract_*d() is called separately.
## In general, 'burst.x' is removed from .zenplots_burst_envir in zenplot()
## as extract_*d() might not be called on last plot (e.g., if plot1d is
## user-provided and does not call extract_*d() or if last1d = FALSE etc.)
}
## Pick out the plot variable indices
ix <- vars[num,1] # index of x
iy <- vars[num,2] # index of y
## Pick out the data
xcols <- xburst$xcols
xcols. <- as_numeric(xcols) # possibly transform all columns so that range() etc. works
x. <- data.frame(xcols.[[ix]]) # (possibly transformed) data x to be plotted
y. <- data.frame(xcols.[[iy]]) # (possibly transformed) data y to be plotted
## => Conversion to matrix allows for column names
names(x.) <- names(xcols[ix])
names(y.) <- names(xcols[iy])
## Determine whether they are in the same group and compute xlim, ylim
same.group <- xburst$groups[ix] == xburst$groups[iy]
lim.method <- if(is.numeric(lim) && length(lim) == 2) "fixed" else lim
finite_range <- function(z) range(z[sapply(z, is.finite)]) # see https://stackoverflow.com/questions/8173094/how-to-check-a-data-frame-for-any-non-finite
switch(lim.method,
"fixed" = {
xlim <- lim
ylim <- lim
},
"individual" = {
xlim <- if(all(is.na(x.))) 0:1 else finite_range(x.) # adapted from plot.default()
ylim <- if(all(is.na(y.))) 0:1 else finite_range(y.)
},
"groupwise" = {
if(is.list(x) && !is.data.frame(x)) { # multiple groups
x.. <- unlist(xcols.[xburst$groups == xburst$groups[ix]]) # all x's belonging to the current group
xlim <- if(all(is.na(x..))) 0:1 else range(x..)
y.. <- unlist(xcols.[xburst$groups == xburst$groups[iy]])
ylim <- if(all(is.na(y..))) 0:1 else range(y..)
} else { # no groups = only one group = global
ax <- vars[,1] # all x indices
ay <- vars[,2] # all y indices
axd <- unlist(xcols.[ax]) # all x data; need the unlisted version here for is.finite()
xlim <- if(all(is.na(axd))) 0:1 else range(axd)
ayd <- unlist(xcols.[ay]) # all y data; need the unlisted version here for is.finite()
ylim <- if(all(is.na(ayd))) 0:1 else range(ayd)
}
},
"global" = {
ax <- vars[,1] # all x indices
ay <- vars[,2] # all y indices
axd <- unlist(xcols.[ax]) # all x's; need the unlisted version here for is.finite()
xlim <- if(all(is.na(axd))) 0:1 else range(axd)
ayd <- unlist(xcols.[ay]) # all y's; need the unlisted version here for is.finite()
ylim <- if(all(is.na(ayd))) 0:1 else range(ayd)
},
stop("Wrong 'lim.method'."))
## Return
c(x = list(x.), y = list(y.), # (numeric!) data (possibly converted); list() to keep the column labels
xburst, # components returned by burst(): xcols (original entries; with glabs + vlabs), groups, vars, glabs, vlabs
list(xlim = xlim, ylim = ylim, same.group = same.group))
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/tools.R |
## Tools for computing a path through all variables which can then be plotted
## with a zen plot
##' @title Extract Pairs from a Path of Indices
##' @usage extract_pairs(x, n)
##' @description Extracts pairs from a path of indices, representing the path
##' by the pairs (connected by common variable) and return a shortened path.
##' @family tools related to constructing zenpaths
##' @param x the path, a \code{\link{vector}} or
##' \code{\link{list}} of indices of the variables to be plotted.
##' @param n A \code{\link{vector}} of length two giving the number
##' of pairs to extract from the path \code{x} (if \code{NULL}, all pairs are
##' returned (nothing extracted); if of length one, it is replicated in the pair).
##' The first number corresponds to the beginning of the path,
##' the second to the end; at least one of the two numbers should be >= 1.
##' @return returns an object of the same type as the input
##' \code{x} but (possibly) shortened. It extracts the first/last so-many
##' pairs of \code{x}.
##' @author Marius Hofert and Wayne Oldford
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @export
##' @import PairViz
##' @examples
##' ## Begin with a path
##' (zp <- zenpath(c(3, 5), method = "eulerian.cross")) # integer(2) argument
##'
##' ## Extract the first two pairs and last four of indices
##' extract_pairs(zp, n = c(2, 4))
##'
##' ## Extract the first and last three pairs of indices
##' extract_pairs(zp, n = 3) # the 3 is repeated automatically
##'
##'
extract_pairs <- function(x, n)
{
if(is.null(n))
return(x) # nothing extracted
if(length(n) == 1) n <- rep(n, 2)
if((length(n) != 2) || any(n < 0))
stop("'n' must be NULL or one or two integers >= 0.")
if(sum(n) <= 0)
stop("At least one component of 'n' should be >= 1.")
stopifnot(is.list(x) || (is.numeric(x) && is.vector(x)))
if(is.list(x)) { # x is a list of indices
## Auxiliary function
truncation_point <- function(x, num, first = TRUE) {
l <- 0
i.ind <- 1:length(x)
if(!first) i.ind <- rev(i.ind)
for(i in i.ind) { # iterates over x top-down (if first = TRUE) or bottom-up (if first = FALSE)
j.ind <- seq_len(length(x[[i]])-1) # iterates over the pairs in x[[i]]
if(!first) j.ind <- rev(j.ind)
for(j in j.ind) { # iterates over the pairs in the vector x[[i]]
l <- l + 1
if(l >= num)
return(c(i, j)) # i = sublist; j = first index where last pair of interest begins
}
}
}
## Determine the first part
if(n[1] == 0) x.first <- NULL else {
x.first <- x
ij <- truncation_point(x, num = n[1])
i <- ij[1]
j <- ij[2]
x.first[[i]] <- head(x.first[[i]], n = j+1) # grab out the first part of the line
x.first <- head(x.first, n = i) # truncate the rest of the list
}
## Determine the last part
if(n[2] == 0) x.last <- NULL else {
x.last <- x
ij <- truncation_point(x, num = n[2], first = FALSE)
i <- ij[1]
j <- ij[2]
x.last[[i]] <- tail(x.last[[i]], n = length(x.last[[i]])-j+1) # grab out the last part of the line
x.last <- tail(x.last, n = length(x)-i+1) # truncate the first part of the list
}
## Return
res <- c(x.first, x.last)
if(is.list(res) && length(res) == 1) unlist(res) else res
} else { # x is a vector of indices
c(head(x, n = n[1] + 1), tail(x, n = n[2] + 1))
}
}
##' @title Connecting Possibly Overlapping Pairs Into a List of Paths
##' @usage connect_pairs(x, duplicate.rm = FALSE)
##' @name connect_pairs
##' @aliases connect_pairs
##' @description Pairs, given as rows of a \code{\link{matrix}},
##' \code{\link{data.frame}}, or \code{\link{list}}, are processed to return
##' a list of paths, each identifying the connected pairs in the rows of \code{x}.
##' @family tools related to constructing zenpaths
##' @param x two-column \code{\link{matrix}}, \code{\link{data.frame}}, or
##' a \code{\link{list}} containing vectors of length two representing
##' the pairs to be connected.
##' @param duplicate.rm \code{\link{logical}} indicating whether equal
##' pairs (up to permutation) are to be omitted.
##' @return A \code{\link{list}} each of whose elements give a path of connected pairs.
##' Each list element is a vector of length at least 2
##' (longer vectors > 2 in length identify the pairs connected in a path).
##' @author Marius Hofert and Wayne Oldford
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @export
##' @examples
##' ## First something simple.
##' (pairs <- matrix(c(1,2,2,3,3,5,5,7,8,9), ncol = 2, byrow = TRUE))
##' ## Connect pairs into separate paths defined by the row order.
##' connect_pairs(pairs)
##'
##' ## Now something different
##' nVars <- 5
##' pairs <- expand.grid(1:nVars, 1:nVars)
##' ## and take those where
##' (pairs <- pairs[pairs[,1] < pairs[,2],])
##' connect_pairs(pairs)
##'
##' ## Something more complicated.
##' ## Get weights
##' set.seed(27135)
##' x <- runif(choose(nVars,2)) # weights
##'
##' ## We imagine pairs identify edges of a graph with these weights
##' ## Get a zenpath ordering the edges based on weights
##' (zp <- zenpath(x, pairs = pairs, method = "strictly.weighted"))
##'
##' ## And connect these giving the list of paths
##' connect_pairs(zp)
##'
connect_pairs <- function(x, duplicate.rm = FALSE)
{
if(is.list(x)) {
if(is.data.frame(x)) { # matrix-like data frame
stopifnot(ncol(x) == 2)
x <- as.matrix(x)
} else { # proper list
stopifnot(all(sapply(x, function(x.) length(x.) == 2)))
x <- matrix(unlist(x), ncol = 2, byrow = TRUE)
}
}
stopifnot(is.matrix(x), nrow(x) >= 1, is.logical(duplicate.rm))
if(duplicate.rm) {
swapped <- rep(FALSE, nrow(x))
for(i in seq_len(nrow(x))) {
if(x[i,1] > x[i,2]) {
x[i,] <- rev(x[i,])
swapped[i] <- TRUE
}
}
dupl <- duplicated(x)
x <- x[!dupl,] # only grab out the unique pairs
swapped <- swapped[!dupl]
for(i in seq_len(nrow(x))) {
if(swapped[i]) x[i,] <- rev(x[i,]) # swap back
}
}
if(!is.matrix(x)) x <- rbind(x)
nr <- nrow(x)
res <- vector("list", length = nr) # result list of variables/indices
l <- 1 # index where to add next element in res
vec <- integer(2*nr) # most of it is 0, but c() to an empty vector is about 50x slower
vec[1:2] <- x[1,] # start with first two connected variables
v <- 2 # index of the last element in vec
for(i in 2:nr) { # go over all variable pairs
## Deal with first 2 variables of a new group (we can still rev() these variables)
if(v == 2) {
matches <- x[i-1,] %in% x[i,] # which of the two entries in the previous row is in the current row
sm <- sum(matches) # number of variables in the current row also present in the previous row
if(sm == 2 && duplicate.rm)
## Note: - This case should actually not happen due to the removal of the duplicates above
## - Without the duplicate.rm part above, this would only remove *adjacent* duplicates
## warning("Found two equal pairs (up to permutation) in rows ",i-1," and ",i,".")
next
if(sm >= 1)
if(matches[1]) vec[1:2] <- vec[2:1] # if the first one matches, flip the elements
}
## Now check whether the last variable in vec is found in the current row of pairs
## If so, add the *other* variable from the current row of pairs; otherwise start a new group
is.valid.match <- vec[v] == x[i,]
stopifnot(sum(is.valid.match) <= 1) # fail-safe programming
if(any(is.valid.match)) {
j <- which(!is.valid.match) # index of the *other* variable (the new one to add)
vec[v+1] <- x[i,j]
v <- v+1 # update index of last element in vec
} else { # start a new group
res[l] <- list(vec[1:v]) # add old vector
l <- l+1 # update index where to add next element in res
vec[1:2] <- x[i,] # define the new vec (entry is reversed above if necessary)
v <- 2 # update index of last element in vec
}
if(i == nr) res[l] <- list(vec[1:v]) # add last built vector
}
res[1:l]
}
##' @title Turn pairs or paths into a graph
##' @family tools related to constructing zenpaths
##' @usage graph_pairs(x, var.names = NULL, edgemode = c("undirected", "directed"))
##' @name graph_pairs
##' @aliases graph_pairs
##' @description Pairs are processed to produce a graph with the elements
##' of the pairs as vertices and the pairs as undirected edges.
##' The result can be displayed using \code{\link{plot}()}.
##' @param x \code{\link{matrix}} or \code{\link{list}} of pairs along a zenpath.
##' Can also be a list containing vectors representing paths in the graph.
##' Every path must be of length at least 2 (i.e. each vector element of
##' the list).
##' @param var.names names of the variables appearing in \code{x}.
##' @param edgemode type of edges to be used: either \code{"undirected"} (the default)
##' or \code{"directed"} (in which case the order of the nodes in each pair matters).
##' @return a \code{\link{graphNEL}} object; can be displayed using
##' \code{\link{plot}()}.
##' @author Marius Hofert and Wayne Oldford
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @note \code{\link{zenplot}()} never use directed graphs nor graphs with isolated (disconnected) nodes.
##' @export
##' @examples
##' ## To display the graphs constructed the packages
##' ## graph and Rgraphviz packages need to be loaded
##' library(graph)
##' library(Rgraphviz)
##' ##
##' ## Get some pairs
##' pairs <- matrix(c(1,2, 5,1, 3,4, 2,3, 4,2), ncol = 2, byrow = TRUE)
##' g <- graph_pairs(pairs)
##' ## which can be displayed using plot(g)
##' plot(g)
##'
##' ## Build a graph from a list of paths
##' paths <- list(3:1, c(3,5,7), c(1,4,7), c(6,7))
##' gp <- graph_pairs(paths)
##' ## graph package draws with grid, so clear
##' grid.newpage()
##' plot(gp)
##'
##' ## Nodes do not need to be numbers
##' alpha_paths <- list(letters[3:1], letters[c(3,5,7)],
##' letters[c(1,4,7)], letters[c(6,7)])
##' grid.newpage()
##' plot(graph_pairs(alpha_paths))
##'
##' ## Zenplots never uses this feature but you could
##' ## build a directed graph with a single isolated node
##' dg <- graph_pairs(alpha_paths,
##' var.names = c(letters[1:7], "ALONE"),
##' edgemode = "directed" )
##' grid.newpage()
##' plot(dg)
##'
graph_pairs <- function(x, var.names = NULL,
edgemode = c("undirected", "directed"))
{
edgemode <- match.arg(edgemode)
## If x a list (even with different lengths of its components, so
## 'grouped'), convert x to a 2-column matrix
if(is.list(x) && !is.data.frame(x)) {
stopifnot(all(sapply(x, function(x.) length(x.) >= 2)))
x.. <- lapply(x, function(x.) {
l <- length(x.)
if(l > 2) {
c(x.[1], rep(x.[2:(l-1)], each = 2), x.[l]) # recycle all elements except first and last
} else x.
})
x <- matrix(unlist(x..), ncol = 2, byrow = TRUE)
}
## => x is now a two-column matrix of the (ordered) pairs to be graphed
## according to the weights
## Deal with weights
## Works but not needed
## if(!is.null(weights)) {
## if(is.vector(weights)) {
## stopifnot(length(weights) == nrow(x))
## } else if(is.matrix(weights)) {
## stopifnot(nrow(weights) == ncol(weights))
## weights <- weights[x] # grab out
## } else stop("'weights' must either be a vector or a square matrix")
## ## => weights is now a vector
## }
## Build vertex names
var.x <- as.character(sort(unique(as.vector(x)))) # vertices in x as characters
if(is.null(var.names)) {
var.names <- var.x
} else {
# var.names must be a character vector
var.names <- as.character(var.names)
# Must have at least as many names in
# var.names as in var.x
if(length(var.names) < length(var.x)){
stop("'var.names' must be at least of length ",length(var.x))
}
# check that var.names contain all of var.x
var.x_notin_var.names <-setdiff(var.x, var.names)
if (length(var.x_notin_var.names) != 0) {
stop(paste("var.names are missing",
paste(var.x_notin_var.names, collapse = ", "),
"from `x`."))
}
}
## Build graph
ftM2graphNEL(x, V = var.names, edgemode = edgemode) # possibly uneven, disconnected
}
##' @title Splitting a Matrix into a List of Matrices
##' @family tools related to constructing zenpaths
##' @usage groupData(x, indices, byrow = FALSE)
##' @name groupData
##' @aliases groupData
##' @description Takes a matrix \code{x} and groups its rows (or columns)
##' as specified by \code{indices}. Returns a list of matrices, one for each group.
##' @param x A \code{\link{matrix}} (or an object
##' convertible to such via \code{\link{as.matrix}()}).
##' @param indices list of vectors of indices according to
##' which \code{x} is grouped; each vector of indices define a group.
##' @param byrow \code{\link{logical}} indicating whether the grouping is
##' done by row (\code{byrow = TRUE})
##' or by column (\code{byrow = FALSE}, the default).
##' @return A \code{\link{list}} of matrices (one per group).
##' Such a list, grouped by columns, is then typically passed on to \code{\link{zenplot}()}.
##' @author Marius Hofert and Wayne Oldford
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @export
##' @examples
##' ## get a matrix
##' x <- matrix(1:15, ncol = 3)
##' colGroups <- list(c(1,2), list(2:3))
##' rowGroups <- list(c(1,4), list(2:3))
##' groupData(x, indices = colGroups)
##' groupData(x, indices = rowGroups, byrow = TRUE)
##'
##'
groupData <- function(x, indices, byrow = FALSE)
{
if(length(dim(x)) != 2)
stop("'x' needs to have two dimensions")
stopifnot(is.list(indices))
if(byrow)
lapply(indices, function(ii) x[unlist(ii), , drop = FALSE])
else lapply(indices, function(ii) x[, unlist(ii), drop = FALSE])
}
##' @title Indexing a Matrix or Data Frame According to Given Indices
##' @usage indexData(x, indices)
##' @family tools related to constructing zenpaths
##' @param x A \code{\link{matrix}} or \code{\link{data.frame}}
##' (most useful for the latter).
##' @param indices vector of column indices of \code{x}
##' (typically obtained from \code{\link{zenpath}()}).
##' @return An object as \code{x}
##' (typically a \code{\link{data.frame}} or
##' \code{\link{matrix}}) containing \code{x}
##' indexed by \code{indices}.
##' @author Marius Hofert and Wayne Oldford
##' @note Useful for constructing data.frames without .1, .2, ... in their
##' names when indexing a data.frame with a zenpath.
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @export
##' @examples
##' ## The function is handiest for data frames
##' ## where we want to reuse the variable names
##' ## without adding a suffix like ".1" etc.
##' ## For example,
##' x <- BOD # Biochemical Oxygen Demand data in base R
##' indices <- rep(1:2, 2)
##' ## now compare
##' indexData(x, indices)
##' ## to
##' x[, indices]
##' ## zenplots prefer not to have the suffixes.
##'
indexData <- function(x, indices)
{
if(length(dim(x)) != 2)
stop("'x' needs to have two dimensions")
res <- x[, indices]
names(res) <- names(x)[indices]
res
}
## \references{
## Hofert, M., Oldford, W. (2015). Zigzag Expanded Navigation Plots.
## \emph{} \bold{}(), --.
## }
##' @title Construct a Path of Indices to Order Variables
##' @usage
##' zenpath(x, pairs = NULL,
##' method = c("front.loaded", "back.loaded",
##' "balanced", "eulerian.cross",
##' "greedy.weighted", "strictly.weighted"),
##' decreasing = TRUE)
##' @family tools related to constructing zenpaths
##' @description Constructing zenpaths and tools for extracting,
##' connecting and displaying pairs, as well as
##' grouping and indexing data structures.
##' @name zenpath
##' @aliases zenpath
##' @param x
##' \describe{for \code{method}
##' \describe{
##' \item{\code{"front.loaded"}:}{single \code{\link{integer}} >= 1.}
##' \item{\code{"back.loaded"}:}{as for \code{method = "front.loaded"}.}
##' \item{\code{"balanced"}:}{as for \code{method = "front.loaded"}.}
##' \item{\code{"eulerian.cross"}:}{two \code{\link{integer}}s >= 1
##' representing the group sizes.}
##' \item{\code{"greedy.weighted"}:}{\code{\link{numeric}} weight
##' \code{\link{vector}} (or
##' \code{\link{matrix}} or distance matrix).}
##' \item{\code{"strictly.weighted"}:}{as for
##' \code{method = "greedy.weighted"}.}
##' }
##' }
##'
##' @param pairs a two-column \code{\link{matrix}} containing (row-wise)
##' the pairs of connected variables to be sorted according to the
##' weights. Note that the resulting graph must be connected
##' (i.e. any variable can be reached from any other variable
##' following the connections given by \code{pairs}).
##' The \code{pairs} argument is only used for the \code{method}s
##' \code{greedy.weighted} and \code{strictly.weighted} and can be
##' \code{NULL} (in which case a default is constructed in lexicographical order).
##' @param method \code{\link{character}} string indicating the sorting
##' method to be used. Available methods are:
##' \describe{
##' \item{\code{"front.loaded"}:}{Sort all pairs such that the first variables appear
##' the most frequently early in the sequence;
##' an Eulerian path; note that it might be slightly
##' longer than the number of pairs because, first, an even
##' graph has to be made.}
##' \item{\code{"back.loaded"}:}{Sort all pairs such that the later variables appear
##' the most frequently later in the sequence;
##' an Eulerian path (+ see front.loaded concerning length)}
##' \item{\code{"balanced"}:}{Sort all pairs such that all variables appear in
##' balanced blocks throughout the sequence
##' (a Hamiltonian Decomposition; Eulerian, too).}
##' \item{\code{"eulerian.cross"}:}{Generate a sequence of pairs such that
##' each is formed with one variable from each group.}
##' \item{\code{"greedy.weighted"}:}{Sort all pairs according to a greedy (heuristic)
##' Euler path with \code{x} as weights visiting each
##' edge precisely once.}
##' \item{\code{"strictly.weighted"}:}{
##' Strictly respect the order of the weights - so the first, second,
##' third, and so on, adjacent pair of numbers of the output of
##' \code{zenpath()} corresponds to the pair with largest,
##' second-largest, third-largest, and so on, weight.
##' }
##' }
##' @param decreasing A \code{\link{logical}} indicating whether the
##' sorting is done according to increasing or decreasing weights.
##' @return Returns a sequence of variables (indices or names,
##' possibly a list of such), which can then be used to index the data
##' (via \code{\link{groupData}()}for plotting via \code{\link{zenplot}()}.
##' @author Marius Hofert and Wayne Oldford
##' @seealso \code{\link{zenplot}()} which provides the zenplot.
##' @export
##' @examples
##' ## Some calls of zenpath()
##' zenpath(10) # integer argument
##' ## Note that the result is of length 50 > 10 choose 2 as the underlying graph has to
##' ## be even (and thus edges are added here)
##' (zp <- zenpath(c(3, 5), method = "eulerian.cross")) # integer(2) argument
##'
zenpath <- function(x, pairs = NULL,
method = c("front.loaded", "back.loaded", "balanced",
"eulerian.cross", "greedy.weighted",
"strictly.weighted"),
decreasing = TRUE)
{
method <- match.arg(method)
switch(method,
"front.loaded" = {
stopifnot(is.numeric(x))
if(length(x) != 1 || x %% 1 != 0 || x < 1)
stop("'x' has to be an integer >= 1 for method = \"front.loaded\".")
if(x > 1) rev((x:1)[eseq(x)]) else 1
},
"back.loaded" = {
stopifnot(is.numeric(x))
if(length(x) != 1 || x %% 1 != 0 || x < 1)
stop("'x' has to be an integer >= 1 for method = \"back.loaded\".")
if(x > 1) eseq(x) else 1
},
"balanced" = {
stopifnot(is.numeric(x))
if(length(x) != 1 || x %% 1 != 0 || x < 1)
stop("'x' has to be an integer >= 1 for method = \"balanced\".")
if(x > 1) hpaths(x, matrix = FALSE) else 1
},
"eulerian.cross" = {
stopifnot(is.numeric(x))
if(length(x) != 2 || any(x %% 1 != 0) || any(x < 1))
stop("'x' has to be an integer vector of length 2 with entries >= 1.")
g1 <- seq_len(x[1])
g2 <- x[1] + seq_len(x[2])
as.numeric(eulerian(bipartite_graph(g1, g2)))
},
"greedy.weighted" =, "strictly.weighted" = {
## Deal with missing 'x' if pairs are given
if(missing(x)) {
if(missing(pairs))
stop("'pairs' need to be specified for method = ",method,".")
if(!is.matrix(pairs)) pairs <- as.matrix(pairs)
## Now pairs are given but 'x' is missing => construct 'x'
x <- 1:nrow(pairs) # 'decreasing' is dealt with differently for the different methods
}
## If 'x' is a matrix or distance matrix, convert it to a vector
if(is.matrix(x) || inherits(x, "dist"))
x <- as.vector(as.dist(x)) # => lower triangular matrix as vector
## Check
if(!is.vector(x))
stop("'x' needs to be a vector (or matrix, or distance matrix).")
## Check pairs
if(is.null(pairs)) {
## Check if length(x) is of the form 'n*(n-1)/2'
nVars <- (1+sqrt(1+8*length(x)))/2
if(nVars %% 1 != 0)
stop("'x' has to be of length n*(n-1)/2 for some n >= 2.")
## Build matrix of (all) pairs
pairs <- expand.grid(1:nVars, 1:nVars)
pairs <- pairs[pairs[,1] > pairs[,2],] # => Pairs = (2, 1), (3, 1), ... (=> lower triangular matrix)
pairs <- as.matrix(pairs)
rownames(pairs) <- NULL
colnames(pairs) <- NULL
}
if(!is.matrix(pairs)) pairs <- as.matrix(pairs)
nr <- nrow(pairs)
stopifnot(length(x) == nr, nr >= 1, ncol(pairs) == 2)
## Check whether none of the edges is given more than once (fail-safe programming)
## Note: pairs. is not used anymore below!
pairs. <- pairs
for(i in 1:nr) { # sort the pairs (only for checking)
if(pairs.[i,1] < pairs.[i,2]) {
tmp <- pairs.[i,1]
pairs.[i,1] <- pairs.[i,2]
pairs.[i,2] <- tmp
}
}
if(nrow(unique(pairs.)) != nrow(pairs.)) # use sorted 'pairs' to unique-ify and check
stop("'pairs' needs to have unique rows (possibly after applying rev()).")
## Now distinguish between the methods
if(method == "greedy.weighted") { # method "greedy.weighted"
if(decreasing) x <- -x
eul <- eulerian(ftM2graphNEL(ft = pairs, W = x, edgemode = "undirected"))
eul.lst <- lapply(eul, as.numeric) # returns character otherwise
if(is.vector(eul)) as.numeric(eul) else eul.lst
} else { # method "strictly.weighted"
pairs. <- pairs[order(x, decreasing = decreasing),] # sort pairs according to decreasing/increasing weights
lst.indices <- split(pairs., f = row(pairs.)) # result list of variables/indices
names(lst.indices) <- NULL # remove names
lst.indices
}
},
stop("Wrong 'method'"))
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/zenpath.R |
## Unfolding and zenplots
##' @title Unfold the hypercube and produce all information concerning the zenpath
##' and zenplot layout
##' @family creating zenplots
##' @name unfold
##' @aliases unfold
##' @description The \code{unfold()} function imagines each pair of variables/dimensions
##' as a "face" of a high dimensional cube. These faces are "unfolded" from one 2d space
##' or "face" to the next about the 1d face or "edge" they share. The \code{unfold()}
##' function takes, as first argument, \code{nfaces},
##' the number of 2d plots/spaces to be "unfolded" and produces the zenpath and
##' zenplot layout required for the function zenplot(). Laying out these pairs
##' with a zenplot is what is alluded to as an "unfolding" of (at least a part of)
##' the high dimensional space.
##' @usage
##' unfold(nfaces, turns = NULL,
##' n2dcols = c("letter", "square", "A4", "golden", "legal"),
##' method = c("tidy", "double.zigzag", "single.zigzag", "rectangular"),
##' first1d = TRUE, last1d = TRUE, width1d = 1, width2d = 10)
##' @param nfaces The number of faces of the hypercube to unfold
##' @param turns A \code{\link{character}} vector (of length two times the
##' number of variables to be plotted minus 1) consisting of \code{"d"},
##' \code{"u"}, \code{"r"} or \code{"l"} indicating the turns out of the
##' current plot position; if \code{NULL}, the \code{turns} are
##' constructed.
##' @param n2dcols number of columns of 2d plots (\eqn{\ge 1}{>= 1})
##' or one of \code{"letter"}, \code{"square"}, \code{"A4"},
##' \code{"golden"} or \code{"legal"} in which case a similar layout is constructed.
##' Note that \code{n2dcols} is ignored if \code{!is.null(turns)}.
##' @param method The type of zigzag plot (a \code{\link{character}}).
##'
##' Available are:
##' \describe{
##' \item{\code{tidy}:}{more tidied-up \code{double.zigzag}
##' (slightly more compact placement of plots towards the end).}
##' \item{\code{double.zigzag}:}{zigzag plot in the form of a
##' flipped \dQuote{S}. Along this path, the plots
##' are placed in the form of an \dQuote{S} which is rotated
##' counterclockwise by 90 degrees.}
##' \item{\code{single.zigzag}:}{zigzag plot in the form of a
##' flipped \dQuote{S}.}
##' \item{\code{rectangular}:}{plots that fill the page from
##' left to right and top to bottom. This is useful (and most compact)
##' for plots that do not share an axis.}
##' }
##' Note that \code{method} is ignored if \code{turns} are provided.
##' @param first1d A \code{\link{logical}} indicating whether the first one-dimensional (1d)
##' plot should be plotted.
##' @param last1d A \code{\link{logical}} indicating whether the last one-dimensional (1d)
##' plot should be plotted
##' @param width1d A graphical parameter > 0 giving the width of 1d plots.
##' @param width2d A graphical parameter > 0 giving the width of 2d plots.
##' @return A \code{\link{list}} describing the unfolded path and its layout
##' as a list of named components:
##' \describe{
##' \item{\code{path}:}{the path of the unfolding, itself given
##' as a structured \code{\link{list}} having components
##' \describe{
##' \item{\code{turns}:}{the sequence of turns
##' -- each being one of \dQuote{l} (for left), \dQuote{r} (for right),
##' \dQuote{d} (for down), and \dQuote{u} (for up) --
##' required to move from the current plot location in the display to the next along
##' the unfolded path.}
##' \item{\code{positions}:}{the path as a matrix of \code{(x, y)} positions giving
##' the indices in the \code{occupancy} matrix of each plot in the path.}
##' \item{\code{occupancy}:}{A rectangular array whose cells indicate the positions
##' of the plots on the page.}
##' }
##' }
##' \item{\code{layout}:}{the details of the visual layout of the plots and given
##' as a structured \code{\link{list}} having components
##' \describe{
##' \item{\code{orientations}:}{a vector indicating the orientation of each of the
##' displays in order -- \dQuote{h} for horizontal, \dQuote{v} for vertical, and
##' \dQuote{s} for square.}
##' \item{\code{dimensions}:}{a vector giving the dimensionality of each
##' plot in order.}
##' \item{\code{vars}:}{A matrix of the variable indices to be used in each plot -- \code{x}
##' being the horizontal variable and \code{y} the vertical.}
##' \item{\code{layoutWidth}:}{A positive integer giving the display width of
##' a 2d plot.}
##' \item{\code{layoutHeight}:}{A positive integer giving the display height of
##' a 2d plot.}
##' \item{\code{boundingBoxes}:}{A matrix of 4 columns giving locations (\code{left},
##' \code{right}, \code{bottom}, and \code{top}) of the box which bound each of the
##' plots in order.}
##' }
##' }
##' }
##' @author Marius Hofert and Wayne Oldford
##' @export
##' @note Although \code{unfold()} is probably rather rarely used directly by a user,
##' it provides insight into how zenplots are constructed.
##' @examples
##' dim <- 20
##' unfolding <- unfold(nfaces = dim -1)
##' names(unfolding)
unfold <- function(nfaces, turns = NULL,
n2dcols = c("letter", "square", "A4", "golden", "legal"),
method = c("tidy", "double.zigzag", "single.zigzag", "rectangular"),
first1d = TRUE, last1d = TRUE, width1d = 1, width2d = 10)
{
## Checking
stopifnot(nfaces >= 0, is.logical(first1d), is.logical(last1d), length(width1d) == 1,
length(width2d) == 1, width1d >= 0, width2d >= 0)
if(nfaces == 0 && (!first1d || !last1d))
stop("'first1d' or 'last1d' can only be FALSE if 'nfaces' is >= 1.")
if(is.character(n2dcols)) n2dcols <- n2dcols_aux(nfaces, method = n2dcols)
if(is.null(turns)) { # turns not provided => use n2dcols and method
stopifnot(length(n2dcols) == 1, n2dcols >= 1)
if(nfaces >= 2 && n2dcols < 2)
stop("If nfaces >= 2, n2dcols must be >= 2.")
method <- match.arg(method)
} else { # turns provided
## If the turns are provided, we should check them *before* calling
## get_path(). Otherwise (see below), we check them after they
## have been constructed by get_path()
turn_checker(turns, n2dplots = nfaces, first1d = first1d, last1d = last1d)
}
## 1) Construct the path (= turns, positions in the occupancy matrix
## and the occupancy matrix)
path <- get_path(turns, n2dplots = nfaces, n2dcols = n2dcols,
method = method, first1d = first1d, last1d = last1d)
## If 'turns' is not provided, extract them now (for checking and computing
## the layout via get_layout())
if(is.null(turns)) {
turns <- path$turns
turn_checker(turns, n2dplots = nfaces, first1d = first1d, last1d = last1d)
}
## 2) Determine the layout
layout <- get_layout(turns, n2dplots = nfaces, first1d = first1d, last1d = last1d,
width1d = width1d, width2d = width2d)
## Return
list(path = path, layout = layout)
}
## Set up hidden (not found on ls()) environment in R_GlobalEnv for burst object 'x'
.zenplots_burst_envir <- new.env(hash = FALSE, parent = emptyenv()) # define the environment to cache the burst x
##' @title Main function to create a zenplot
##' @family creating zenplots
##' @name zenplot
##' @aliases zenplot
##' @description Constructs and draws a zigzag expanded navigation plot for a
##' graphical exploratory analysis of a path of variables. The result is an
##' alternating sequence of one-dimensional (1d) and two-dimensional (2d) plots
##' laid out in a zigzag-like structure so that each consecutive pair of 2d plots has one of its
##' variates (or coordinates) in common with that of the 1d plot appearing between them.
##' @usage
##' zenplot(x, turns = NULL,
##' first1d = TRUE, last1d = TRUE,
##' n2dcols = c("letter", "square", "A4", "golden", "legal"),
##' n2dplots = NULL,
##' plot1d = c("label", "points", "jitter", "density", "boxplot", "hist",
##' "rug", "arrow", "rect", "lines", "layout"),
##' plot2d = c("points", "density", "axes", "label", "arrow", "rect", "layout"),
##' zargs = c(x = TRUE, turns = TRUE, orientations = TRUE,
##' vars = TRUE, num = TRUE, lim = TRUE, labs = TRUE,
##' width1d = TRUE, width2d = TRUE,
##' ispace = match.arg(pkg) != "graphics"),
##' lim = c("individual", "groupwise", "global"),
##' labs = list(group = "G", var = "V", sep = ", ", group2d = FALSE),
##' pkg = c("graphics", "grid", "loon"),
##' method = c("tidy", "double.zigzag", "single.zigzag", "rectangular"),
##' width1d = if(is.null(plot1d)) 0.5 else 1,
##' width2d = 10,
##' ospace = if(pkg == "loon") 0 else 0.02,
##' ispace = if(pkg == "graphics") 0 else 0.037,
##' draw = TRUE,
##' ...)
##' @param x A data object of "standard forms", being a \code{\link{vector}}, or a \code{\link{matrix}},
##' or a \code{\link{data.frame}}, or a \code{\link{list}} of any of these.
##' In the case of a list, the components of \code{x} are interpreted as
##' groups of data which are visually separated by a two-dimensional
##' (group) plot.
##' @param turns A \code{\link{character}} vector (of length two times the
##' number of variables to be plotted minus 1) consisting of \code{"d"},
##' \code{"u"}, \code{"r"} or \code{"l"} indicating the turns out of the
##' current plot position; if \code{NULL}, the \code{turns} are
##' constructed (if \code{x} is of the "standard form" described above).
##' @param first1d A \code{\link{logical}} indicating whether the first
##' one-dimensional plot is included.
##' @param last1d A \code{\link{logical}} indicating whether the last
##' one-dimensional plot is included.
##' @param n2dcols number of columns of 2d plots (\eqn{\ge 1}{>= 1})
##' or one of \code{"letter"}, \code{"square"}, \code{"A4"},
##' \code{"golden"} or \code{"legal"}
##' in which case a similar layout is constructed.
##' Note that \code{n2dcols} is ignored if \code{!is.null(turns)}.
##' @param n2dplots The number of 2d plots.
##' @param plot1d A \code{\link{function}} to use to return a
##' one-dimensional plot constructed with package \code{pkg}.
##' Alternatively, a \code{\link{character}} string of an existing
##' function.
##' For the defaults provided, the corresponding functions
##' are obtained when appending \code{_1d_graphics}, \code{_1d_grid}
##' or \code{_1d_loon} depending on which \code{pkg} is used.
##'
##' If \code{plot1d = NULL}, then no 1d plot is produced in the \code{zenplot}.
##' @param plot2d A \code{\link{function}} returning a two-dimensional plot
##' constructed with package \code{pkg}.
##' Alternatively, a \code{\link{character}} string of an existing
##' function. For the defaults provided, the corresponding functions
##' are obtained when appending \code{_2d_graphics}, \code{_2d_grid}
##' or \code{_2d_loon} depending on which \code{pkg} is used.
##'
##' As for \code{plot1d}, \code{plot2d} omits 2d plots if \code{plot2d = NULL}.
##' @param zargs A fully named \code{\link{logical}} \code{\link{vector}}
##' indicating whether the respective arguments are (possibly) passed to
##' \code{plot1d()} and \code{plot2d()} (if the latter contain the
##' formal argument \code{zargs}, which they typically do/should, but
##' see below for an example in which they do not).
##'
##' \code{zargs} can maximally contain all variables as given in the default.
##' If one of those variables does not appear in \code{zargs}, it is
##' treated as \code{TRUE} and the corresponding arguments are passed
##' on to \code{plot1d} and \code{plot2d}. If one of them is set to
##' \code{FALSE}, the argument is not passed on.
##' @param lim (x-/y-)axis limits. This can be a \code{\link{character}} string
##' or a \code{numeric(2)}.
##'
##' If \code{lim = "groupwise"} and \code{x} does not contain groups,
##' the behaviour is equivalent to \code{lim = "global"}.
##'
##' @param labs The plot labels to be used; see the argument \code{labs} of
##' \code{\link{burst}()} for the exact specification.
##' \code{labs} can, in general, be anything as long as \code{plot1d}
##' and \code{plot2d} know how to deal with it.
##' @param pkg The R package used for plotting (depends on how the
##' functions \code{plot1d} and \code{plot2d} were constructed;
##' the user is responsible for choosing the appropriate package
##' among the supported ones).
##' @param method The type of zigzag plot (a \code{\link{character}}).
##'
##' Available are:
##' \describe{
##' \item{\code{tidy}:}{more tidied-up \code{double.zigzag}
##' (slightly more compact placement of plots towards the end).}
##' \item{\code{double.zigzag}:}{zigzag plot in the form of a
##' flipped \dQuote{S}. Along this path, the plots
##' are placed in the form of an \dQuote{S} which is rotated
##' counterclockwise by 90 degrees.}
##' \item{\code{single.zigzag}:}{zigzag plot in the form of a
##' flipped \dQuote{S}.}
##' \item{\code{rectangular}:}{plots that fill the page from
##' left to right and top to bottom. This is useful (and most compact)
##' for plots that do not share an axis.}
##' }
##' Note that \code{method} is ignored if \code{turns} are provided.
##' @param width1d A graphical parameter > 0 giving the width of 1d plots.
##' @param width2d A graphical parameter > 0 giving the height of 2d plots.
##' @param ospace The outer space around the zenplot. A vector
##' of length four (bottom, left, top, right),
##' or one whose values are repeated to be of length four,
##' which gives the outer space between the device region and
##' the inner plot region around the zenplot.
##'
##' Values should be in \eqn{[0,1]} when \code{pkg} is \code{"graphics"} or
##' \code{"grid"}, and as number of pixels when\code{pkg} is \code{"loon"}.
##' @param ispace The inner space in \eqn{[0,1]} between the each figure region
##' and the region of the (1d/2d) plot it contains.
##' Again, a vector of length four (bottom, left, top, right) or a shorter one
##' whose values are repeated to produce a vector of length four.
##' @param draw A \code{\link{logical}} indicating whether a the \code{zenplot}
##' is immediately displayed (the default) or not.
##' @param ... arguments passed to the drawing functions for both \code{plot1d} and
##' \code{plot2d}. If you need to pass certain arguments only to one
##' of them, say, \code{plot2d}, consider providing your own
##' \code{plot2d}; see the examples below.
##' @return (besides plotting) invisibly returns a list having additional classnames
##' marking it as a zenplot and a zenPkg object (with Pkg being one of Graphics,
##' Grid, or Loon, so as to identify the
##' package used to construct the plot).
##'
##' As a list it contains at least
##' the path and layout (see \code{\link{unfold}} for details).
##'
##' Depending on the graphics package \code{pkg} used, the returned list
##' includes additional components. For \code{pkg = "grid"},
##' this will be the whole plot as a \code{\link[grid]{grob}} (grid object).
##' For \code{pkg = "loon"}, this will be the whole plot as a
##' \code{loon} plot object as
##' well as the toplevel \code{tk} object in which the plot appears.
##'
##' @author Marius Hofert and Wayne Oldford
##' @seealso All provided default \code{plot1d} and \code{plot2d} functions.
##'
##' \code{\link{extract_1d}()} and \code{\link{extract_2d}()}
##' for how \code{zargs} can be split up into a list of columns and corresponding
##' group and variable information.
##'
##' \code{\link{burst}()} for how \code{x} can be split up into all sorts of
##' information useful for plotting (see our default \code{plot1d} and \code{plot2d}).
##' \code{\link{vport}()} for how to construct a viewport for
##' (our default) \pkg{grid} (\code{plot1d} and \code{plot2d}) functions.
##'
##' \code{\link{extract_pairs}()}, \code{\link{connect_pairs}()},
##' \code{\link{group}()} and \code{\link{zenpath}()} for
##' (zen)path-related functions.
##'
##' The various vignettes for additional examples.
##' @keywords hplot
##' @export
##' @examples
##' ### Basics #####################################################################
##'
##' ## Generate some data
##' n <- 1000 # sample size
##' d <- 20 # dimension
##' set.seed(271) # set seed (for reproducibility)
##' x <- matrix(rnorm(n * d), ncol = d) # i.i.d. N(0,1) data
##'
##' ## A basic zenplot
##' res <- zenplot(x)
##' uf <- unfold(nfaces = d - 1)
##' ## `res` and `uf` is not identical as `res` has specific
##' ## class attributes.
##' for(name in names(uf)) {
##' stopifnot(identical(res[[name]], uf[[name]]))
##' }
##'
##' ## => The return value of zenplot() is the underlying unfold()
##'
##' ## Some missing data
##' z <- x
##' z[seq_len(n-10), 5] <- NA # all NA except 10 points
##' zenplot(z)
##'
##' ## Another column with fully missing data (use arrows)
##' ## Note: This could be more 'compactified', but is technically
##' ## more involved
##' z[, 6] <- NA # all NA
##' zenplot(z)
##'
##' ## Lists of vectors, matrices and data frames as arguments (=> groups of data)
##' ## Only two vectors
##' z <- list(x[,1], x[,2])
##' zenplot(z)
##'
##' ## A matrix and a vector
##' z <- list(x[,1:2], x[,3])
##' zenplot(z)
##'
##' ## A matrix, NA column and a vector
##' z <- list(x[,1:2], NA, x[,3])
##' zenplot(z)
##' z <- list(x[,1:2], cbind(NA, NA), x[,3])
##' zenplot(z)
##' z <- list(x[,1:2], 1:10, x[,3])
##' zenplot(z)
##'
##' ## Without labels or with different labels
##' z <- list(A = x[,1:2], B = cbind(NA, NA), C = x[,3])
##' zenplot(z, labs = NULL) # without any labels
##' zenplot(z, labs = list(group = NULL, group2d = TRUE)) # without group labels
##' zenplot(z, labs = list(group = NULL)) # without group labels unless groups change
##' zenplot(z, labs = list(var = NULL)) # without variable labels
##' zenplot(z, labs = list(var = "Variable ", sep = " - ")) # change default labels
##'
##' ## Example with a factor
##' zenplot(iris)
##' zenplot(iris, lim = "global") # global scaling of axis
##' zenplot(iris, lim = "groupwise") # acts as 'global' here (no groups in the data)
##'
##'
##' ### More sophisticated examples ################################################
##'
##' ## Note: The third component (data.frame) naturally has default labels.
##' ## zenplot() uses these labels and prepends a default group label.
##' z <- list(x[,1:5], x[1:10, 6:7], NA,
##' data.frame(x[seq_len(round(n/5)), 8:19]), cbind(NA, NA), x[1:10, 20])
##' zenplot(z, labs = list(group = "Group ")) # change the group label (var and sep are defaults)
##' ## Alternatively, give z labels
##' names(z) <- paste("Group", LETTERS[seq_len(length(z))]) # give group names
##' zenplot(z) # uses given group names
##' ## Now let's change the variable labels
##' z. <- lapply(z, function(z.) {
##' if(!is.matrix(z.)) z. <- as.matrix(z.)
##' colnames(z.) <- paste("Var.", seq_len(ncol(z.)))
##' z.
##' }
##' )
##' zenplot(z.)
##'
##'
##' ### A dynamic plot based on 'loon' (if installed and R compiled with tcl support)
##'
##' \dontrun{
##' if(requireNamespace("loon", quietly = TRUE))
##' zenplot(x, pkg = "loon")
##' }
##'
##'
##' ### Providing your own turns ###################################################
##'
##' ## A basic example
##' turns <- c("l","d","d","r","r","d","d","r","r","u","u","r","r","u","u","l","l",
##' "u","u","l","l","u","u","l","l","d","d","l","l","d","d","l","l",
##' "d","d","r","r","d","d")
##' zenplot(x, plot1d = "layout", plot2d = "layout", turns = turns) # layout of plot regions
##' ## => The tiles stick together as ispace = 0.
##' zenplot(x, plot1d = "layout", plot2d = "layout", turns = turns,
##' pkg = "grid") # layout of plot regions with grid
##' ## => Here the tiles show the small (default) ispace
##'
##' ## Another example (with own turns and groups)
##' zenplot(list(x[,1:3], x[,4:7]), plot1d = "arrow", plot2d = "rect",
##' turns = c("d", "r", "r", "r", "r", "d",
##' "d", "l", "l", "l", "l", "l"), last1d = FALSE)
##'
##'
##' ### Providing your own plot1d() or plot2d() ####################################
##'
##' ## Creating a box
##' zenplot(x, plot1d = "label", plot2d = function(zargs)
##' density_2d_graphics(zargs, box = TRUE))
##'
##' ## With grid
##' \donttest{
##' zenplot(x, plot1d = "label", plot2d = function(zargs)
##' density_2d_grid(zargs, box = TRUE), pkg = "grid")
##' }
##'
##' ## An example with width1d = width2d and where no zargs are passed on.
##' ## Note: This could have also been done with 'rect_2d_graphics(zargs, col = ...)'
##' ## as plot1d and plot2d.
##' myrect <- function(...) {
##' plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
##' rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, ...)
##' }
##' zenplot(matrix(0, ncol = 15),
##' n2dcol = "square", width1d = 10, width2d = 10,
##' plot1d = function(...) myrect(col = "royalblue3"),
##' plot2d = function(...) myrect(col = "maroon3"))
##'
##' ## Colorized rugs as plot1d()
##' basecol <- c("royalblue3", "darkorange2", "maroon3")
##' palette <- colorRampPalette(basecol, space = "Lab")
##' cols <- palette(d) # different color for each 1d plot
##' zenplot(x, plot1d = function(zargs) {
##' rug_1d_graphics(zargs, col = cols[(zargs$num+1)/2])
##' }
##' )
##'
##' ## With grid
##' library(grid) # for gTree() and gList()
##' \donttest{
##' zenplot(x, pkg = "grid", # you are responsible for choosing the right pkg (cannot be tested!)
##' plot1d = function(zargs)
##' rug_1d_grid(zargs, col = cols[(zargs$num+1)/2]))
##' }
##'
##' ## Rectangles with labels as plot2d() (shows how to overlay plots)
##' ## With graphics
##' ## Note: myplot2d() could be written directly in a simpler way, but is
##' ## based on the two functions here to show how they can be combined.
##' zenplot(x, plot1d = "arrow", plot2d = function(zargs) {
##' rect_2d_graphics(zargs)
##' label_2d_graphics(zargs, add = TRUE)
##' })
##'
##' ## With grid
##' \donttest{
##' zenplot(x, pkg = "grid", plot1d = "arrow", plot2d = function(zargs)
##' gTree(children = gList(rect_2d_grid(zargs),
##' label_2d_grid(zargs))))
##' }
##'
##' ## Rectangles with labels outside the 2d plotting region as plot2d()
##' ## With graphics
##' zenplot(x, plot1d = "arrow", plot2d = function(zargs) {
##' rect_2d_graphics(zargs)
##' label_2d_graphics(zargs, add = TRUE, xpd = NA, srt = 90,
##' loc = c(1.04, 0), adj = c(0,1), cex = 0.7)
##' })
##'
##' ## With grid
##' \donttest{
##' zenplot(x, pkg = "grid", plot1d = "arrow", plot2d = function(zargs)
##' gTree(children = gList(rect_2d_grid(zargs),
##' label_2d_grid(zargs, loc = c(1.04, 0),
##' just = c("left", "top"),
##' rot = 90, cex = 0.45))))
##' }
##'
##' ## 2d density with points, 1d arrows and labels
##' zenplot(x, plot1d = function(zargs) {
##' rect_1d_graphics(zargs)
##' arrow_1d_graphics(zargs, add = TRUE, loc = c(0.2, 0.5))
##' label_1d_graphics(zargs, add = TRUE, loc = c(0.8, 0.5))
##' }, plot2d = function(zargs) {
##' points_2d_graphics(zargs, col = adjustcolor("black", alpha.f = 0.4))
##' density_2d_graphics(zargs, add = TRUE)
##' })
##'
##' ## 2d density with labels, 1d histogram with density and label
##' ## Note: The 1d plots are *improper* overlays here as the density
##' ## plot does not know the heights of the histogram. In other
##' ## words, both histograms and densities use the whole 1d plot
##' ## region but are not correct relative to each other in the
##' ## sense of covering the same are. For a *proper* overlay
##' ## see below.
##' zenplot(x,
##' plot1d = function(zargs) {
##' hist_1d_graphics(zargs)
##' density_1d_graphics(zargs, add = TRUE,
##' border = "royalblue3",
##' lwd = 1.4)
##' label_1d_graphics(zargs, add = TRUE,
##' loc = c(0.2, 0.8),
##' cex = 0.6, font = 2,
##' col = "darkorange2")
##' },
##' plot2d = function(zargs) {
##' density_2d_graphics(zargs)
##' points_2d_graphics(zargs, add = TRUE,
##' col = adjustcolor("black", alpha.f = 0.3))
##' }
##' )
##'
##'
##' ### More sophisticated examples ################################################
##'
##' ### Example: Overlaying histograms with densities (the *proper* way)
##' \donttest{
##' ## Define proper 1d plot for overlaying histograms with densities
##' hist_with_density_1d <- function(zargs)
##' {
##' ## Extract information and data
##' num <- zargs$num # plot number (among all 1d and 2d plots)
##' turn.out <- zargs$turns[num] # turn out of current position
##' horizontal <- turn.out == "d" || turn.out == "u"
##' # the indices of the 'x' variable to be displayed in the current plot
##' ii <- plot_indices(zargs)
##' label <- paste0("V", ii[1]) # label
##' srt <- if(horizontal) 0 else if(turn.out == "r") -90 else 90 # label rotation
##' x <- zargs$x[,ii[1]] # data
##' lim <- range(x) # data limits
##' ## Compute histogram information
##' breaks <- seq(from = lim[1], to = lim[2], length.out = 21)
##' binInfo <- hist(x, breaks = breaks, plot = FALSE)
##' binBoundaries <- binInfo$breaks
##' widths <- diff(binBoundaries)
##' heights <- binInfo$density
##' ## Compute density information
##' dens <- density(x)
##' xvals <- dens$x
##' keepers <- (min(x) <= xvals) & (xvals <= max(x)) # keep those within the range of the data
##' x. <- xvals[keepers]
##' y. <- dens$y[keepers]
##' ## Determine plot limits and data
##' if(turn.out == "d" || turn.out == "l") { # flip density/histogram
##' heights <- -heights
##' y. <- -y.
##' }
##' if(horizontal) {
##' xlim <- lim
##' xlim.bp <- xlim - xlim[1] # special for barplot(); need to shift the bars
##' ylim <- range(0, heights, y.)
##' ylim.bp <- ylim
##' x <- c(xlim[1], x., xlim[2]) - xlim[1] # shift due to plot region set up by barplot()
##' y <- c(0, y., 0)
##' } else {
##' xlim <- range(0, heights, y.)
##' xlim.bp <- xlim
##' ylim <- lim
##' ylim.bp <- ylim - ylim[1] # special for barplot(); need to shift the bars
##' x <- c(0, y., 0)
##' y <- c(xlim[1], x., xlim[2]) - ylim[1] # shift due to plot region set up by barplot()
##' }
##' ## Determining label position relative to the zenpath
##' loc <- c(0.1, 0.6)
##'
##' # when walking downwards, change both left/right and up/down
##' if(turn.out == "d") loc <- 1-loc
##'
##' # when walking to the right, coordinates change and 2nd is flipped
##' if(turn.out == "r") {
##' loc <- rev(loc)
##' loc[2] <- 1-loc[2]
##' }
##'
##' # when walking to the left, coordinates change and 1st is flipped
##' if(turn.out == "l") {
##' loc <- rev(loc)
##' loc[1] <- 1-loc[1]
##' }
##' ## Plotting
##' barplot(heights, width = widths, xlim = xlim.bp, ylim = ylim.bp,
##' space = 0, horiz = !horizontal, main = "", xlab = "", axes = FALSE) # histogram
##' polygon(x = x, y = y, border = "royalblue3", lwd = 1.4) # density
##' opar <- par(usr = c(0, 1, 0, 1)) # switch to relative coordinates for text
##' on.exit(par(opar))
##' text(x = loc[1], y = loc[2], labels = label, cex = 0.7, srt = srt, font = 2,
##' col = "darkorange2") # label
##' }
##'
##' ## Zenplot
##' zenplot(x,
##' plot1d = "hist_with_density_1d",
##' plot2d = function(zargs) {
##' density_2d_graphics(zargs)
##' points_2d_graphics(zargs,
##' add = TRUE,
##' col = adjustcolor("black", alpha.f = 0.3))
##' }
##' )
##' }
##'
##' ### Example: A path through pairs of a grouped t copula sample
##'
##' \donttest{
##' ## 1) Build a random sample from a 17-dimensional grouped t copula
##' d. <- c(8, 5, 4) # sector dimensions
##' d <- sum(d.) # total dimension
##' nu <- rep(c(12, 1, 0.25), times = d.) # d.o.f. for each dimension
##' n <- 500 # sample size
##' set.seed(271)
##' Z <- matrix(rnorm(n * d), ncol = n) # (d,n)-matrix
##' P <- matrix(0.5, nrow = d, ncol = d)
##' diag(P) <- 1
##' L <- t(chol(P)) # L: LL^T = P
##' Y <- t(L %*% Z) # (n,d)-matrix containing n d-vectors following N(0,P)
##' U. <- runif(n)
##' W <- sapply(nu, function(nu.) 1/qgamma(U., shape = nu./2, rate = nu./2)) # (n,d)-matrix
##' X <- sqrt(W) * Y # (n,d)-matrix
##' U <- sapply(1:d, function(j) pt(X[,j], df = nu[j])) # (n,d)-matrix
##'
##' ## 2) Plot the data with a pairs plot, colorizing the groups
##' cols <- matrix("black", nrow = d, ncol = d) # colors
##' start <- c(1, cumsum(head(d., n = -1))+1) # block start indices
##' end <- cumsum(d.) # block end indices
##' for(j in seq_along(d.)) cols[start[j]:end[j], start[j]:end[j]] <- basecol[j] # colors
##' diag(cols) <- NA # remove colors corresponding to diagonal entries
##' cols <- as.vector(cols) # convert to a vector
##' cols <- cols[!is.na(cols)] # remove NA entries corresponding to diagonal
##' count <- 0 # panel number
##' my_panel <- function(x, y, ...) # panel function for colorizing groups
##' { count <<- count + 1; points(x, y, pch = ".", col = cols[count]) }
##' pairs(U, panel = my_panel, gap = 0,
##' labels = as.expression( sapply(1:d, function(j) bquote(italic(U[.(j)]))) ))
##'
##' ## 3) Zenplot of a random path through all pairs, colorizing the respective group
##' ## Define our own points_2d_grid() for colorizing the groups
##' my_points_2d_grid <- function(zargs, basecol, d.) {
##' r <- extract_2d(zargs) # extract information from zargs
##' x <- r$x
##' y <- r$y
##' xlim <- r$xlim
##' ylim <- r$ylim
##' num2d <- zargs$num/2
##' vars <- as.numeric(r$vlabs[num2d:(num2d+1)]) # two variables to be plotted
##' ## Alternatively, we could have used ord[r$vars[num2d:(num2d+1)]] with
##' ## the order 'ord' (see below) being passed to my_points_2d_grid()
##' col <- if(all(1 <= vars & vars <= d.[1])) { basecol[1] } else {
##' if(all(d.[1]+1 <= vars & vars <= d.[1]+d.[2])) { basecol[2] } else {
##' if(all(d.[1]+d.[2]+1 <= vars & vars <= d)) basecol[3] else "black"
##' }
##' } # determine the colors
##' vp <- vport(zargs$ispace, xlim = xlim, ylim = ylim, x = x, y = y) # viewport
##' pointsGrob(x = x[[1]], y = y[[1]], pch = 21, size = unit(0.02, units = "npc"),
##' name = "points_2d", gp = gpar(col = col), vp = vp)
##' }
##' ## Plot a random permutation of columns via a zenplot
##' ## Note: We set column labels here, as otherwise the labels can only
##' ## show *indices* of the variables to be plotted, i.e., the column
##' ## number in U[,ord], and not the original column number in U (which
##' ## is what we want to see in order to see how our 'path' through
##' ## the pairs of variables looks like).
##' colnames(U) <- 1:d
##' set.seed(1)
##' (ord <- sample(1:d, size = d)) # path; 1:d would walk parallel to the secondary diagonal
##' zenplot(U[,ord], plot1d = "layout", plot2d = "layout", pkg = "grid") # layout
##' zenplot(U[,ord], # has correct variable names as column names
##' pkg = "grid",
##' plot1d = function(zargs) arrow_1d_grid(zargs, col = "grey50"),
##' plot2d = function(zargs)
##' gTree(children = gList(
##' my_points_2d_grid(zargs, basecol = basecol, d. = d.),
##' rect_2d_grid(zargs, width = 1.05, height = 1.05,
##' col = "grey50", lty = 3),
##' label_2d_grid(zargs, loc = c(1.06, -0.03),
##' just = c("left", "top"), rot = 90, cex = 0.45,
##' fontface = "bold") )))
##' ## => The points are colorized correctly (compare with the pairs plot).
##' }
##'
##'
##' ### Using ggplot2 ##############################################################
##'
##' ## Although not thoroughly tested, in principle ggplot2 can also be used via
##' ## pkg = "grid" as follows.
##' \donttest{
##' library(ggplot2)
##'
##' ## Define our own 2d plot
##' my_points_2d_ggplot <- function(zargs, extract2d = TRUE)
##' {
##' if(extract2d) {
##' r <- extract_2d(zargs) # extract results from zargs
##' df <- data.frame(r$x, r$y) # data frame
##' names(df) <- c("x", "y")
##' cols <- zargs$x[,"Species"]
##' } else {
##' ii <- plot_indices(zargs) # the indices of the variables to be plotted
##' irs <- zargs$x # iris data
##' df <- data.frame(x = irs[,ii[1]], y = irs[,ii[2]]) # data frame
##' cols <- irs[,"Species"]
##' }
##' num2d <- zargs$num/2 # plot number among all 2d plots
##' p <- ggplot() + geom_point(data = df, aes(x = x, y = y, colour = cols),
##' show.legend = num2d == 3) +
##' labs(x = "", y = "") # 2d plot
##' if(num2d == 3) p <- p + theme(legend.position = "bottom", # legend for last 2d plot
##' legend.title = element_blank())
##' ggplot_gtable(ggplot_build(p)) # 2d plot as grob
##' }
##'
##' ## Plotting
##' iris. <- iris
##' colnames(iris.) <- gsub("\\\\.", " ", x = colnames(iris)) # => nicer 1d labels
##' zenplot(iris., n2dplots = 3, plot2d = "my_points_2d_ggplot", pkg = "grid")
##' zenplot(iris., n2dplots = 3,
##' plot2d = function(zargs) my_points_2d_ggplot(zargs, extract2d = FALSE),
##' pkg = "grid")
##' }
##'
##'
##' ### Providing your own data structure ##########################################
##'
##' \donttest{
##' ## Danger zone: An example with a new data structure (here: a list of *lists*)
##' ## Note: - In this case, we most likely need to provide both plot1d and plot2d
##' ## (but not in this case here since arrow_1d_graphics() does not depend
##' ## on the data structure)
##' ## - Note that we still make use of zargs here.
##' ## - Also note that the variables are not correctly aligned anymore:
##' ## In the ggplot2 examples we guaranteed this by plot_indices(),
##' ## but here we don't. This then still produces our layout but the
##' ## x/y axis of adjacent plots might not be the same anymore. This is
##' ## fine if only a certain order of the plots is of interest, but
##' ## not a comparison between adjacent plots.
##' z <- list(list(1:5, 2:1, 1:3), list(1:5, 1:2))
##' zenplot(z, n2dplots = 4, plot1d = "arrow", last1d = FALSE,
##' plot2d = function(zargs, ...) {
##' r <- unlist(zargs$x, recursive = FALSE)
##' num2d <- zargs$num/2 # plot number among 2d plots
##' x <- r[[num2d]]
##' y <- r[[num2d + 1]]
##' if(length(x) < length(y)) x <- rep(x, length.out = length(y))
##' else if(length(y) < length(x)) y <- rep(y, length.out = length(x))
##' plot(x, y, type = "b", xlab = "", ylab = "")
##' }, ispace = c(0.2, 0.2, 0.1, 0.1))
##' }
##'
##'
##' ### Zenplots based on 3d lattice plots #########################################
##'
##' \donttest{
##' library(lattice)
##' library(grid)
##' library(gridExtra)
##'
##' ## Build a list of cloud() plots (trellis objects)
##' ## Note:
##' ## - 'grid' problem: Without print(), the below zenplot() may fail (e.g.,
##' ## in fresh R sessions) with: 'Error in UseMethod("depth") :
##' ## no applicable method for 'depth' applied to an object of class "NULL"'
##' ## - col = "black" inside scales is needed to make the ticks show
##' mycloud <- function(x, num) {
##' lim <- extendrange(0:1, f = 0.04)
##' print(cloud(x[, 3] ~ x[, 1] * x[, 2], xlim = lim, ylim = lim, zlim = lim,
##' xlab = substitute(U[i.], list(i. = num)),
##' ylab = substitute(U[i.], list(i. = num + 1)),
##' zlab = substitute(U[i.], list(i. = num + 2)),
##' zoom = 1, scales = list(arrows = FALSE, col = "black"),
##' col = "black",
##' par.settings = list(standard.theme(color = FALSE),
##' axis.line = list(col = "transparent"),
##' clip = list(panel = "off"))))
##' }
##' plst.3d <- lapply(1:4, function(i)
##' mycloud(x[,i:(i+2)], num = i)) # list of trellis objects
##'
##' ## Preparing the zenplot
##' num <- length(plst.3d)
##' ncols <- 2
##' turns <- c(rep("r", 2*(ncols-1)), "d", "d",
##' rep("l", 2*(ncols-1)), "d")
##' plot2d <- function(zargs) {
##' num2d <- (zargs$num+1)/2
##' vp <- vport(zargs$ispace, xlim = 0:1, ylim = 0:1)
##' grob(p = zargs$x[[num2d]], vp = vp, cl = "lattice") # convert trellis to grid object
##' ## Note: For further plots, Work with
##' ## gTree(children = gList(grob(zargs$x[[num2d]], vp = vp,
##' ## cl = "lattice")))
##' }
##'
##' ## Zenplot
##' ## Note: We use a list of *plots* here already (not data)
##' zenplot(plst.3d, turns = turns, n2dplots = num, pkg = "grid", first1d = FALSE,
##' last1d = FALSE, plot1d = "arrow_1d_grid", plot2d = plot2d)
##' }
zenplot <- function(x, turns = NULL, first1d = TRUE, last1d = TRUE,
n2dcols = c("letter", "square", "A4", "golden", "legal"),
n2dplots = NULL,
plot1d = c("label", "points", "jitter", "density", "boxplot",
"hist", "rug", "arrow", "rect", "lines", "layout"),
plot2d = c("points", "density", "axes", "label", "arrow",
"rect", "layout"),
zargs = c(x = TRUE, turns = TRUE, orientations = TRUE,
vars = TRUE, num = TRUE, lim = TRUE, labs = TRUE,
width1d = TRUE, width2d = TRUE,
ispace = match.arg(pkg) != "graphics"),
lim = c("individual", "groupwise", "global"),
labs = list(group = "G", var = "V", sep = ", ", group2d = FALSE),
pkg = c("graphics", "grid", "loon"),
method = c("tidy", "double.zigzag", "single.zigzag", "rectangular"),
width1d = if(is.null(plot1d)) 0.5 else 1, width2d = 10,
ospace = if(pkg == "loon") 0 else 0.02,
ispace = if(pkg == "graphics") 0 else 0.037,
draw = TRUE, ...)
{
### Check and define basic variables ###########################################
## Check whether 'x' is of standard form and check 'n2dplots'
if(is.standard(x) && is.null(n2dplots)) {
n2dplots <- num_cols(x) - 1
} else {
if(is.null(n2dplots))
stop("'n2dplots' must be provided if 'x' is not a vector, matrix, data.frame or list of such.")
}
if(!is.numeric(n2dplots) || n2dplots < 0 || (n2dplots %% 1 != 0))
stop("'n2dplots' must be a nonnegative number.")
## Check zargs
nms <- names(zargs)
if(!is.logical(zargs) || is.null(nms) || any(nms == ""))
stop("'zargs' has to be a (fully) named, logical vector.")
if(!all(nms %in% c("x", "turns", "orientations", "vars", "num", "lim", "labs", "width1d", "width2d", "ispace")))
stop("The only valid components of 'zargs' are \"x\", \"turns\", \"orientations\", \"vars\", \"num\", \"lim\", \"labs\", \"width1d\", \"width2d\" or \"ispace\".")
## Check lim
if(is.character(lim)) {
lim <- match.arg(lim)
} else {
if(!(is.numeric(lim) && length(lim) == 2))
stop("'lim' must be a character string or numeric(2).")
}
## Default for n2dcols
if(is.character(n2dcols))
n2dcols <- n2dcols_aux(n2dplots, method = n2dcols)
## Check logicals and turns
stopifnot(is.logical(first1d), is.logical(last1d), is.logical(draw))
if(n2dplots == 0 && (!first1d || !last1d))
stop("'first1d' or 'last1d' can only be FALSE if 'n2dplots' is >= 1.")
if(is.null(turns)) { # turns not provided => use n2dcols and method
stopifnot(length(n2dcols) == 1, n2dcols >= 1)
if(n2dplots >= 2 && n2dcols < 2)
stop("If the number of 2d plots is >= 2, n2dcols must be >= 2.")
method <- match.arg(method)
} else { # turns provided
## Check length of 'turns'
turn_checker(turns, n2dplots = n2dplots, first1d = first1d, last1d = last1d)
}
## Check width1d, width2d
## Note: Use the same defaults in the respective *_1d/2d_graphics/grid functions
stopifnot(length(width1d) == 1, width1d > 0, length(width2d) == 1, width2d > 0)
## Check pkg
## Note: If you provide your own function, you have to choose 'pkg' accordingly
pkg <- match.arg(pkg)
if(pkg == "grid" && !requireNamespace("grid", quietly = TRUE))
stop("Package 'grid' is not available.")
if(pkg == "loon" && !requireNamespace("loon", quietly = TRUE))
stop("Package 'loon' is not available.")
## Check plot1d
if(missing(plot1d)) plot1d <- match.arg(plot1d)
if(!is.null(plot1d)) {
if(is.character(plot1d)) {
if(plot1d %in% eval(formals(zenplot)$plot1d)) # we don't use partial matching here as this could conflict with a user's provided string
plot1d <- paste(plot1d, "1d", pkg, sep = "_")
## Note: see below for plot2d
} else {
if(!is.function(plot1d))
stop("'plot1d' has to be either a character string or a function.")
}
if(!plot_exists(plot1d))
stop("Function provided as argument 'plot1d' does not exist.")
} # => plot1d either NULL, "<defaults>_<pkg>", a string of an existing function or an existing function
## Check plot2d
if(missing(plot2d)) plot2d <- match.arg(plot2d)
if(!is.null(plot2d)) {
if(is.character(plot2d)) {
if(plot2d %in% eval(formals(zenplot)$plot2d)) # we don't use partial matching here as this could conflict with a user's provided string
plot2d <- paste(plot2d, "2d", pkg, sep = "_")
## Note: We don't throw an error in the 'else' case as the user can provide
## a string of an existing or self-defined function as well. This may
## lead to problems. For example, if plot2d = "lines" (does not exist
## as one of the provided options), R's 1d lines() function is used
## (which of course fails).
} else {
if(!is.function(plot2d))
stop("'plot2d' has to be either a character string or a function")
}
if(!plot_exists(plot2d))
stop("Function provided as argument 'plot2d' does not exist.")
} # => plot2d either NULL, "<defaults>_<pkg>", a string of an existing function or an existing function
## Check ospace and ispace
if(length(ospace) != 4) ospace <- rep(ospace, length.out = 4)
if(length(ispace) != 4) ispace <- rep(ispace, length.out = 4)
### 1) Get arguments, variable names etc., call unfold(), determine layout #####
## Get '...' arguments
.args <- list(...)
## Call unfold() to compute the path and corresponding layout
## Note: This is *independent* of the data
pathLayout <- unfold(n2dplots, turns = turns, n2dcols = n2dcols, method = method,
first1d = first1d, last1d = last1d,
width1d = width1d, width2d = width2d)
path <- pathLayout$path
layout <- pathLayout$layout
bbs <- layout$boundingBoxes
vars <- layout$vars # 2-column matrix of plot variables (= indices)
dims <- layout$dimensions
orientations <- layout$orientations
layoutWidth <- layout$layoutWidth
layoutHeight <- layout$layoutHeight
turns <- path$turns
nPlots <- nrow(bbs)
stopifnot(nPlots == nrow(vars)) # fail-safe programming
## Determine layout
fg.rows <- unique(bbs[,c("bottom", "top"), drop = FALSE])
fg.rows <- fg.rows[order(fg.rows[,1], decreasing = TRUE),, drop = FALSE]
fg.cols <- unique(bbs[,c("left", "right"), drop = FALSE])
fg.cols <- fg.cols[order(fg.cols[,1], decreasing = FALSE),, drop = FALSE]
fg.nrow <- nrow(fg.rows)
fg.ncol <- nrow(fg.cols)
heights <- (fg.rows[, "top"] - fg.rows[,"bottom"]) / layoutHeight
widths <- (fg.cols[,"right"] - fg.cols[, "left"]) / layoutWidth
### 2) Determine formal arguments of plot1d() and plot2d() to be passed ########
## Decide whether to add the object named arg to the argument list zargs
add_to_zargs <- function(arg) {
exists.arg <- arg %in% names(zargs)
!exists.arg || (exists.arg && zargs[[arg]]) # if not appearing in zargs or appearing and TRUE, add it to the argument list zargs (only if set to FALSE, they are omitted)
}
## Determine whether the formal argument 'zargs' needs to be constructed,
## filled and passed on to plot1d() and plot2d()
## 1d plots
zargs1d <- list()
if(!is.null(plot1d) && "zargs" %in% names(eval(formals(plot1d)))) { # if 'zargs' is a formal argument of plot1d()
if(add_to_zargs("x")) zargs1d <- c(zargs1d, list(x = x)) # the original data object
if(add_to_zargs("turns")) zargs1d <- c(zargs1d, list(turns = turns)) # the vector of turns
if(add_to_zargs("orientations")) zargs1d <- c(zargs1d, list(orientations = orientations)) # the vector of orientations
if(add_to_zargs("vars")) zargs1d <- c(zargs1d, list(vars = vars)) # the 2-column matrix of plot variables
if(add_to_zargs("lim")) zargs1d <- c(zargs1d, list(lim = lim)) # character string containing the plot limits or plot limits themselves
if(add_to_zargs("labs")) zargs1d <- c(zargs1d, list(labs = labs)) # the argument 'labs' of zenplot()
if(add_to_zargs("width1d")) zargs1d <- c(zargs1d, list(width1d = width1d)) # the width of the 1d plots
if(add_to_zargs("width2d")) zargs1d <- c(zargs1d, list(width2d = width2d)) # the width of the 2d plots
if(add_to_zargs("num")) zargs1d <- c(zargs1d, list(num = NULL)) # current plot number
if(add_to_zargs("ispace")) zargs1d <- c(zargs1d, list(ispace = ispace)) # the inner space
}
## 2d plots
zargs2d <- list()
if(!is.null(plot2d) && "zargs" %in% names(eval(formals(plot2d)))) { # if 'zargs' is a formal argument of plot2d()
if(add_to_zargs("x")) zargs2d <- c(zargs2d, list(x = x)) # the original data object
if(add_to_zargs("turns")) zargs2d <- c(zargs2d, list(turns = turns)) # the vector of turns
if(add_to_zargs("orientations")) zargs2d <- c(zargs2d, list(orientations = orientations)) # the vector of orientations
if(add_to_zargs("vars")) zargs2d <- c(zargs2d, list(vars = vars)) # the 2-column matrix of plot variables
if(add_to_zargs("lim")) zargs2d <- c(zargs2d, list(lim = lim)) # character string containing the plot limits or plot limits themselves
if(add_to_zargs("labs")) zargs2d <- c(zargs2d, list(labs = labs)) # the argument 'labs' of zenplot()
if(add_to_zargs("width1d")) zargs2d <- c(zargs2d, list(width1d = width1d)) # the width of the 1d plots
if(add_to_zargs("width2d")) zargs2d <- c(zargs2d, list(width2d = width2d)) # the width of the 2d plots
if(add_to_zargs("num")) zargs2d <- c(zargs2d, list(num = NULL)) # current plot number
if(add_to_zargs("ispace")) zargs2d <- c(zargs2d, list(ispace = ispace)) # the inner space
}
### Plot #######################################################################
## plot1d = NULL or plot2d = NULL (=> plot nothing)
plot.NULL <- apply(vars, 1, function(vars.) {
((vars.[1] == vars.[2]) && is.null(plot1d)) || # plot1d = NULL
((vars.[1] != vars.[2]) && is.null(plot2d))}) # plot2d = NULL
## Big switch
positions <- path$positions
switch(pkg,
"graphics" = { # graphics ##################################################
if(draw) {
## 3) Determine default spacing around zenplot and around 1d/2d plots
stopifnot(0 <= ospace, ospace <= 1, 0 <= ispace, ispace <= 1)
opar <- par(no.readonly = TRUE) # get plotting parameter list
par(omd = c(0+ospace[2], 1-ospace[4], 0+ospace[1], 1-ospace[3]), # left, right, bottom, top space in [0,1]; more convenient than 'oma'
plt = c(0+ispace[2], 1-ispace[4], 0+ispace[1], 1-ispace[3])) # left, right, bottom, top space in [0,1]; more convenient than 'mar'
on.exit(par(opar)) # set back after function call
## Layout
lay <- matrix(0, nrow = fg.nrow, ncol = fg.ncol, byrow = TRUE)
for(k in 1:nPlots)
lay[positions[k,1], positions[k,2]] <- k
indices <- sort(unique(as.numeric(lay))) # get all assigned numbers >= 0
indices <- indices[indices > 0] # omit 0s in matrix
if(length(indices) > nPlots || !all(indices %in% 0:nPlots))
stop("That's a bug, please report.")
if(length(indices) < nPlots) {
mssng <- which(!(1:nPlots %in% indices)) # missing indices
stop("layout() failed due to missing plot numbers (",paste(mssng, collapse = ", "),") in its first argument.\nThese were most likely overwritten by later 'turns', please check.")
}
layout(lay, widths = widths, heights = heights) # layout
## => Use, e.g., layout.show(nPlots) to display the layout
## 4) Iterate over plots
for(i in seq_len(nPlots))
{
## Possibly add the plot number
if(exists("num", where = zargs1d)) zargs1d[["num"]] <- i
if(exists("num", where = zargs2d)) zargs2d[["num"]] <- i
## Plot
if(plot.NULL[i]) { # no plot
plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
} else { # plot
if(dims[i] == 1) {
do.call(plot1d, args = c(list(zargs = zargs1d), .args))
} else {
do.call(plot2d, args = c(list(zargs = zargs2d), .args))
}
}
}
}
## Delete 'burst.x' from .zenplots_burst_envir (need to do that
## here as extract_*d() might not be called by all 1d/2d plots
## (e.g., if plot1d is user-provided and does not call extract_*d() or
## if last1d = FALSE etc.)
if(exists("burst.x", envir = .zenplots_burst_envir))
rm("burst.x", envir = .zenplots_burst_envir) # remove 'burst.x'
## Return (the return value of unfold())
zen <- list(path = path, layout = layout)
attr(zen, "class") <- c("zenGraphics", "zenplot", "list")
invisible(zen)
},
"grid" = { # grid ###################################################
## 3) Layout
lay <- grid.layout(nrow = fg.nrow, ncol = fg.ncol,
widths = unit(widths, "npc"),
heights = unit(heights, "npc"), just = "centre")
## Determine default spacing around zenplot
stopifnot(0 <= ospace, ospace <= 1, 0 <= ispace, ispace <= 1)
vp <- viewport(x = unit(ospace[2], "npc"),
y = unit(ospace[1], "npc"),
just = c("left", "bottom"),
width = unit(1-sum(ospace[c(2,4)]), "npc"),
height = unit(1-sum(ospace[c(1,3)]), "npc"))
## 4) Iterate over plots (time-consuming part)
if(draw) grid.newpage()
fg <- frameGrob(layout = lay, vp = vp) # major result (a frame grob)
for(i in seq_len(nPlots))
{
## Possibly add the plot number
if(exists("num", where = zargs1d)) zargs1d[["num"]] <- i
if(exists("num", where = zargs2d)) zargs2d[["num"]] <- i
## Plot
plotGrob <- if(plot.NULL[i]) { # no plot
nullGrob()
} else { # plot
if(dims[i] == 1) {
do.call(plot1d, args = c(list(zargs = zargs1d), .args))
} else {
do.call(plot2d, args = c(list(zargs = zargs2d), .args))
}
}
## Placing the plot grob in the frame grob
fg <- placeGrob(fg, grob = plotGrob, row = positions[i,1], col = positions[i,2])
}
## Plot the actual plot object (another time-consuming part)
if(draw) grid.draw(fg)
## Delete 'burst.x' from .zenplots_burst_envir (need to do that
## here as extract_*d() might not be called by all 1d/2d plots
## (e.g., if plot1d is user-provided and does not call extract_*d() or
## if last1d = FALSE etc.)
if(exists("burst.x", envir = .zenplots_burst_envir))
rm("burst.x", envir = .zenplots_burst_envir) # remove 'burst.x'
zen <- list(path = path, layout = layout, grob = fg)
attr(zen, "class") <- c("zenGrid", "zenplot", "list")
## Return (the return value of unfold() and the frame grob)
invisible(zen)
},
"loon" = { # loon ###################################################
if(!draw) # return the return value of unfold()
return(invisible(list(path = path, layout = layout)))
## 3) Determine default spacing around zenplot
stopifnot(0 <= ospace, 0 == ospace %% 1, 0 <= ispace, ispace <= 1)
tt <- tktoplevel()
parent <- tkframe(tt)
tkpack(parent, fill="both", expand=TRUE,
padx=ospace[1:2],
pady=ospace[3:4])
## tktitle(parent) <- "Zenplot layout in Loon"
## Save the plots in a list for later configuration
loonPlots <- vector(mode="list", length = nPlots)
## 4) Iterate over plots
for(i in seq_len(nPlots))
{
## Possibly add the plot number
if(exists("num", where = zargs1d)) zargs1d[["num"]] <- i
if(exists("num", where = zargs2d)) zargs2d[["num"]] <- i
## Add additional args
## args1d <- if(!hasArg("linkingGroup")) {
## c(zargs1d,
## list(linkingGroup = paste0("Zenplots: loon ID =", parent$ID)),
## .args)
##} else c(zargs1d, .args)
##args2d <- if(!hasArg("linkingGroup")) {
## c(zargs2d,
## list(linkingGroup = paste0("Zenplots: loon ID =", parent$ID)),
## .args)
##} else c(zargs2d, .args)
## Plot
newPlot <- if(plot.NULL[i]) { # no plot
loon::l_plot(showLabels = FALSE, showScales = FALSE)
} else { # plot
if(dims[i] == 1) {
do.call(plot1d, args = c(list(zargs = zargs1d, parent=parent), .args))
} else {
do.call(plot2d, args = c(list(zargs = zargs2d, parent=parent), .args))
}
}
## Placing of plots in the parent tkgrid
##
tkgrid(newPlot, row = positions[i,1] - 1, column = positions[i,2] - 1, sticky="nesw" )# tk is zero based
## Tuck the plot away for later configuration
loonPlots[[i]] <- newPlot
}
## Resize the parent so that all plots fit
loon::l_resize(tt, 600, 600)
## Resize all plots
for(p in loonPlots)
tkconfigure(paste0(p,'.canvas'), width=1, height=1)
## loon::l_configure(p, showLabels=FALSE, showScales=FALSE)
## Set the row widths/weights
rowWeights <- round(heights * layoutHeight)
for(rowNo in 1:length(rowWeights))
tkgrid.rowconfigure(parent,
rowNo - 1, # zero based indexing
weight=rowWeights[rowNo])
## Set the column widths/weights
colWeights <- round(widths * layoutWidth)
for(colNo in 1:length(colWeights))
tkgrid.columnconfigure(parent,
colNo - 1, # zero based indexing
weight=colWeights[colNo])
## Delete 'burst.x' from .zenplots_burst_envir (need to do that
## here as extract_*d() might not be called by all 1d/2d plots
## (e.g., if plot1d is user-provided and does not call extract_*d() or
## if last1d = FALSE etc.)
if(exists("burst.x", envir = .zenplots_burst_envir))
rm("burst.x", envir = .zenplots_burst_envir) # remove 'burst.x'
## Return (the return value of unfold() and more)
zen <- list(path = path, layout = layout, loon = parent, toplevel = tt)
attr(zen, "class") <- c("zenLoon", "zenplot", "list")
## Return (the return value of unfold() and the frame grob)
invisible(zen)
},
stop("Wrong 'pkg'"))
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/zenplot.R |
#' zenplots: Zigzag Expanded Navigation Plots
#'
#' Zenplots, like pairs plots (scatterplot matrices), lay out a large
#' number of one- and two-dimensional plots in an organized way.
#'
#' Unlike pairs plots, zenplots can lay out a much larger number of
#' plots by pursuing a zigzagging layout (following a zenpath) of
#' alternating one- and two-dimensional plots.
#'
#' The plots can be created by R's base graphics package, by the grid
#' graphics package, or even made interactive (brushing, etc.) by using
#' using the loon package.
#'
#'
#' @docType package
#' @aliases zenplots-package
#' @name zenplots
#' @useDynLib zenplots, .registration=TRUE
#'
#' @import graphics
#' @import grid
#' @importFrom MASS kde2d
#' @importFrom tcltk tktoplevel tktitle<- tkgrid tkconfigure tkgrid.rowconfigure tkgrid.columnconfigure tkframe tkpack
#' @importFrom graph ftM2graphNEL
#' @importFrom PairViz eseq hpaths eulerian bipartite_graph
#' @importFrom grDevices colorRampPalette contourLines hcl xy.coords
#' @importFrom stats density qnorm quantile runif na.omit as.dist median qqplot approx
#' @importFrom methods hasArg existsFunction
#' @importFrom utils head tail
#'
#'
NULL
#> NULL
| /scratch/gouwar.j/cran-all/cranData/zenplots/R/zenplots.R |
## By Marius Hofert
## This script investigates tail dependence in constituent data of the S&P 500.
## It takes 3h to run on standard hardware (2016; can differ substantially).
### Setup ######################################################################
library(rugarch)
library(ADGofTest)
library(qqtest)
library(zoo)
library(Matrix)
library(pcaPP)
library(copula)
library(mvtnorm)
library(zenplots)
library(lattice)
library(qrmdata)
library(qrmtools)
doPNG <- require(crop)
## Set working directory (to find existing objects!)
## usr <- Sys.getenv("USER")
## if(usr == "mhofert") setwd("../../misc") else if (usr == "rwoldford")
## setwd("/Users/rwoldford/Documents/Software/zenplots/pkg/misc")
### 0 Auxiliary functions ######################################################
##' @title Panel Function to Display Sectors and Subsectors
##' @param x matrix
##' @param sectors sector division points
##' @param subsectors subsector division points
##' @return (panel) function
##' @author Marius Hofert
sector_panel_function <- function(x, sectors, subsectors,
colsec="black", colsubs="black",
lwdsec=1, lwdsubs=0.2) {
function(...){
panel.levelplot(...)
## Sectors
for(s in sectors) {
panel.lines(x = c(s, s), y = c(s, nrow(x)), col = colsec, lwd=lwdsec, lty = 2)
panel.lines(x = c(1, s), y = c(s, s), col = colsec, lwd=lwdsec, lty = 2)
}
## Subsectors
for(s in subsectors) {
panel.lines(x = c(s, s), y = c(s, nrow(x)), col = colsubs, lwd = lwdsubs)
panel.lines(x = c(1, s), y = c(s, s), col = colsubs, lwd = lwdsubs)
}
}
}
##' @title Compute Pairwise Rosenblatt Transformed Data Based on a Fitted Full
##' or Bivariate t Copulas and Compute Pairwise p-values via an AD Test
##' after Mapping to a K_2
##' @param U pseudo-observations
##' @param P correlation matrix of the fitted (full or pairwise) t copula(s)
##' @param nu matrix of degrees of freedom of the fitted (full or pairwise) t copula(s)
##' @return list with
##' 1) an (i,j,n,2)-array containing the row index i, col index j,
##' U[,i] and C(U[,j] | U[,i])
##' 2) an (i,j,.)-array containing the corresponding p-values
##' (of the AD tests after mapping the Rosenblatt transformed data
##' to a K_2 distribution)
##' 3) a (d,d)-matrix containing the p-values
##' @author Marius Hofert
##' Note: We should actually work with gofCopula(, method = "Sn"), but see the
##' the note in Section 7.2 below. Also, gofCopula() is probably much slower
pw_test <- function(U, P, Nu)
{
stopifnot(is.matrix(U))
n <- nrow(U)
d <- ncol(U)
stopifnot(is.matrix(P), dim(P) == c(d, d),
is.matrix(Nu), dim(Nu) == c(d, d))
## Setup
nms <- colnames(U)
URosen <- array(, dim = c(d*(d-1), n, 2)) # (i, j), U_i, C(U_j|U_i)
FUN <- function(q) pchisq(2*q*q, df = 2) # df of a K_2 distribution
pvals <- matrix(, nrow = d*(d-1), ncol = 3) # i, j, p-value
pb <- txtProgressBar(max = d*(d-1), style = if(isatty(stdout())) 3 else 1) # setup progress bar
on.exit(close(pb)) # on exit, close progress bar
k <- 0 # counter over all pairs
## Compute pairwise Rosenblatt transformed data and p-values
for(i in 1:d) { # row index
for(j in 1:d) { # column index
if(i != j) {
k <- k + 1
## Test
u <- U[, c(i,j)]
tc <- tCopula(P[i,j], df = Nu[i,j])
U. <- cCopula(u, copula = tc) # Rosenblatt transformed data
URosen[k,,] <- U. # save as result
pvals[k,] <- c(i, j, ad.test(sqrt(rowMeans(qnorm(U.)^2)), # (*)
distr.fun = FUN)$p.value) # compute p-values; equivalent ordering results when 'statistic' is used
## (*): Careful: Can be Inf multiple times (in which case p-values of
## 7.94702e-07 result) for pairwise Rosenblatt transformed
## data based on the pairwise fitted models
## Update progress bar
setTxtProgressBar(pb, k) # update progress bar
}
}
}
## Build matrix of p-values
pvalsMat <- matrix(, ncol = d, nrow = d)
k <- 0
for(i in 1:d) {
for(j in 1:d) {
if(i != j) {
k <- k + 1
pvalsMat[i,j] <- pvals[k,3]
}
}
}
## Return
list(URosen = URosen, pvals = pvals, pvalsMat = pvalsMat)
}
##' @title Maximal p-value Over Ljung--Box Tests for Various Lags
##' @param x univariate time series
##' @param lag.max maximal lag
##' @param p fitted AR order
##' @param q fitted MA order
##' @return maximal p-value
##' @author Marius Hofert
##' @note The order of the pairs may depend on whether p-values or the
##' Ljung--Box test statistics are used as the latter depends on
##' the (thirty considered) lag(s).
LB_test <- function(x, lag.max = 30, p = 1, q = 1) {
lag <- seq_len(lag.max)
df <- rep(0, lag.max)
df[lag > p + q] <- p + q
min(vapply(lag, FUN = function(l)
Box.test(x, lag = l, type = "Ljung-Box", fitdf = df[l])$p.value,
FUN.VALUE = NA_real_))
}
### 1 Basic data manipulation and building risk-factor changes #################
## Read the S&P 500 constituent data (composition of the S&P 500 as of 2016-01-03)
data("SP500_const") # load the constituents data from qrmdata
time <- c("2007-01-03", "2009-12-31") # time period
x <- SP500_const[paste0(time, collapse = "/"),] # data
sectors <- SP500_const_info$Sector # sectors
ssectors <- SP500_const_info$Subsector # subsectors
## Detecting NAs
if(doPNG)
png(file = (file <- paste0("fig_SP500_NA.png")),
width = 7.5, height = 6, units = "in", res = 300, bg = "transparent")
NA_plot(x)
if(doPNG) dev.off.crop(file)
## Keep the time series with at most 20% missing data and fill NAs
keep <- apply(x, 2, function(x.) mean(is.na(x.)) <= 0.2) # keep those with <= 20% NA
x <- x[, keep] # data we keep
percentNA <- round(100 * apply(x, 2, function(x.) mean(is.na(x.)))) # % of NAs for those with <= 20% NA
percentNA[percentNA > 0] # => DAL (11%), DFS (15%), TEL (15%), TWC (1%)
sectors <- sectors[keep] # corresponding sectors
ssectors <- ssectors[keep] # corresponding subsectors
if(doPNG)
png(file = (file <- paste0("fig_SP500_NA<=0.2.png")),
width = 7.5, height = 6, units = "in", res = 300, bg = "transparent")
NA_plot(x) # => only very little NA (yet still introduces interesting shape in some pobs below)
if(doPNG) dev.off.crop(file)
colnames(x)[apply(x, 2, function(x) any(is.na(x)))] # components with <= 20% NA
x <- na.fill(x, fill = "extend") # fill NAs
stopifnot(all(!is.na(x)))
### 2 Fitting marginal ARMA(1,1)-GARCH(1,1) models #############################
## We first fit ARMA(1,1)-GARCH(1,1) time series models to each margin and extract
## the standardized residuals which can then be investigated
## for cross-sectional dependence (de-GARCHing). Since the marginal fitting of so
## many time series models can fail, we use the fail-safe implementation
## fit_ARMA_GARCH() in qrmtools. The appearing warnings for six time series can
## be ignored (they come from finding initial values).
file <- paste0("SP500_",paste0(time, collapse = "--"),"_X_Z_nu_sectors_ssectors.rda")
if(file.exists(file)) {
load(file)
} else {
X <- -returns(x) # -log-returns
uspec <- rep(list(ugarchspec(distribution.model = "std")), ncol(X))
system.time(fit.ARMA.GARCH <- fit_ARMA_GARCH(X, ugarchspec.list = uspec)) # ~ 2.5min
## Note: Without the default 'solver = "hybrid"', fitting for component
## 297 throws the warning...
## Warning message:
## In .sgarchfit(spec = spec, data = data, out.sample = out.sample, :
## ugarchfit-->warning: solver failer to converge.
## ... and extracting the standardized residuals below fails!
stopifnot(sapply(fit.ARMA.GARCH$error, is.null)) # NULL = no error
## Display warnings
fit.ARMA.GARCH$warning[!sapply(fit.ARMA.GARCH$warning, is.null)]
## => 6x warnings:
## Warning message:
## In arima(data, order = c(modelinc[2], 0, modelinc[3]), include.mean = modelinc[1], :
## possible convergence problem: optim gave code = 1
## => Comes from finding initial values and can be ignored here.
fits <- fit.ARMA.GARCH$fit # fitted models
resi <- lapply(fits, residuals, standardize = TRUE) # grab out standardized residuals
Z <- as.matrix(do.call(merge, resi)) # standardized residuals
stopifnot(is.matrix(Z), nrow(Z) == 755, ncol(Z) == 465) # fail-safe programming
colnames(Z) <- colnames(x)
nu.margins <- vapply(fits, function(x) x@fit$coef[["shape"]], NA_real_) # vector of estimated df
save(X, Z, nu.margins, sectors, ssectors, file = file, compress = "xz") # save computed objects
}
n <- nrow(X) # 755
d <- ncol(X) # 465
stopifnot(n == 755, d == 465) # fail-safe programming
### 3 Pseudo-observations ######################################################
## Order the data according to business sectors (only sectors; not subsectors;
## this order gives an easier way to describe zenplots in the paper)
ord. <- order(sectors) # order according to sectors
sec. <- sectors[ord.] # sectors in sector order
ssec. <- ssectors[ord.] # subsectors in sector order
usec. <- unique(sec.) # unique sectors
nsec. <- sapply(usec., function(s) sum(sec. == s)) # sector sizes
dsec. <- head(cumsum(nsec.), n = -1) # sector division points
## Compute pseudo-observations sorted according to sectors
U. <- pobs(Z[,ord.])
## A few scatterplots to start with
if(doPNG)
png(file = (file <- paste0("fig_SP500_Unif_U12_U23_U34.png")),
width = 16, height = 4.35, units = "in", res = 200, bg = "transparent")
opar <- par(no.readonly = TRUE)
layout(matrix(1:4, nrow = 1), widths = rep(1, 4), heights = 1)
set.seed(271)
plot(matrix(runif(n*2), ncol = 2), pch = 19, xlab = "U(0,1)", ylab = "U(0,1)",
col = adjustcolor("black", alpha.f = 0.4))
plot(U.[,1:2], pch = 19, col = adjustcolor("black", alpha.f = 0.4))
plot(U.[,2:3], pch = 19, col = adjustcolor("black", alpha.f = 0.4))
plot(U.[,3:4], pch = 19, col = adjustcolor("black", alpha.f = 0.4))
par(opar)
if(doPNG) dev.off.crop(file)
## In more than two or three dimensions, one typically uses a scatterplot matrix
## to visualize the pseudo-observations. As the following plot shows, as the dimensions increase
## (here about 5% of 465), the pairs plot becomes crowded with superfluous
## information; it would be even harder to see anything interesting without alpha
## blending and, especially, in higher dimensions.
## A scatterplot matrix of the first 22 components only
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_splom.png")),
width = 10, height = 10, units = "in", res = 600, bg = "transparent")
pairs(U.[,1:22], gap = 0, cex = 0.1, cex.labels = 0.9, oma = rep(0.2, 4),
col = adjustcolor("black", alpha.f = 0.5), xaxt="n", yaxt="n")
if(doPNG) dev.off.crop(file)
## Note that we have far too many pairs to be visible in a scatterplot matrix!
## A zenplot, visualizing some of the pairs of variables, makes more sense here.
## These pairs are, by default, $(1,2), (2,3), (3,4), ..., (d-1,d)$ (with
## $d$ denoting the dimension) but will be chosen in a more meaningful way below.
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_zenplot.png")),
width = 10, height = 10, units = "in", res = 600, bg = "transparent")
zenplot(U., n2dcols = 23, ospace = 0,
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.5),
plot2d = function(zargs) points_2d_graphics(zargs, cex = 0.1,
col = adjustcolor("black", alpha.f = 0.5)))
if(doPNG) dev.off.crop(file)
## From a risk management perspective, for example, the pairs we are most
## interested in are those with the strongest tail dependence, and possibly
## also those with the weakest tail dependence (to get a feeling for the range
## of tail dependence found in the data). Our goal is thus to find and display
## (just) these pairs.
## Order the data according to business sectors *and* subsectors
## In what follows, we exclusively work with these fully ordered components
ord <- order(sectors, ssectors) # order according to sectors and subsectors
sec <- sectors[ord] # sectors in sector and subsector order
ssec <- ssectors[ord] # subsectors in sector and subsector order
## Sector information
usec <- unique(sec) # unique sectors
nsec <- sapply(usec, function(s) sum(sec == s)) # sector sizes
dsec <- head(cumsum(nsec), n = -1) # sector division points
## Subsector information
ussec <- unique(ssec) # unique subsectors
nssec <- sapply(ussec, function(s) sum(ssec == s)) # subsector sizes
dssec <- head(cumsum(nssec), n = -1) # subsector division points
## Compute pseudo-observations sorted according to sectors and subsectors
U <- pobs(Z[,ord])
## Plot several/many/all pairs of pseudo-observations (164 zenplots!)
if(FALSE) {
zpath.all <- zenpath(465) # all pairs
l <- length(zpath.all)
n2dcol <- 23
n2drow <- 30
nplots <- ceiling(l/((n2dcol-1)*n2drow)) # number of plots (note: each row has one plot less)
gr <- rep(1:nplots, each = (n2dcol-1)*n2drow)[1:l]
zpath.all.splt <- split(zpath.all, f = gr)
U.lst <- group(U, indices = zpath.all.splt)
max.nplots <- nplots # adjust here
stopifnot(1 <= max.nplots, max.nplots <= nplots)
## Loop (~ 30s/plot, 38MB each) => 82min, 6.2GB
for(i in 1:max.nplots) {
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_zenplot_all_",i,".png")),
width = 10, height = 13, units = "in", res = 600, bg = "transparent")
zenplot(U.lst[[i]], n2dcols = 23, ospace = 0,
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.5),
plot2d = function(zargs) points_2d_graphics(zargs, cex = 0.1,
col = adjustcolor("black", alpha.f = 0.5)))
if(doPNG) dev.off() # omit cropping here to save time
}
}
### 4 Computing pairwise estimators of the tail-dependence matrix ##############
### 4.1 Non-parametric estimators (conditional Spearman's rho) #################
## Non-parametric estimator based on conditional Spearman's rho
file <- paste0("SP500_",paste0(time, collapse = "--"),"_LamPWnp.rda")
if(file.exists(file)) {
load(file)
} else {
## Pairwise nonparametric estimating of the upper tail-dependence coefficient
system.time(LamPWnp <- fitLambda(U, p = 0.1, lower.tail = FALSE, verbose = TRUE)) # ~ 2min
diag(LamPWnp) <- NA
## Save object
save(LamPWnp, file = file, compress = "xz")
}
## Plot of Lambda in 'sectorial' order with sectors and subsectors
if(doPNG)
png(file = (file <- paste0("fig_SP500_Lambda_pw_nonparametric.png")),
width = 7.5, height = 6, units = "in", res = 600, bg = "transparent")
matrix_plot(LamPWnp, at = seq(0, 1, length.out = 200),
col.regions = grey(c(seq(1, 0, length.out = 200))),
panel = sector_panel_function(LamPWnp, sectors = dsec, subsectors = dssec))
if(doPNG) dev.off.crop(file)
## Density of all pairwise lambdas
if(doPNG)
png(file = (file <- paste0("fig_SP500_lambdas_pw_nonparametric.png")),
width = 7.5, height = 6, units = "in", res = 200, bg = "transparent")
matrix_density_plot(LamPWnp, xlim = 0:1,
xlab = expression("Pairwise"~lambda[U]~"(conditional Spearman's rhos)"))
if(doPNG) dev.off.crop(file)
### 4.2 Parametric estimators (bivariate t copulas) ############################
## Fit t copulas to all pairs of columns of pseudo-observations with the
## approach of Mashal, Zeevi (2002)
file <- paste0("SP500_",paste0(time, collapse = "--"),"_PPW_NuPW_LamPW.rda")
if(file.exists(file)) {
load(file)
} else {
## Pairwise fitting of t copulas
system.time(res <- fitLambda(U, method = "t", lower.tail = FALSE, verbose = TRUE)) # ~ 1.5h
## Symmetrize matrices (diagonals remain NA)
LamPW <- res$Lam
diag(LamPW) <- NA
PPW <- res$P
diag(PPW) <- NA
NuPW <- res$Nu
## Save objects
save(PPW, NuPW, LamPW, file = file, compress = "xz")
}
## Plot of Lambda in 'sectorial' order with sectors and subsectors
if(doPNG)
png(file = (file <- paste0("fig_SP500_Lambda_pw.png")),
width = 7.5, height = 6, units = "in", res = 600, bg = "transparent")
matrix_plot(LamPW, at = seq(0, 1, length.out = 200),
col.regions = grey(c(seq(1, 0, length.out = 200))),
panel = sector_panel_function(LamPWnp, sectors = dsec, subsectors = dssec,
colsec="black", lwdsec=0.8, lwdsubs=0.2, colsubs="black"))
if(doPNG) dev.off.crop(file)
## Density of all pairwise lambdas
if(doPNG)
png(file = (file <- paste0("fig_SP500_lambdas_pw.png")),
width = 7.5, height = 6, units = "in", res = 200, bg = "transparent")
matrix_density_plot(LamPW, xlim = 0:1,
xlab = expression("Pairwise"~lambda[U]~"(bivariate t copulas)"))
if(doPNG) dev.off.crop(file)
## Density of all degrees of freedom
if(doPNG)
png(file = (file <- paste0("fig_SP500_nus_pw.png")),
width = 7.5, height = 6, units = "in", res = 200, bg = "transparent")
matrix_density_plot(NuPW, log = "x",
xlab = "Pairwise degrees of freedom (bivariate t copulas)")
abline(v = 12.98722, lty = 2) # d.o.f. of the fitted full model (see below)
legend("topright", bty = "n", lty = 1:2,
legend = c("Density",
as.expression(substitute("Joint t copula"~hat(nu)==nu.,
list(nu. = 12.98)))))
if(doPNG) dev.off.crop(file)
whch <- NuPW > 999
sum(whch, na.rm = TRUE) / choose(465, 2) * 100 # % pairs with estimated d.o.f. > 999 (1.57%)
summary(LamPW[whch]) # => they are (numerically correctly treated as) 0
if(FALSE) {
## The following is known/clear, but still quite impressive to see
## Plot of Lambda in the original (unsorted) order of the components
num <- (1:ncol(x))[ord] # column numbers ordered according to sectors and subsectors
oord <- order(num) # indices to go back to original order
stopifnot(colnames(U[, oord]) == colnames(SP500_const[, keep])) # basic sanity check
LamPWunsort <- LamPW[oord, oord] # LamPW in the original, unsorted order
matrix_plot(LamPWunsort, at = seq(0, 1, length.out = 200),
col.regions = grey(c(seq(1, 0, length.out = 200))))
}
### 5 Extreme pairs ############################################################
### 5.1 Largest and smallest among all pairs ###################################
## Build a list containing the k most and least extreme lambdas
## Note: zenpath also accepts other objects, like
## as.vector(LamPW[lower.tri(LamPW)]) for which then, internally,
## the default argument 'pairs' is automatically built correctly.
k <- 10 # bottom and top number of pairs (k most extreme pairs)
zpath <- zenpath(LamPW, method = "strictly.weighted") # zenpath with decreasing weights over all pairs
czpath <- connect_pairs(zpath) # connected zpath
zp <- extract_pairs(czpath, n = k) # extract top/bottom k pairs
## Zenplot of pseudo-observations of these k most and least extreme pairs
U.groups <- group(U, indices = zp)
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_largest_smallest_lambdas_pw.png")),
width = 7.5, height = 12, units = "in", res = 600, bg = "transparent")
zenplot(U.groups, n2dcols = 5, ospace = 0, ispace = 0.01,
plot2d = function(zargs) points_2d_graphics(zargs, box = TRUE,
col = adjustcolor("black", alpha.f = 0.4)),
labs = list(group = "Path ", var = "V", sep = ", "))
if(doPNG) dev.off.crop(file)
### 5.2 Largest among all (cross-)pairs (= pairs whose components belong to
### different groups) ######################################################
## Idea: We use the zenpath over all pairs, extract those pairs lying in
## different groups and extract the most extremes among them.
## Build a matrix indicating whether a pair (i,j) lies in the different sectors
diffGrp <- matrix(TRUE, nrow = d, ncol = d)
sec.ind <- c(0, dsec, d) # 0, 78, 111,..., 436, 465
for(i in 1:(length(sec.ind)-1)) {
ii <- (sec.ind[i]+1) : sec.ind[i+1]
if(FALSE)
print(c(head(colnames(U[,ii]), n = 1), tail(colnames(U[,ii]), n = 1)))
diffGrp[ii, ii] <- FALSE
}
## Pick out those pairs along the zenpath which lie in different sectors
l <- 0
zp <- zpath
for(i in 1:length(zpath)) {
pair <- zpath[[i]]
if(diffGrp[pair[1], pair[2]]) {
l <- l+1
zp[[l]] <- zpath[[i]]
}
}
zp <- zp[1:l]
## Pick out largest k pairs and (try to) connect them
zp <- connect_pairs(extract_pairs(zp, n = c(k, 0)))
## Zenplot of pseudo-observations of these k most and least extreme pairs
U.groups <- group(U, indices = zp)
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_largest_lambdas_pw_cross_sectors.png")),
width = 7.5, height = 9, units = "in", res = 600, bg = "transparent")
zenplot(U.groups, n2dcols = 5, ospace = 0, ispace = 0.01,
plot2d = function(zargs) points_2d_graphics(zargs, box = TRUE,
col = adjustcolor("black", alpha.f = 0.4)),
labs = list(group = "Path ", var = "V", sep = ", "))
if(doPNG) dev.off.crop(file)
### 5.3 Among all pairs within a group (for all groups) ########################
## We can also look at the pseudo-observations of the pairs with largest
## pairwise tail dependencies *within each* of the 10 sectors. If the corresponding
## pairs of variables are connected, draw all connected pairs; otherwise, only draw
## the pairs corresponding to largest tail dependence within that group.
## Build a list containing the most extreme lambdas per sector (sectors are
## ordered in their original order, so lexicographically)
LamPWlst <- lapply(usec, function(s) LamPW[sec == s, sec == s]) # correct
zpath <- vector("list", length = length(usec))
for(s in seq_len(length(usec))) {
zp <- connect_pairs(zenpath(LamPWlst[[s]], method = "strictly.weighted"))[[1]] # grab out most extreme 'sub-path'
zpath[[s]] <- zp + if(s >= 2) dsec[s-1] else 0 # shift by 'previous sectors' to grab out the right variables
## Note: We could have used zenpath's extract feature to extract more
## extreme pairs but then we would have obtained a list of lists
## which cannot be dealt with easily by zenplot().
}
## Zenplot of pseudo-observations of these extreme pairs per sector
U.groups <- group(U, indices = zpath)
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_largest_lambdas_pw_per_sector.png")),
width = 7.5, height = 12, units = "in", res = 600, bg = "transparent")
zenplot(U.groups, n2dcols = 5, ospace = 0, ispace = 0.01,
plot2d = function(zargs) points_2d_graphics(zargs, box = TRUE,
col = adjustcolor("black", alpha.f = 0.4)),
labs = list(group = "GICS ", var = "V", sep = ", "))
if(doPNG) dev.off.crop(file)
### 6 Fitting a proper multivariate t copula ###################################
## Fit a d-dimensional t copula to the pseudo-observations with the approach of
## Mashal, Zeevi (2002)
file <- paste0("SP500_",paste0(time, collapse = "--"),"_t_cop.rda")
if(file.exists(file)) {
load(file)
} else {
tc <- tCopula(dim = d, dispstr = "un")
system.time(cop <- fitCopula(tc, data = U, method = "itau.mpl")) # ~ 50s
save(cop, file = file, compress = "xz")
}
nu <- tail(cop@estimate, n = 1) # estimated degrees of freedom nu
Nu <- p2P(nu, d = d) # corresponding matrix
p <- head(cop@estimate, n = -1) # estimated correlation coefficients
P <- p2P(p, d = d) # estimated correlation matrix
tc <- tCopula(p, dim = d, dispstr = "un", df = nu) # fitted t copula
Lam <- p2P(lambda(tc)[1:(d*(d-1)/2)], d = d) # 2 * pt(- sqrt((nu + 1) * (1 - P) / (1 + P)), df=nu + 1)
diag(Lam) <- NA # to be comparable to the other matrices
## Check that the estimated correlation matrices are close
## Note: They are not the same because the full model nearPD() (via fitCopula())
PPW. <- PPW
diag(PPW.) <- 1
stopifnot(all.equal(P, PPW., tol = 0.0003))
if(FALSE)
matrix_plot(P-PPW.)
## Plot of Lambda (in 'sectorial' order as above)
if(doPNG)
png(file = (file <- paste0("fig_SP500_Lambda_full.png")),
width = 7.5, height = 6, units = "in", res = 600, bg = "transparent")
matrix_plot(Lam, at = seq(0, 1, length.out = 200),
col.regions = grey(c(seq(1, 0, length.out = 200))),
panel = sector_panel_function(LamPWnp, sectors = dsec, subsectors = dssec,
colsec="black", lwdsec=0.8, lwdsubs=0.2, colsubs="black"))
if(doPNG) dev.off.crop(file)
## Compare Lam with LamPW in a scatter plot
lamPW <- LamPW[lower.tri(LamPW)]
lam <- Lam[lower.tri(Lam)]
if(doPNG)
png(file = (file <- paste0("fig_SP500_Lambda_full_vs_Lambda_pw.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
par(pty = "s")
plot(lamPW, lam, xlim = 0:1, ylim = 0:1,
xlab = expression("Pairwise"~lambda[U]~"(bivariate t copulas)"),
ylab = expression("Pairwise"~lambda[U]~"(t copula)"),
pch = 19, cex=0.5,col = adjustcolor("black", 0.5)
# pch = ".", col = "black" # An alternative to the above
)
abline(b = 1, a = 0, lwd = 0.5)
if(doPNG) dev.off.crop(file)
## Compare pobs of Lam and lamPW
if(doPNG)
png(file = (file <- paste0("fig_SP500_Lambda_full_vs_Lambda_pw_pobs.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
par(pty = "s")
plot(pobs(cbind(lamPW, lam)), xlim = 0:1, ylim = 0:1,
xlab = expression("Pseudo-observations of pairwise"~lambda[U]~"(bivariate t copulas)"),
ylab = expression("Pseudo-observations of pairwise"~lambda[U]~"(t copula)"),
pch = ".", col = adjustcolor("black", alpha.f = 0.4))
if(doPNG) dev.off.crop(file)
## Compare Lam with LamPW in a density plot
dists <- LamPW-Lam # in [-1,1]
madists <- max(abs(dists), na.rm = TRUE)
xran <- c(-madists, madists)
if(doPNG)
png(file = (file <- paste0("fig_SP500_lambdas_abs_differences_full_vs_pw.png")),
width = 7.5, height = 6, units = "in", res = 200, bg = "transparent")
matrix_density_plot(dists, xlim = xran,
xlab = expression("Pairwise"~lambda[U]~"differences (bivariate t copulas minus full t copula)"))
if(doPNG) dev.off.crop(file)
## Density of all pairwise implied lambdas
if(doPNG)
png(file = (file <- paste0("fig_SP500_lambdas_full.png")),
width = 7.5, height = 6, units = "in", res = 200, bg = "transparent")
matrix_density_plot(Lam, xlim = 0:1,
xlab = expression("Pairwise"~lambda[U]~"(t copula)"))
if(doPNG) dev.off.crop(file)
### 7 Goodness-of-fit ##########################################################
### 7.1 Marginal ARMA(1,1)-GARCH(1,1) models ###################################
### 7.1.1 Marginally test for autocorrelation of the standardized residuals Z ##
## Compute p-values for the Ljung--Box test and order Z accordingly
doSquared <- FALSE # TRUE
Z. <- if(doSquared) Z^2 else Z
pvals.margins.LB <- sapply(1:d, function(j) LB_test(Z.[,j])) # compute p-values
ord <- order(pvals.margins.LB) # order
Z.ord <- Z.[, ord] # order standardized residuals according to p-values (names also ordered)
nu.margins.ord <- nu.margins[ord] # sort degrees of freedom accordingly
pvals.margins.ord <- pvals.margins.LB[ord] # sort p-values accordingly
## Auxiliary function for zenplot() below
acf_2d <- function(zargs, pvalues, nus, lag.max = 30, ...)
{
## Extract information
x <- zargs$x
turns <- zargs$turns
num <- zargs$num/2
z <- x[, num, drop = FALSE]
lab <- colnames(z)
nu <- nus[num]
pval <- pvalues[num]
## ACF plot
acf(z, lag.max = lag.max, main = "", xlab = "", ylab = "", ...)
## Labels
opar <- par(usr = c(0, 1, 0, 1)) # to get coordinates in [0,1]
text(x = 0.95, y = 0.9, labels = lab, adj = 1)
## text(x = 0.95, y = 0.9, labels = substitute(hat(nu) == df, list(df = round(nu, 2))),
## adj = 1)
## pval.r <- round(pval, 4)
## text(x = 0.4, y = 0.9,
## labels = if (pval.r == 0) paste0("SL < 0.0001") else paste0("SL = ", pval.r))
par(opar)
invisible()
}
## Zenplot of the ACFs for those margins with smallest LB test p-values
n.col <- 4 # number of columns in the layout
n.row <- 4 # number of rows in the layout
fname <- if(doSquared) "fig_SP500_gof_margins_LB_squared.png" else "fig_SP500_gof_margins_LB.png"
if(doPNG)
png(file = (file <- paste0(fname)),
width = 8.4, height = 8.4, units = "in", res = 200, bg = "transparent")
zenplot(Z.ord[,1:(n.col*n.row+1)], # fill it completely
n2dcols = n.col, method = "rectangular",
last1d = FALSE, ospace = 0.03, ispace = c(0.17, 0.17, 0, 0), cex = 0.1,
plot1d = "arrow", plot2d = function(zargs, ...) {
acf_2d(zargs, pvalues = pvals.margins.ord, nus = nu.margins.ord, ...)
})
if(doPNG) dev.off.crop(file)
## Checking the time series which had NA
## Specify the fitted model
uspec <- ugarchspec(distribution.model = "std")
## Components with NA in (0%, 20%)
percentNA[percentNA > 0]
## DAL
x. <- x[,"DAL"]
plot(x., type = "l") # => fine
x.. <- -returns(x.)
plot(x.., type = "l") # => fine
fit.. <- ugarchfit(uspec, data = x.., solver = "hybrid")
Z.. <- as.numeric(residuals(fit.., standardize = TRUE))
plot(Z.., type = "l") # ... suddenly a peak
day <- index(x..)[which(Z.. < -1e5)]
x..[c(day-2, day-1, day)] # ... at the first trading day
acf(Z..) # ... but ACF not affected
## Check out lag plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_ACF_problem_DAL_lag_plot.png")),
width = 6, height = 6, units = "in", res = 300, bg = "transparent")
lZ.. <- length(Z..)
opar <- par(pty = "s")
plot(Z..[2:lZ..], Z..[1:(lZ..-1)], xlab = expression(Z[t+1]), ylab = expression(Z[t]))
abline(a = 0, b = 1, lty = 2, col = "gray60")
par(opar)
if(doPNG) dev.off.crop(file)
## DFS
x. <- x[,"DFS"]
plot(x., type = "l") # => fine
x.. <- -returns(x.)
plot(x.., type = "l") # => fine
fit.. <- ugarchfit(uspec, data = x.., solver = "hybrid")
Z.. <- as.numeric(residuals(fit.., standardize = TRUE))
plot(Z.., type = "l") # ... suddenly a peak
day <- index(x..)[which(Z.. < -1e5)]
x..[c(day-2, day-1, day)] # ... at the first trading day
acf(Z..) # ... but ACF not affected
## Check out lag plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_ACF_problem_DFS_lag_plot.png")),
width = 6, height = 6, units = "in", res = 300, bg = "transparent")
lZ.. <- length(Z..)
opar <- par(pty = "s")
plot(Z..[2:lZ..], Z..[1:(lZ..-1)], xlab = expression(Z[t+1]), ylab = expression(Z[t]))
abline(a = 0, b = 1, lty = 2, col = "gray60")
par(opar)
if(doPNG) dev.off.crop(file)
## TWC
x. <- x[,"TWC"]
plot(x., type = "l") # => fine
x.. <- -returns(x.)
plot(x.., type = "l") # => fine
fit.. <- ugarchfit(uspec, data = x.., solver = "hybrid")
Z.. <- as.numeric(residuals(fit.., standardize = TRUE))
plot(Z.., type = "l") # => fine
acf(Z..) # => fine
## TEL
x. <- x[,"TEL"]
plot(x., type = "l") # => fine
x.. <- -returns(x.)
plot(x.., type = "l") # => fine
fit.. <- ugarchfit(uspec, data = x.., solver = "hybrid")
Z.. <- as.numeric(residuals(fit.., standardize = TRUE))
if(doPNG)
png(file = (file <- paste0("fig_SP500_ACF_problem_TEL_Z.png")),
width = 6, height = 6, units = "in", res = 300, bg = "transparent")
opar <- par(pty = "s")
plot(index(x..), Z.., type = "l", xlab = "t",
ylab = expression("Standardized residuals"~~Z[t])) # ... suddenly a peak
par(opar)
if(doPNG) dev.off.crop(file)
day <- index(x..)[which(Z.. > 10)]
x..[c(day-2, day-1, day)] # ... at the first *two* trading days
acf(Z..) # ... ACF *is* affected
## Check out lag plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_ACF_problem_TEL_lag_plot.png")),
width = 6, height = 6, units = "in", res = 300, bg = "transparent")
lZ.. <- length(Z..)
opar <- par(pty = "s")
plot(Z..[2:lZ..], Z..[1:(lZ..-1)], xlab = expression(Z[t+1]), ylab = expression(Z[t]))
abline(a = 0, b = 1, lty = 2, col = "gray60")
par(opar)
if(doPNG) dev.off.crop(file)
## How about just using an ARMA(1,1)?
uspec <- ugarchspec(variance.model = list(garchOrder = c(0, 0)), distribution.model = "std")
fit.. <- ugarchfit(uspec, data = x.., solver = "hybrid")
Z.. <- as.numeric(residuals(fit.., standardize = TRUE))
plot(Z.., type = "l") # => fine
acf(Z..) # => fine
## Check out lag plot (=> fine)
if(doPNG)
png(file = (file <- paste0("fig_SP500_ACF_problem_TEL_lag_plot_pure_arma.png")),
width = 6, height = 6, units = "in", res = 300, bg = "transparent")
lZ.. <- length(Z..)
opar <- par(pty = "s")
plot(Z..[2:lZ..], Z..[1:(lZ..-1)], xlab = expression(Z[t+1]), ylab = expression(Z[t])) # => fine
abline(a = 0, b = 1, lty = 2, col = "gray60")
par(opar)
if(doPNG) dev.off.crop(file)
## Note: When only using a GARCH(1,1), there is only one spike (much larger)
## which does not affect the ACF.
### 7.1.2 Marginally test the assumption of Z being t ##########################
## Compute p-values for the AD test and order Z accordingly
pvals.margins.AD <- sapply(1:d, function(j)
ad.test(Z[,j], distr.fun = function(q)
pt(sqrt(nu.margins[j]/(nu.margins[j]-2)) * q, df = nu.margins[j]))$p.value) # note: equivalent ordering results when 'statistic' is used (with order(, decreasing = TRUE) below)
ord <- order(pvals.margins.AD) # order
Z.ord <- Z[, ord] # order standardized residuals according to p-values (names also ordered)
nu.margins.ord <- nu.margins[ord] # sort degrees of freedom accordingly
pvals.margins.ord <- pvals.margins.AD[ord] # sort p-values accordingly
## Auxiliary function for zenplot() below
qqtest_t_2d <- function(zargs, pvalues, nus, nreps, ...)
{
## Extract information
x <- zargs$x
turns <- zargs$turns
num <- zargs$num/2
z <- x[, num, drop = FALSE]
lab <- colnames(z)
nu <- nus[num]
pval <- pvalues[num]
## Q-Q plot
qqtest(z, qfunction = function(p) sqrt((nu-2)/nu) * qt(p, df = nu), # theoretical quantiles
legend = FALSE, nreps = nreps, col = "black",
ann = FALSE, axes = FALSE, frame.plot = TRUE, ...) # x-axis = theoretical quantiles; y-axis = sample quantiles
## Labels
opar <- par(usr = c(0, 1, 0, 1)) # to get coordinates in [0,1]
text(x = 0.92, y = 0.1, labels = substitute(hat(nu) == df~~~~~~L,
list(df = round(nu, 2), L = lab)),
adj = 1)
## pval.r <- round(pval, 4)
## text(x = 0.4, y = 0.07,
## labels = if (pval.r == 0) paste0("SL < 0.0001") else paste0("SL = ", pval.r))
par(opar)
invisible()
}
## Zenplot of the Q-Q plots for those margins with smallest AD test p-values
n.col <- 4 # number of columns in the layout
n.row <- 4 # number of rows in the layout
set.seed(271) # set a seed (for qqtest())
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_margins_AD.png")),
width = 7, height = 7, units = "in", res = 200, bg = "transparent")
zenplot(Z.ord[,1:(n.col*n.row+1)], # fill it completely
n2dcols = n.col, method = "rectangular",
last1d = FALSE, ospace = 0, cex = 0.1,
plot1d = "arrow", plot2d = function(zargs, ...) {
qqtest_t_2d(zargs, pvalues = pvals.margins.ord, nus = nu.margins.ord, nreps = 1000, ...)
abline(0, 1, col = adjustcolor("black", 0.5), lwd = 0.5)
})
if(doPNG) dev.off.crop(file)
### 7.2 Single test: Full model ################################################
## Note:
## 1) We should actually work with gofCopula(tc, x = U, method = "Sn"), but:
## Error in .gofPB(copula, x, N = N, method = method, estim.method = estim.method, :
## Param. boostrap with 'method'="Sn" not available for t copulas as pCopula() cannot be computed for non-integer degrees of freedom yet.
## 2) The next best would be gofCopula(tc, x = U, method = "SnB", trafo.method = "cCopula") but:
## 0% => Error in optim(start, loglikCopula, lower = lower, upper = upper, method = optim.method, :
## non-finite finite-difference value [1]
## => We stick to a ad.test() based on the Rosenblatt-transformed
## pseudo-observations here
## Single AD test based on full (d-dimensional) model
URosenFull <- cCopula(U, copula = tc) # Rosenblatt transformation; ~ 1.5min
stopifnot(0 <= URosenFull, URosenFull <= 1) # sanity check
## Problem: URosenFull can be 0 (14x) or 1 (3732x) => use pobs() to avoid
URosenFull. <- pobs(URosenFull)
stopifnot(0 < URosenFull., URosenFull. < 1) # sanity check
URosenFull.K <- sqrt(rowMeans(qnorm(URosenFull.)^2)) # map to a K_d
pK <- function(q, d) pchisq(d*q*q, df = d) # df of a K_d distribution
(pvalFull <- ad.test(URosenFull.K, distr.fun = pK, d = d)$p.value) # compute p-value; equivalent ordering results when 'statistic' is used
## Note: - ~ 8 * 10^{-7} => rejection!
## - The formal test based on the K_d distribution is actually the same
## as the test based on the chi_d^2 distribution
## Plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_full.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
qqtest(URosenFull.K, dist = "kay", df = d, nreps = 1000, pch = 1,
col = adjustcolor("black", alpha.f = 0.5), main = "", cex = 0.3,
xlab = substitute(K[dof]~"quantiles", list(dof = d))) # envelope = FALSE, nexemplars = 5,
if(doPNG) dev.off.crop(file)
## Do the same for random permutation of the order of the variables
set.seed(271)
URosenFull. <- cCopula(U[,sample(1:ncol(U))], copula = tc) # Rosenblatt transformation; ~ 1.5min
stopifnot(0 <= URosenFull., URosenFull. <= 1) # sanity check
## Problem: URosenFull. can be 0 (15x) or 1 (4073x) => use pobs() to avoid
URosenFull.. <- pobs(URosenFull.)
stopifnot(0 < URosenFull.., URosenFull.. < 1) # sanity check
URosenFull.K. <- sqrt(rowMeans(qnorm(URosenFull..)^2)) # map to a K_d
(pvalFull. <- ad.test(URosenFull.K., distr.fun = pK, d = d)$p.value) # compute p-value; equivalent ordering results when 'statistic' is used
## Note: - ~ 8 * 10^{-7} => rejection, too
## Plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_full_randomized.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
qqtest(URosenFull.K., dist = "kay", df = d, nreps = 1000, pch = 1,
col = adjustcolor("black", alpha.f = 0.5), main = "", cex = 0.3,
xlab = substitute(K[dof]~"quantiles", list(dof = d)))
if(doPNG) dev.off.crop(file)
### 7.3 Pairwise tests: With full ("wrong dof?") and pairwise fitted models
### ("is the data not even any t?") ########################################
### 7.3.1 Compute the objects ##################################################
## Compute pairwise Rosenblatt transformed data based on the *full* fitted model
file <- paste0("SP500_",paste0(time, collapse = "--"),"_URosenPWFull_pvalsPWFull_pvalsMatPWFull.rda")
if(file.exists(file)) {
load(file) # ~ 30s
} else {
system.time(res <- pw_test(U = U, P = P, Nu = Nu)) # ~ 30min
URosenPWFull <- res$URosen # object.size(URosenPWFull) ~= 2.6GB
pvalsPWFull <- res$pvals
pvalsMatPWFull <- res$pvalsMat
save(URosenPWFull, pvalsPWFull, pvalsMatPWFull, file = file, compress = "xz") # takes ~ 15min; 1.1GB
}
## Compute pairwise Rosenblatt transformed data based on the pairwise fitted models
file <- paste0("SP500_",paste0(time, collapse = "--"),"_URosenPWPW_pvalsPWPW_pvalsMatPWPW.rda")
if(file.exists(file)) {
load(file)
} else {
system.time(res <- pw_test(U = U, P = PPW, Nu = NuPW)) # ~ 30min
URosenPWPW <- res$URosen
pvalsPWPW <- res$pvals
pvalsMatPWPW <- res$pvalsMat
save(URosenPWPW, pvalsPWPW, pvalsMatPWPW, file = file, compress = "xz") # takes ~ 15min; 1.1GB
}
### 7.3.2 Tests/analysis #######################################################
if(FALSE) {
## Plot the matrix of p-values for the pairwise tests based on the full/pairwise model(s)
matrix_plot(pvalsMatPWFull, at = c(0, 0.05, 1), col.regions = c("black", "white")) # full model
matrix_plot(pvalsMatPWPW, at = c(0, 0.05, 1), col.regions = c("black", "white")) # pairwise models
}
## Check whether they lead to the same rejections at 5%
rejPWFull <- pvalsPWFull
rejPWFull[,3] <- pvalsPWFull[,3] < 0.05
rejPWPW <- pvalsPWPW
rejPWPW[,3] <- pvalsPWPW[,3] < 0.05
same <- rejPWFull[,3] == rejPWPW[,3] # length d*(d-1)
mean(same) * 100 # ~ 99.99397% => almost always the same decision
## Do all rejections of bivariate t models also lead to rejections of the full model?
stopifnot(! any(rejPWPW[,3] & !rejPWFull[,3]))
## => ok, all rejections of bivariate t models also lead to rejections of the full model
## For which pairs is the full model rejected but not the bivariate?
ii <- which(rejPWFull[,3] & !rejPWPW[,3])
prs <- rejPWFull[ii,1:2]
t(apply(prs, 1, function(pair) colnames(U)[pair]))
## => 13 pairs, 12 are 'symmetric', only c("WMB", "VLO") not
### 7.3.3 Matrices of p-values #################################################
## Build matrix of rejections (at 5% level)
rej <- pvalsMatPWFull # diag() is NA
rej[pvalsMatPWFull >= 0.05] <- 0 # non-rejections
rej[pvalsMatPWFull < 0.05] <- 1 # rejections of full model
rej[pvalsMatPWPW < 0.05] <- 2 # rejections of bivariate t models
## Plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_pw_matrix.png")),
width = 7.5, height = 6, units = "in", res = 600, bg = "transparent")
matrix_plot(rej, at = c(0, 2/3, 4/3, 2), col.regions = c("white", "black", "maroon3"),
colorkey = list(tck = 0,
labels = list(at = c(1/3-0.17, 1-0.29, 10/6-0.32), rot = 90,
cex = 0.7, labels = c("p-value >= 0.05",
"Only full t's p-value < 0.05",
"Both models' p-values < 0.05"))),
panel = sector_panel_function(rej, sectors = dsec, subsectors = dssec))
if(doPNG) dev.off.crop(file)
## Omit the empty rows/cols in the above matrix plots, only do the one where
## the full model is rejected and indicate those pairs where also the bivariate
## t is rejected
## rej is *almost* symmetric (but not quite, so we have to treat the general case)
vrej <- as.vector(rej)
vtrej <- as.vector(t(rej))
ii <- which(vrej != vtrej)
vrej[ii]
vtrej[ii]
## Determine the rows/cols with at least one rejection
rkeep <- rowSums(rej, na.rm = TRUE) >= 1
ckeep <- colSums(rej, na.rm = TRUE) >= 1
stopifnot(all(rkeep == ckeep)) # => indeed we keep the same rows and cols (although rej is not symmetric)
keep <- rkeep
## Extract smaller matrix
rej. <- rej[keep, keep] # build (smaller) matrix we keep
## Extract sectors
sec.. <- sec[keep] # extract sectors
usec.. <- unique(sec..) # unique sectors
nsec.. <- sapply(usec.., function(s) sum(sec.. == s)) # sector sizes
dsec.. <- head(cumsum(nsec..), n = -1) # sector division points
## Extract subsectors
ssec.. <- ssec[keep] # extract sectors
ussec.. <- unique(ssec..) # unique subsectors
nssec.. <- sapply(ussec.., function(s) sum(ssec.. == s)) # subsector sizes
dssec.. <- head(cumsum(nssec..), n = -1) # subsector division points
## Plot
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_pw_matrix_small.png")),
width = 7.5, height = 6, units = "in", res = 600, bg = "transparent")
matrix_plot(rej., at = c(0, 2/3, 4/3, 2), col.regions = c("white", "black", "maroon3"),
colorkey = list(tck = 0,
labels = list(at = c(1/3-0.17, 1-0.29, 10/6-0.32), rot = 90,
cex = 0.7, labels = c("p-value >= 0.05",
"Only full t's p-value < 0.05",
"Both models' p-values < 0.05"))),
panel = sector_panel_function(rej., sectors = dsec.., subsectors = dssec..,
colsec="black", lwdsec=0.8, lwdsubs=0.5, colsubs="grey90"))
if(doPNG) dev.off.crop(file)
## Plot of p-values
vpvalsMatPWFull <- as.vector(pvalsMatPWFull)
vpvalsMatPWPW <- as.vector(pvalsMatPWPW)
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_pw_pvals_full_vs_pw.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
plot(vpvalsMatPWFull, vpvalsMatPWPW, col = adjustcolor("black", alpha.f = 0.08),
cex = 0.3, xlab = "p-values of pairwise AD tests (t copula)",
ylab = "p-values of pairwise AD tests (bivariate t copulas)")
if(doPNG) dev.off.crop(file)
## Plot of corresponding pseudo-observations
pobs.vpvals <- pobs(cbind(vpvalsMatPWFull, vpvalsMatPWPW))
if(doPNG)
png(file = (file <- paste0("fig_SP500_gof_pw_pvals_full_vs_pw_pobs.png")),
width = 6, height = 6, units = "in", res = 200, bg = "transparent")
plot(pobs.vpvals, col = adjustcolor("black", alpha.f = 0.08),
cex = 0.3, xlab = "Pseudo-observations of p-values of pairwise AD tests (t copula)",
ylab = "Pseudo-observations of p-values of pairwise AD tests (bivariate t copulas)")
if(doPNG) dev.off.crop(file)
### 7.3.4 Pobs plots of all pairs with smallest p-value for the bivariate t copulas
### (most pairs also have the smallest p-value for the bivariate t copulas
### implied by the full t copula)
## Sort pairs according to increasing p-values for tests of pairwise models and
## pairwise models implied by the full model
pvalsPWPWord <- pvalsPWPW[order(pvalsPWPW[,3]),] # order p-values for test of pairwise models
pvalsPWFullord <- pvalsPWFull[order(pvalsPWFull[,3]),] # order p-values for test of pairwise models implied by the full model
## Same order?
same <- rowSums(pvalsPWPWord[,1:2] == pvalsPWFullord[,1:2]) == 2
if(FALSE)
plot(same, xlab = "Pair", ylab = "0 = different order, 1 = same order")
which(same)
(mn <- min(which(!same)) - 1) # => the first 336 pairs are ordered the same
colnames(U)[pvalsPWPWord[mn, 1:2]] # corresponding last pair "DAL", "DFS" where they are ordered in the same way
cbind(pvalsPWPWord[mn:350,], pvalsPWFullord[336:350,])
## Note:
## For all those pairs until ("DAL", "DFS"), the order is the same and both the
## pairwise models and the pairwise models implied by the full model lead to
## rejection at (the meaningless) 0.05.
## We depict the pobs of those pairs (duplicates removed) and some more to
## fill the last row of the zenplot. For those we simply use more pairs
## of those with smallest p-value for the bivariate t copulas but those
## will be exactly those for which this (meaningless) p-value is >= 0.05.
## And, one can show, that for those additional pairs, sometimes the full
## model does not lead to rejection at the (meaningless) 0.05 level.
## Pick out the pairs to plot
ii <- max(which(pvalsPWPWord[,3] < 0.1261)) # indicator of all pairs for which the bivariate models have a p-value < such that the last row is filled
## ii <- max(which(pvalsPWFullord[,3] < 0.05)) # ... would be one more plot and would start a new row
prs <- pvalsPWPWord[1:ii, 1:2] # (ii, 2)-matrix containing these pairs
prs.lst.connect <- connect_pairs(prs, duplicate.rm = TRUE) # connect them and remove duplicates
## Extract pobs to be plotted (connected, duplicates removed)
U.lst <- vector("list", length = length(prs.lst.connect))
for(l in 1:length(prs.lst.connect))
U.lst[[l]] <- U[, prs.lst.connect[[l]]] # matrices (>= 2 columns)
## Plot of the pobs of those pairs for which the bivariate t copula models
## lead to the smallest p-values. Note that all pairs until ("DAL", "DFS")
## are precisely those for which a) the pairwise t copulas are rejected at the
## (meaningless) 0.05 level and b) the order is the same as for the
## p-values for the bivariate t copulas implied by the full t model
if(doPNG)
png(file = (file <- paste0("fig_SP500_pobs_zenplot_smallest_p-values.png")),
width = 7, height = 8.65, units = "in", res = 600, bg = "transparent")
zenplot(U.lst, n2dcol = 17, ospace = 0, ispace = 0.01,
labs = list(group = NULL, var = "V", sep = " "),
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.4),
plot2d = function(zargs) points_2d_graphics(zargs, cex = 0.1,
col = adjustcolor("black", alpha.f = 0.2)))
if(doPNG) dev.off.crop(file)
| /scratch/gouwar.j/cran-all/cranData/zenplots/demo/SP500.R |
## ---- message=FALSE, warning=FALSE--------------------------------------------
library(zenplots)
## ---- message=FALSE, warning=FALSE--------------------------------------------
library(PairViz)
## -----------------------------------------------------------------------------
head(attenu)
## ---- echo=FALSE--------------------------------------------------------------
names(attenu)
## ---- message=FALSE, warning=FALSE--------------------------------------------
## Since attenu has 5 variates, the complete graph has n=5 nodes
## and an Euler sequence is given as
eseq(5)
## ---- message=FALSE, warning=FALSE--------------------------------------------
names(attenu)[eseq(5)]
## ---- echo=FALSE, message=FALSE, warning=FALSE, fig.align="center"------------
library(Rgraphviz)
parOptions <- par(no.readonly = TRUE)
plot(mk_complete_graph(names(attenu)), "circo")
par(parOptions)
## ---- message=FALSE, warning=FALSE, fig.align="center"------------------------
zenpath(5)
## ---- message=FALSE, warning=FALSE, fig.align="center"------------------------
## Back loading ensures all pairs appear latest (back) for
## high values of the indices.
zenpath(5, method = "back.loaded")
## Frot loading ensures all pairs appear earliest (front) for
## low values of the indices.
zenpath(5, method = "front.loaded")
## Balanced loading ensures all pairs appear in groups of all
## indices (Hamiltonian paths -> a Hamiltonian decomposition of the Eulerian)
zenpath(5, method = "balanced")
## ----zenpath, echo= FALSE, include=FALSE, fig.align="center"------------------
parOptions <- par(mfrow=c(1,3), mar=c(4, 2,2,0),oma=rep(0,4))
back <- zenpath(15, method = "back.loaded")
balanced <- zenpath(15, method = "balanced")
front <- zenpath(15, method = "front.loaded")
n <- length(zenpath(15))
plot_chars <- letters[1:15]
plot(back, n - 1:n,type="b", ylab="", xlab="", main="Back loaded",
pch=plot_chars[back], bty="n", xaxt="n", yaxt="n")
plot(balanced, n - 1:n,type="b", ylab="", xlab="", main="Balanced",
pch=plot_chars[balanced], bty="n", xaxt="n", yaxt="n")
plot(front, n - 1:n,type="b", ylab="", xlab="", main="Front loaded",
pch=plot_chars[front], bty="n", xaxt="n", yaxt="n")
par(parOptions)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## We remove the space between plots and suppress the axes
## so as to give maximal space to the individual scatterplots.
## We also choose a different plotting character and reduce
## its size to better distinguish points.
pairs(attenu, oma=rep(0,4), gap=0, xaxt="n", yaxt="n")
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## Plotting character and size are chosen to match that
## of the pairs plot.
## zenpath ensures that all pairs of variates appear
## in the zenplot.
## The last argument, n2dcol, is chosen so that the zenplot
## has the same number of plots across the page as does the
## pairs plot.
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=4)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## Call zenplot exactly as before, except that each scatterplot is replaced
## by an arrow that shows the direction of the layout.
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow", n2dcol=4)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=6----
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=5)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10----
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))])
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10----
## The directions
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow")
## -----------------------------------------------------------------------------
## Access the German election data from zenplots package
data(de_elect)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## pairs(de_elect[,1:34], oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n")
## ----message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## Try invoking the plot with the following
## zenplot(de_elect[,zenpath(68)], pch=".", n2dcol="square",col=adjustcolor("black",0.5))
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7----
## pairs(de_elect, oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n",col=adjustcolor("black",0.5))
## ---- message=FALSE, warning=FALSE--------------------------------------------
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Employment <- c("Employed", "FFF", "Industry",
"CTT", "OS" )
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=6----
EducationData <- de_elect[, Education]
EmploymentData <- de_elect[, Employment]
## Plot all pairs within each group
zenplot(list(Educ= EducationData[, zenpath(ncol(EducationData))],
Empl= EmploymentData[, zenpath(ncol(EmploymentData))]))
## -----------------------------------------------------------------------------
## Grouping variates in the German election data
Regions <- c("District", "State", "Density")
PopDist <- c("Men", "Citizens", "Pop.18.25", "Pop.25.35",
"Pop.35.60", "Pop.g.60")
PopChange <- c("Births", "Deaths", "Move.in", "Move.out", "Increase")
Agriculture <- c("Farms", "Agriculture")
Mining <- c("Mining", "Mining.employees")
Apt <- c("Apt.new", "Apt")
Motorized <- c("Motorized")
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Unemployment <- c("Unemployment.03", "Unemployment.04")
Employment <- c("Employed", "FFF", "Industry", "CTT", "OS" )
Voting.05 <- c("Voters.05", "Votes.05", "Invalid.05", "Valid.05")
Voting.02 <- c("Voters.02", "Votes.02", "Invalid.02", "Valid.02")
Voting <- c(Voting.02, Voting.05)
VotesByParty.02 <- c("Votes.SPD.02", "Votes.CDU.CSU.02", "Votes.Gruene.02",
"Votes.FDP.02", "Votes.Linke.02")
VotesByParty.05 <- c("Votes.SPD.05", "Votes.CDU.CSU.05", "Votes.Gruene.05",
"Votes.FDP.05", "Votes.Linke.05")
VotesByParty <- c(VotesByParty.02, VotesByParty.05)
PercentByParty.02 <- c("SPD.02", "CDU.CSU.02", "Gruene.02",
"FDP.02", "Linke.02", "Others.02")
PercentByParty.05 <- c("SPD.05", "CDU.CSU.05", "Gruene.05",
"FDP.05", "Linke.05", "Others.05")
PercentByParty <- c(PercentByParty.02, PercentByParty.05)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=11, fig.height=14----
groups <- list(Regions=Regions, Pop=PopDist,
Change = PopChange, Agric=Agriculture,
Mining=Mining, Apt=Apt, Cars=Motorized,
Educ=Education, Unemployed=Unemployment, Employed=Employment#,
# Vote02=Voting.02, Vote05=Voting.05,
# Party02=VotesByParty.02, Party05=VotesByParty.05,
# Perc02=PercentByParty.02, Perc05=PercentByParty.05
)
group_paths <- lapply(groups, FUN= function(g) g[zenpath(length(g), method = "front.loaded")] )
x <- groupData(de_elect, indices=group_paths)
zenplot(x, pch = ".", cex=0.7, col = "grey10")
## ----message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=10----
#
## Grouping variates in the German election data
RegionsShort <- c("ED", "State", "density")
PopDistShort <- c("men", "citizen", "18-25", "25-35", "35-60", "> 60")
PopChangeShort <- c("births", "deaths", "in", "out", "up")
AgricultureShort <- c("farms", "hectares")
MiningShort <- c("firms", "employees")
AptShort <- c("new", "all")
TransportationShort <- c("cars")
EducationShort <- c("finishers", "no.2nd", "2nd", "Real", "UED")
UnemploymentShort<- c("03", "04")
EmploymentShort <- c("employed", "FFF", "Industry", "CTT", "OS" )
Voting.05Short <- c("eligible", "votes", "invalid", "valid")
Voting.02Short <- c("eligible", "votes", "invalid", "valid")
VotesByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
VotesByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
PercentByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
PercentByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
shortNames <- list(RegionsShort, PopDistShort, PopChangeShort, AgricultureShort,
MiningShort, AptShort, TransportationShort, EducationShort,
UnemploymentShort, EmploymentShort, Voting.05Short, Voting.02Short,
VotesByParty.02Short, VotesByParty.05Short, PercentByParty.02Short,
PercentByParty.05Short)
# Now replace the names in x by these.
nGroups <- length(x)
for (i in 1:nGroups) {
longNames <- colnames(x[[i]])
newNames <- shortNames[[i]]
oldNames <- groups[[i]]
#print(longNames)
#print(newNames)
for (j in 1:length(longNames)) {
for (k in 1:length(newNames)) {
if (grepl(oldNames[k], longNames[j])) {
longNames[longNames == longNames[j]] <- newNames[k]
}
}
}
colnames(x[[i]]) <- longNames
}
zenplot(x, pch = ".", cex=0.75)
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=16----
crossedGroups <- c(Employment, Education)
crossedPaths <- zenpath(c(length(Employment), length(Education)), method="eulerian.cross")
zenplot(de_elect[,crossedGroups][crossedPaths])
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=2----
earthquakes <- attenu[, c(1,2,4,5)] # ignore the station id
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=5, width2d=1,
turns=c("r","r","r","r","r","r","r"))
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4----
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=1, width2d=1, # now widths must be the same
turns=c("r","d","d","l","l","u","u"))
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4----
zenplot(earthquakes,
plot1d= "arrow", plot2d="arrow",
width1d=1, width2d=2,
turns=c("r","d","d","l","l","u","u"))
## ---- message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4----
zenplot(earthquakes,
plot1d = function(zargs, ...) {
rect_1d_graphics(zargs, ...)
arrow_1d_graphics(zargs, col="firebrick", lwd=3, add=TRUE, ...)
},
plot2d = function(zargs, ...) {
rect_2d_graphics(zargs, ...)
arrow_2d_graphics(zargs, col="steelblue", lwd=3, lty=2, add=TRUE, ...)
},
width1d = 1, width2d = 2,
turns=c("r","d","d","l","l","u","u"))
## ---- message=FALSE, warning=FALSE, results="hide", fig.align="center", fig.width=6, fig.height=3----
library(qqtest)
zenplot(earthquakes[,zenpath(ncol(earthquakes))],
width1d = 1, width2d = 2, n2dcol=5,
plot1d = function(zargs, ...) {
r <- extract_1d(zargs) # extract arguments for 1d
col <- adjustcolor(if (r$horizontal) "firebrick" else "steelblue",
alpha.f = 0.7)
hist_1d_graphics(zargs, col=col, ...)
},
plot2d=function(zargs, ...) {
r <- extract_2d(zargs) # extract arguments for 2d
x <- as.matrix(r$x)
xlim <- r$xlim
y <- as.matrix(r$y)
ylim <- r$ylim
qqtest(y, dataTest=x,
xlim=xlim, ylim=ylim,
cex=0.3, col="black", pch=19,
legend=FALSE, main="", axes=FALSE, ...)
})
| /scratch/gouwar.j/cran-all/cranData/zenplots/inst/doc/intro.R |
---
title: Introduction to zenplots
author: M. Hofert and R. W. Oldford
date: '`r Sys.Date()`'
output:
html_vignette:
toc: yes
css: style.css
pdf_document:
keep_tex: yes
latex_engine: xelatex
number_sections: yes
toc: yes
word_document: default
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Introduction to zenplots}
%\VignetteEncoding{UTF-8}
---
```{r, message=FALSE, warning=FALSE}
library(zenplots)
```
# All pairs
A `zenplot` can show the same information as a `pairs` plot but with two
important display differences.
First, the matrix organization of the `pairs` layout is replaced by the
"zig-zag" layout of `zenplot`. Second, the number of plots produced is about
half that of a `pairs` plot allowing each plot in a `zenplot` to be given more
visual space.
## Producing all pairs with `PairViz`
A convenient function to produce all pairs can be found in the `PairViz` package
found on `cran` and installed in `R` via `install.packages("PairViz")`.
```{r, message=FALSE, warning=FALSE}
library(PairViz)
```
We will illustrate this functionality and the difference between a `pairs` plot
and a `zenplot` by first considering a small dataset on earthquakes having only
a few variates. The difference between the two plots becomes much more
important for data having larger numbers of variates -- we illustrate the
difference again using German data on voting patterns in two elections.
### Example: Ground acceleration of earthquakes
The built-in `R` data set called `attenu` contains measurements to estimate the
attenuating effect of distance on the ground acceleration of earthquakes in
California.
There are `r ncol(attenu)` different variates used to describe the peak
acceleration of 23 California earthquakes measured at different observation
stations. The data set contains `r nrow(attenu)` different peak acceleration
measurements and has some missing data. The first few cases of the data set
look like
```{r}
head(attenu)
```
Its variates are
```{r, echo=FALSE}
names(attenu)
```
and we are interested in all pairs of these variates.
To get these, first imagine a graph having as its nodes the variates of the
data. An edge of this graph connects two nodes and hence represents a pair of
variates. If interest lies in all pairs of varates, then the graph is a
complete graph -- it will have an edge between every pair of nodes. An ordering
of variate pairs corresponds to any path on the graph. To have an ordering of
all pairs of variates, the path must visit all edges and is called an Eulerian,
or Euler path. Such a path always exists for complete graphs on an odd number
of nodes; when the number of nodes is even, extra edges must be added to the
graph before an Eulerian can exist.
For a complete graph with n nodes, the function `eseq` (for Euler sequence)
function from the `PairViz` package returns an order in which the nodes
(numbered 1 to n) can be visited to produce an Euler path. It works as follows.
```{r, message=FALSE, warning=FALSE}
## Since attenu has 5 variates, the complete graph has n=5 nodes
## and an Euler sequence is given as
eseq(5)
```
In terms of the variate names of `attenu`, this is:
```{r, message=FALSE, warning=FALSE}
names(attenu)[eseq(5)]
```
As can be seen in the corresponding complete graph below,
```{r, echo=FALSE, message=FALSE, warning=FALSE, fig.align="center" }
library(Rgraphviz)
parOptions <- par(no.readonly = TRUE)
plot(mk_complete_graph(names(attenu)), "circo")
par(parOptions)
```
this sequence traces an Eulerian path on the complete graph and so presents
every variate next to every other variate somewhere in the order.
#### Euler sequences via `zenpath`
This functionality (and more) from `PairViz` has been bundled together in the
`zenplots` package as a single function `zenpath`. For example,
```{r, message=FALSE, warning=FALSE, fig.align="center" }
zenpath(5)
```
This sequence, while still Eulerian, is slightly different than that returned by
`eseq(5)`. The sequence is chosen so that all pairs involving the first index
appear earliest in the sequence, then all pairs involving the second index, and
so on. We call this a "front loaded" sequence and identify it with the
`zenpath` argument `method = "front.loaded"`. Other possibilities are `method =
"back.loaded"` and `method = "balanced"` giving the following sequences:
```{r, message=FALSE, warning=FALSE, fig.align="center" }
## Back loading ensures all pairs appear latest (back) for
## high values of the indices.
zenpath(5, method = "back.loaded")
## Frot loading ensures all pairs appear earliest (front) for
## low values of the indices.
zenpath(5, method = "front.loaded")
## Balanced loading ensures all pairs appear in groups of all
## indices (Hamiltonian paths -> a Hamiltonian decomposition of the Eulerian)
zenpath(5, method = "balanced")
```
The differences are easier to see when there are more nodes. Below, we show the
index ordering (top to bottom) for each of these three methods when the graph
has 15 nodes, here labelled"a" to "o" (to make plotting
easier).
```{r zenpath, echo= FALSE, include=FALSE, fig.align="center"}
parOptions <- par(mfrow=c(1,3), mar=c(4, 2,2,0),oma=rep(0,4))
back <- zenpath(15, method = "back.loaded")
balanced <- zenpath(15, method = "balanced")
front <- zenpath(15, method = "front.loaded")
n <- length(zenpath(15))
plot_chars <- letters[1:15]
plot(back, n - 1:n,type="b", ylab="", xlab="", main="Back loaded",
pch=plot_chars[back], bty="n", xaxt="n", yaxt="n")
plot(balanced, n - 1:n,type="b", ylab="", xlab="", main="Balanced",
pch=plot_chars[balanced], bty="n", xaxt="n", yaxt="n")
plot(front, n - 1:n,type="b", ylab="", xlab="", main="Front loaded",
pch=plot_chars[front], bty="n", xaxt="n", yaxt="n")
par(parOptions)
```
Starting from the bottom (the back of the sequence), "back loading" has the last
index, "o", complete its pairing with every other index before "n" completes
all of its pairings. All of "n"'s pairings complete before those of "m", all of
"m"'s before "l", and so on until the last pairing of "a" and "b" are completed.
Note that the last indices still appear at the end of the sequence (since the
sequence begins at the top of the display and moves down). The term "back
loading" is used here in a double sense - the later (back) indices have their
pairings appear as closely together as possible towards the back of the returned
sequence. A simple reversal, that is `rev(zenpath(15, method = "back.loaded"))`,
would have them appear at the beginning of the sequence. In
this case the "back loading" would only be in one sense, namely that the later
indexed (back) nodes appear first in the reversed sequence.
Analogously, "front loading" has the first (front) indices appear at the front
of the sequence with their pairings appear as closely together as possible.
The "balanced" case ensures that all indices appear in each block of pairings.
In the figure there are 7 blocks.
All three sequences are Eulerian, meaning all pairs appear somewhere in each
sequence.
#### Pairs plots versus zenplots
Eulerian sequences can now be used to compare a `pairs` plot with a `zenplot`
when all pairs of variates are to be displayed.
First a pairs plot:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## We remove the space between plots and suppress the axes
## so as to give maximal space to the individual scatterplots.
## We also choose a different plotting character and reduce
## its size to better distinguish points.
pairs(attenu, oma=rep(0,4), gap=0, xaxt="n", yaxt="n")
```
We now effect a display of all pairs using `zenplot`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Plotting character and size are chosen to match that
## of the pairs plot.
## zenpath ensures that all pairs of variates appear
## in the zenplot.
## The last argument, n2dcol, is chosen so that the zenplot
## has the same number of plots across the page as does the
## pairs plot.
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=4)
```
Each display shows scatterplot of all `choose(5,2) =` `r choose(ncol(attenu),
2)` pairs of variates for this data. Each display occupies the same total area.
With `pairs` each plot is displayed twice and arranged in a symmetric matrix
layout with the variate labels appearing along the diagonal. This makes for
easy look-up but uses a lot of space.
With `zenplot`, each plot appears only once with its coordinate defining
variates appearing as labels on horizontal (top or bottom) and vertical (left or
right) axis positions. The layout follows the order of the variates in which
the variates appear in the call to `zenplot` beginning in the top left corner of
the display and then zig-zagging from top left to bottom right; when the
rightmost boundary or the display is reached, the direction is reversed
horizontally and the zigzag moves from top right to bottom left. The following
display illustrates the pattern (had by simply calling `zenplot`):
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Call zenplot exactly as before, except that each scatterplot is replaced
## by an arrow that shows the direction of the layout.
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow", n2dcol=4)
```
The zig zag pattern of plots appears as follows.
- The top left plot (of either `zenplot` display) has horizontal variate `event`
and vertical variate `mag`.
- To its right is a plot sharing the same vertical variate `mag` but now with
horizontal variate `station`. Note that the variate `station` has some
missing values and this is recorded on its label as `station (some NA)`.
- Below this a plot appears with the same horizontal variate `station` but now
with vertical variate `event`. Since this is the first repeat appearance of
`event` it appears with a suffix as `event.1`.
- To its right is a plot with shared vertical variate `event` and new horizontal
variate `dist`.
- Below this is a plot having shared horizontal variate `dist` and as vertical
variate the first repeat of the variate `mag`.
- To its right is a plot having shared vertical variate `mag` and new horizontal
variate `accel`.
- The right edge of the display is reached and the zigzag changes horizontal
direction repeating the pattern until either the left edge is reached
(whereupon the horizontal direction is reversed) or the variates are
exhausted.
Like the `pairs` plot, the `zenplot` lays its plots out on a two dimensional
grid -- the argument `n2dcol=4` specifies the number of columns for the 2d
plots (e.g. scatterplots). As shown, this can lead to a lot of unused space in
the display.
The `zenplot` layout can be made more compact by different choices of the
argument `n2dcol` (odd values provide a more compact layout). For example,
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=6}
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=5)
```
By default, `zenplot` tries to determine a value for `n2dcol` that minimizes the
space unused by its zigzag layout.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10}
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))])
```
with layout directions as
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10}
## The directions
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow")
```
As the direction arrows show, the default layout is to zigzag horizontally first
as much as possible.
This is clearly a much more compact display. Again, axes are shared wherever a label appears between plots.
Unless explicitly specified, the value of `n2dcol` is determined by the
aregument `scaling` which can either be a numerical value specifying the ratio
of the height to the width of the `zenplot` layout or be a string describing a
page whose ratio of height to width will be used. The possible strings are
``letter'' (the default), ``square'', ``A4'', ``golden'' (for the golden ratio),
or ``legal''.
### Visual search
The display arrangement of a scatterplot matrix facilitates the lookup of the
scatterplot for any particular pair of variates by simply identifying the
corresponding row and columns.
The scatterplot matrix also simplifies the visual comparison of the one variate
to each of several others by scanning along any single row (or column). Note
however that this single row scan does come at the price of doubling the number
of scatterplots in the display.
These two visual search facilities are diminished by the layout of a `zenplot`.
Although the same information is available in a `zenplot` the layout does not
lend itself to easy lookup from variates to plots. If the `zenplot` layout is
used in an interactive graphical system, other means of interaction could be
implemented to have, for example, all plots containing a particular variate (or
pair of variates) distinguish themselves visually by having their background
colour change temporarily.
On the other hand, the reverse lookup from plot to variates is simpler in a
`zenplot` than in a scatterplot matrix, particularly for large numbers of
variates.
Both layouts allow a visual search for patterns in the point configurations.
Having many plots be presented at once enables a quick visual search over a
large space for the existence of interesting point configurations
(e.g. correlations, outliers, grouping in data, lines, etc.).
When the number of plots is very large, an efficient compact layout can
dramatically increase the size of the visual search space. This is where
`zenplot`'s zigzag layout outperforms the scatterplot matrix.
This could be illustrated this on the following example.
### Example: German election data
In the `zenplots` package the data set `de_elect` contains the district results
of two German federal elections (2002 and 2005) as well as a number of
socio-economic variates as well.
```{r}
## Access the German election data from zenplots package
data(de_elect)
```
There are `r nrow(de_elect)` districts and `r ncol(de_elect)` variates yielding
a possible `choose(68,2) =` `r choose(68,2)` different scatterplots.
This many scatterplots will overwhelm a `pairs` plot. In its most compact form,
the pairs plot for the first 34 variates already occupies a fair bit of space:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## pairs(de_elect[,1:34], oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n")
```
(N.B. We do not execute any of these large plots simply to keep the storage
needs of this vignette to a minimum. We do encourage the reader to execute the
code however on their own.)
If you execute the above code you will see interesting point configurations
including: some very strong positive correlations, some positive and negative
correlations, non-linear relations, the existence of some outlying points,
clustering, striation, etc.
Because this scatterplot matrix is for only half of the variates it shows
`choose(34,2) =` `r choose(ncol(de_elect)/2,2)` different scatterplots, each one
twice. For a display of `r 2* choose(ncol(de_elect)/2,2)` plots, only about one
quarter of all `r choose(ncol(de_elect),2)` pairwise variate scatterplots
available in the data set appear in this display.
A second scatterplot matrix on the remaining 34 variates would also show only a
quarter of the plots. The remaining half, $34 \times 34 = 1156$ plots, are
missing from both plots.
In contrast, the `zenplot` shows all `r choose(ncol(de_elect),2)` plots at once.
In fact, because an Eulerian sequence requires a graph to be even (i.e. each
node has an even number of edges), whenever the number of variates, $p$, is even
`zenpath(...)` will repeat exactly $p/2$ pairs somewhere in the sequence it
returns.
To produce the `zenplot` of all pairs of variates on the German election data we
call `zenplot(de_elect[,zenpath(68)], pch=".")`. (Again, we don't produce it
here so as to minimize the storage footprint of this vignette.)
```{r message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Try invoking the plot with the following
## zenplot(de_elect[,zenpath(68)], pch=".", n2dcol="square",col=adjustcolor("black",0.5))
```
In approximately the same visual space as the scatterplot matrix (showing only
`r choose(ncol(de_elect)/2,2)` unique plots), the `zenplot` has efficiently and
compactly laid out all `r choose(ncol(de_elect),2)` different plots plus `r
ncol(de_elect)` duplicate plots. This efficient layout means that `zenplot` can
facilitate visual search for interesting point configurations over much larger
collections of variate pairs -- in the case of the German election data, this
all possible pairs of variates are presented simultaneously.
In contrast, all pairs loses most of the detail
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## pairs(de_elect, oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n",col=adjustcolor("black",0.5))
```
# Groups of pairwise plots
Zenplots also accomodate a list of data sets whose pairwise contents are to be
displayed. The need for this can arise quite naturally in many applications.
The German election data, for instance, contains socio-economic data whose
variates naturally group together. For example, we might gather variates
related to education into one group and those related to employment into
another.
```{r, message=FALSE, warning=FALSE}
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Employment <- c("Employed", "FFF", "Industry",
"CTT", "OS" )
```
We could plot all pairs for these two groups in a single `zenplot`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=6}
EducationData <- de_elect[, Education]
EmploymentData <- de_elect[, Employment]
## Plot all pairs within each group
zenplot(list(Educ= EducationData[, zenpath(ncol(EducationData))],
Empl= EmploymentData[, zenpath(ncol(EmploymentData))]))
```
All pairs of education variates are plotted first in zigzag order followed by a
blank plot then continuing in the same zigzag pattern by plots all pairs of
employment variates.
## All pairs by group
In addition to the `Education` and `Employment` groups above, a number of
different groupings of variates having a shared context. For example, these
might include the following:
```{r}
## Grouping variates in the German election data
Regions <- c("District", "State", "Density")
PopDist <- c("Men", "Citizens", "Pop.18.25", "Pop.25.35",
"Pop.35.60", "Pop.g.60")
PopChange <- c("Births", "Deaths", "Move.in", "Move.out", "Increase")
Agriculture <- c("Farms", "Agriculture")
Mining <- c("Mining", "Mining.employees")
Apt <- c("Apt.new", "Apt")
Motorized <- c("Motorized")
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Unemployment <- c("Unemployment.03", "Unemployment.04")
Employment <- c("Employed", "FFF", "Industry", "CTT", "OS" )
Voting.05 <- c("Voters.05", "Votes.05", "Invalid.05", "Valid.05")
Voting.02 <- c("Voters.02", "Votes.02", "Invalid.02", "Valid.02")
Voting <- c(Voting.02, Voting.05)
VotesByParty.02 <- c("Votes.SPD.02", "Votes.CDU.CSU.02", "Votes.Gruene.02",
"Votes.FDP.02", "Votes.Linke.02")
VotesByParty.05 <- c("Votes.SPD.05", "Votes.CDU.CSU.05", "Votes.Gruene.05",
"Votes.FDP.05", "Votes.Linke.05")
VotesByParty <- c(VotesByParty.02, VotesByParty.05)
PercentByParty.02 <- c("SPD.02", "CDU.CSU.02", "Gruene.02",
"FDP.02", "Linke.02", "Others.02")
PercentByParty.05 <- c("SPD.05", "CDU.CSU.05", "Gruene.05",
"FDP.05", "Linke.05", "Others.05")
PercentByParty <- c(PercentByParty.02, PercentByParty.05)
```
The groups can now be used to explore internal group relations for many
different groups in the same plot. Here the following helper function comes in handy.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=11, fig.height=14}
groups <- list(Regions=Regions, Pop=PopDist,
Change = PopChange, Agric=Agriculture,
Mining=Mining, Apt=Apt, Cars=Motorized,
Educ=Education, Unemployed=Unemployment, Employed=Employment#,
# Vote02=Voting.02, Vote05=Voting.05,
# Party02=VotesByParty.02, Party05=VotesByParty.05,
# Perc02=PercentByParty.02, Perc05=PercentByParty.05
)
group_paths <- lapply(groups, FUN= function(g) g[zenpath(length(g), method = "front.loaded")] )
x <- groupData(de_elect, indices=group_paths)
zenplot(x, pch = ".", cex=0.7, col = "grey10")
```
All pairs within each group are presented following the zigzag pattern; each
group is separated by an empty plot. The `zenplot` provides a quick overview of
the pairwise relationships between variates within all groups.
The plot can be improved some by using shorter names for the variates. With a little work we can replace these within each group of `x`.
```{r message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=10}
#
## Grouping variates in the German election data
RegionsShort <- c("ED", "State", "density")
PopDistShort <- c("men", "citizen", "18-25", "25-35", "35-60", "> 60")
PopChangeShort <- c("births", "deaths", "in", "out", "up")
AgricultureShort <- c("farms", "hectares")
MiningShort <- c("firms", "employees")
AptShort <- c("new", "all")
TransportationShort <- c("cars")
EducationShort <- c("finishers", "no.2nd", "2nd", "Real", "UED")
UnemploymentShort<- c("03", "04")
EmploymentShort <- c("employed", "FFF", "Industry", "CTT", "OS" )
Voting.05Short <- c("eligible", "votes", "invalid", "valid")
Voting.02Short <- c("eligible", "votes", "invalid", "valid")
VotesByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
VotesByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
PercentByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
PercentByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
shortNames <- list(RegionsShort, PopDistShort, PopChangeShort, AgricultureShort,
MiningShort, AptShort, TransportationShort, EducationShort,
UnemploymentShort, EmploymentShort, Voting.05Short, Voting.02Short,
VotesByParty.02Short, VotesByParty.05Short, PercentByParty.02Short,
PercentByParty.05Short)
# Now replace the names in x by these.
nGroups <- length(x)
for (i in 1:nGroups) {
longNames <- colnames(x[[i]])
newNames <- shortNames[[i]]
oldNames <- groups[[i]]
#print(longNames)
#print(newNames)
for (j in 1:length(longNames)) {
for (k in 1:length(newNames)) {
if (grepl(oldNames[k], longNames[j])) {
longNames[longNames == longNames[j]] <- newNames[k]
}
}
}
colnames(x[[i]]) <- longNames
}
zenplot(x, pch = ".", cex=0.75)
```
## Crossing pairs between groups
It can also be of interest to compare variates between groups. For example,
to compare the various levels of education with the employment categories.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=16}
crossedGroups <- c(Employment, Education)
crossedPaths <- zenpath(c(length(Employment), length(Education)), method="eulerian.cross")
zenplot(de_elect[,crossedGroups][crossedPaths])
```
# Other plots
A `zenplot` can be thought of as taking a data set whose variates are to be
plotted in the order given. A sequence of one dimensional plots, as determined
by the argument `plot1d`, are constructed in the order of the variates. Between
each pair of these `1d` plots, a two dimensional plot is constructed from the
variates of the `1d` plots. One variate provides the vertical `y` values and
the other the horizontal `x` values. If the orientation of the preceding
one-dimensional plot is horizontal, then that variate gives the `x` values; if
it's vertical then the vertical `y` coordinates.
## Built in `1d` and `2d` plots
The actual displays depend on the arguments `plot1d` and `plot2d`. There are
numerous built-in choices provided.
For `plot1d` any of the following strings may be selected to produce a one-dimensional plot:
` "label" `, ` "rug" `, ` "points" `, ` "jitter" `, ` "density" `, ` "boxplot"
`, ` "hist" `, ` "arrow" `, ` "rect" `, ` "lines" `. The first in the list is
the default.
For `plot2d` any of the following strings can be given:
` "points" `, ` "density" `, ` "axes" `, ` "label" `, ` "arrow" `, ` "rect" `.
Again, the first of these is the default value.
## Arbitrary layout using `turns`
For example, we could produce a `boxplot` for the measured variates of the
earthquake data as follows:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=2}
earthquakes <- attenu[, c(1,2,4,5)] # ignore the station id
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=5, width2d=1,
turns=c("r","r","r","r","r","r","r"))
```
There are a few things to note here. First that every variate in the data set
has a boxplot of its values presented and that the extent of boxplot display is
that variate's range. Second, the argument specification `plot2d=NULL` causes
a null plot to be produced for each of the variate pairs. Third, the arguments
`width1d` and `width2d` determine the relative widths of the two displays.
Finally, the argument `turns` determines the layout of the plots by specifying
where the next display (`1d` or `2d`) is to appear in relation to the current
one. Here every display appears to the right of the existing display.
An alternative layout of the same boxplots can be had by adjusting the `turns`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=1, width2d=1, # now widths must be the same
turns=c("r","d","d","l","l","u","u"))
```
To better see how the turns work, arrows could be used instead to show
the directions of the turns.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d= "arrow", plot2d="arrow",
width1d=1, width2d=2,
turns=c("r","d","d","l","l","u","u"))
```
Adding a rectangle to outline the drawing space will make the layout a little clearer and illustrate the arguments that are passed on to the pne and two dimensional plot functions.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d = function(zargs, ...) {
rect_1d_graphics(zargs, ...)
arrow_1d_graphics(zargs, col="firebrick", lwd=3, add=TRUE, ...)
},
plot2d = function(zargs, ...) {
rect_2d_graphics(zargs, ...)
arrow_2d_graphics(zargs, col="steelblue", lwd=3, lty=2, add=TRUE, ...)
},
width1d = 1, width2d = 2,
turns=c("r","d","d","l","l","u","u"))
```
The red arrows are the turns for the `1d` plots, the blue dashed arrows
for the `2d` plots. The turns are interlaced and begin at the topmost red arrow
for the `1d` plot. It points right, matching the first turn `"r"` in the list
of `turns`. The remaining arrows follow each other in clockwise order. As can
be seen, there is an arrow for each plot: red for the `1d` plots, black for the
`2d` plots.
## Arbitrary plots
The above example also introduces some other important features of `zenplot`.
The value `"arrow"` of `plot2d` argument caused an arrow to be drawn wherever a
`2d` plot was to appear in the direction of the turn associated with that plot.
As the value of `plot1d` here suggests, the argument could also have been a
function.
In fact, when given a string value for `plot2d`, `zenplot` calls a function
whose name is constructed with this string. In the case of `plot2d = "arrow"`,
`zenplot` calls the function `arrow_2d_graphics` to produce a `2d` plot whenever
one is required. The naming convention constructs the function name from the
string supplied, here "arrow", the dimensionality of the plot (here `2d`) and
the `R` graphics package that is being used (here the base `graphics` package).
The function of that name is called on arguments appropriate to draw the plot.
The same construction is also used when a string is given as the value of the
`plot1d` argument. For example `plot1d = "arrow"` causes the function named
`arrow_1d_graphics` to be called to draw the `1d` plots.
Should, for example, the user wish to extend the base functionality of `zenplot`
to include say `"myplot"`, they need only write functions `myplot_1d_graphics`
and/or `myplot_2d_graphics` to allow the value `"myplot"` to be used for
`plot1d` and/or `plot2d` in the base `graphics` package in `R`. Note that two
other `R` plotting packages besides the base `graphics` are supported by
`zenplot`, namely either the highly customizable `grid` package or the highly
interactive `loon` package. The default package is `graphics` but either of the
other two may be specified via the `pkg` argument to `zenplot` as in `pkg =
"grid"` or `pkg = "loon"`.
When `zenplot` is called with `plot1d="arrow"`, say, then one of the functions
`arrow_1d_graphics`, `arrow_1d_grid`, or `arrow_1d_loon` will be called upon
depending on the value of the argument `pkg`. This means that a true extension
of `zenplot` to include, say, `plot1d = "myplot"` would require writing three
functions, namely `myplot_1d_graphics`, `myplot_1d_grid`, and `myplot_1d_loon`,
to complete the functionality.
More often, as shown in the boxplot example, it will be a one-off functionality
that might be required for either `plot2d` or `plot1d`.
In this case, any function passed as the argument value will be used by
`zenplot` to construct the corresponding plots. In the boxplot example, the
default functions `boxplot_1d_graphics` and `arrow_1d_graphics` were both called
so that one could be plotted on top of the other in each `1d` plot of the
`zenplot`.
### Example: mixing plots to assess distributions
`zenplot` can be used to layout graphics produced by any of the three `pkg`
(i.e. `graphics`, `grid`, or `loon`) provided all graphics used are from the
**same** package.
For example, suppose we were interested in the marginal distributions of the
earthquake data. We might craft the following plot to investigate all marginal
distributions and to compare each marginal to every other (i.e. all pairs).
```{r, message=FALSE, warning=FALSE, results="hide", fig.align="center", fig.width=6, fig.height=3}
library(qqtest)
zenplot(earthquakes[,zenpath(ncol(earthquakes))],
width1d = 1, width2d = 2, n2dcol=5,
plot1d = function(zargs, ...) {
r <- extract_1d(zargs) # extract arguments for 1d
col <- adjustcolor(if (r$horizontal) "firebrick" else "steelblue",
alpha.f = 0.7)
hist_1d_graphics(zargs, col=col, ...)
},
plot2d=function(zargs, ...) {
r <- extract_2d(zargs) # extract arguments for 2d
x <- as.matrix(r$x)
xlim <- r$xlim
y <- as.matrix(r$y)
ylim <- r$ylim
qqtest(y, dataTest=x,
xlim=xlim, ylim=ylim,
cex=0.3, col="black", pch=19,
legend=FALSE, main="", axes=FALSE, ...)
})
```
Here we are using the function `qqtest` from the package of that name and whose
display capability is built using only the base `graphics` package. For `2d`
data `qqtest` compares the two empirical distributions by drawing an empirical
quantile-quantile plot which should be near a straight line if the marginal
distributions are of the same shape. The empirical quantile-quantile plot is
supplemented by simulated values of empirical quantiles from the empirical
distribution of the horizontal variate. The results of 1,000 draws from this
distribution are shown in shades of grey on the qqplot. The `1d` plots are
shown as histograms coloured `"grey"` when that histogram was used to generate
the simulated values and in `"steelblue"` when the histogram was not.
As can be seen from the qqplots, since numerous points are outside the gray
envelopes of each plot, no two marginal distributions would appear to be alike.
## Arguments to `plot1d` functions
Every `plot1d` function must take arbitrarily many arguments, accepting at least
the following set:
- `x`, a vector of values for a single variate
- `horizontal`, which is `TRUE` if the `1d` plot is to be horizontal,
- `plotAsp`, the aspect ratio of the plot (i.e. the smaller/larger side ration in [0,1])
- `turn`, the single character turn out from the current plot
- `plotID`, a list containing information on the identification of the `plot`.
If the `plot1d` function is from the package `grid`, then it should also expect
to receive a `vp` or viewport argument; if it is from the package `loon`, it
might also receive a `parent` argument. These arguments should be familiar to
users of either package.
For a `plot1d` function, the `plotID` consists of
- `group`, the number of the group in which this `1d` plot is placed,
- `number.within.group`, the within group index of this variate,
- `index` , the index of the variate among all variates in the data set(s)
- `label`, the variate label, and
- `plotNo`, the number of the `1d` plot being displayed (i.e its position in
order among only those which are `1d`).
All other functions in the ellipsis, `...`, are passed on to the drawing functions.
## Arguments to `plot2d` functions
Every `plot2d` function must take arbitrarily many arguments, accepting at least
the following set:
- `x`, a vector of values for the horizontal variate
- `y`, a vector of values for the vertical variate
- `turn`, the single character turn out from the current plot
- `plotID`, a list containing information on the identification of the `plot`.
If the `plot2d` function is from the package `grid`, then it should also expect
to receive a `vp` or viewport argument; if it is from the package `loon`, it
might also receive a `parent` argument. These arguments should be familiar to
users of either package.
For a `plot2d` function, the `plotID` consists of
- `group`, the number of the group in which this `2d` plot is placed,
- `number.within.group`, the within group index for these variates (same index),
- `index` , the indices of the variates among all variates in the data set(s)
- `label`, the labels of the variates, and
- `plotNo`, the number of the `2d` the plot being displayed (i.e its position
in order among only those which are `2d`).
All other functions in the ellipsis, `...`, are passed on to the drawing
functions.
| /scratch/gouwar.j/cran-all/cranData/zenplots/inst/doc/intro.Rmd |
## ----setup, message = FALSE---------------------------------------------------
# attaching required packages
library(PairViz)
library(MASS)
library(zenplots)
## ---- message = FALSE---------------------------------------------------------
data(olive, package = "zenplots")
## ---- fig.align = "center", fig.width = 6, fig.height = 8---------------------
zenplot(olive)
## ---- fig.align = "center", fig.width = 6, fig.height = 8---------------------
zenplot(olive, plot1d = "layout", plot2d = "layout")
## ---- eval = FALSE------------------------------------------------------------
# str(zenplot)
## ---- eval = FALSE------------------------------------------------------------
# function (x, turns = NULL, first1d = TRUE, last1d = TRUE,
# n2dcols = c("letter", "square", "A4", "golden", "legal"),
# n2dplots = NULL,
# plot1d = c("label", "points", "jitter", "density", "boxplot",
# "hist", "rug", "arrow", "rect", "lines", "layout"),
# plot2d = c("points", "density", "axes", "label", "arrow",
# "rect", "layout"),
# zargs = c(x = TRUE, turns = TRUE, orientations = TRUE,
# vars = TRUE, num = TRUE, lim = TRUE, labs = TRUE,
# width1d = TRUE, width2d = TRUE,
# ispace = match.arg(pkg) != "graphics"),
# lim = c("individual", "groupwise", "global"),
# labs = list(group = "G", var = "V", sep = ", ", group2d = FALSE),
# pkg = c("graphics", "grid", "loon"),
# method = c("tidy", "double.zigzag", "single.zigzag"),
# width1d = if (is.null(plot1d)) 0.5 else 1,
# width2d = 10,
# ospace = if (pkg == "loon") 0 else 0.02,
# ispace = if (pkg == "graphics") 0 else 0.037, draw = TRUE, ...)
## -----------------------------------------------------------------------------
olive2 <- cbind(olive, olive) # just for this illustration
## ---- fig.align = "center", fig.width = 8, fig.height = 13.3------------------
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "single.zigzag")
## ---- fig.align = "center", fig.width = 8, fig.height = 8---------------------
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "double.zigzag")
## ---- fig.align = "center", fig.width = 8, fig.height = 6.6-------------------
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "tidy")
## ---- fig.align = "center", fig.width = 8, fig.height = 5.4-------------------
zenplot(olive2, n2dcols = 6, plot1d = "arrow", plot2d = "layout",
method = "rectangular")
## ---- fig.align = "center", fig.width = 6, fig.height = 10--------------------
zenplot(olive, plot1d = "layout", plot2d = "layout", method = "double.zigzag",
last1d = FALSE, ispace = 0.1)
## ---- fig.align = "center", fig.width = 6, fig.height = 7---------------------
zenplot(olive, plot1d = "layout", plot2d = "layout", n2dcol = 4, n2dplots = 8,
width1d = 2, width2d = 4)
## -----------------------------------------------------------------------------
(path <- 1:5)
## -----------------------------------------------------------------------------
(path <- zenpath(5))
## ---- eval = FALSE------------------------------------------------------------
# zenplot(x = dataMat[,path])
## ---- eval = FALSE------------------------------------------------------------
# str(zenpath)
## ---- eval = FALSE------------------------------------------------------------
# function (x, pairs = NULL,
# method = c("front.loaded", "back.loaded", "balanced",
# "eulerian.cross", "greedy.weighted", "strictly.weighted"),
# decreasing = TRUE)
## -----------------------------------------------------------------------------
zenpath(5, method = "front.loaded")
zenpath(5, method = "back.loaded")
zenpath(5, method = "balanced")
## -----------------------------------------------------------------------------
zenpath(c(3,5), method = "eulerian.cross")
## ---- fig.align = "center", fig.width = 6, fig.height = 9---------------------
oliveAcids <- olive[, !names(olive) %in% c("Area", "Region")] # acids only
zpath <- zenpath(ncol(oliveAcids)) # all pairs
zenplot(oliveAcids[, zpath], plot1d = "hist", plot2d = "density")
## ---- fig.align = "center", fig.width = 8, fig.height = 7.2, eval = FALSE-----
# path <- c(1,2,3,1,4,2,5,1,6,2,7,1,8,2,3,4,5,3,6,4,7,3,8,4,5,6,7,5,8,6,7,8)
# turns <- c("l",
# "d","d","r","r","d","d","r","r","u","u","r","r","u","u","r","r",
# "u","u","l","l","u","u","l","l","u","u","l","l","d","d","l","l",
# "u","u","l","l","d","d","l","l","d","d","l","l","d","d","r","r",
# "d","d","r","r","d","d","r","r","d","d","r","r","d","d")
#
# library(ggplot2) # for ggplot2-based 2d plots
# stopifnot(packageVersion("ggplot2") >= "2.2.1") # need 2.2.1 or higher
# ggplot2d <- function(zargs) {
# r <- extract_2d(zargs)
# num2d <- zargs$num/2
# df <- data.frame(x = unlist(r$x), y = unlist(r$y))
# p <- ggplot() +
# geom_point(data = df, aes(x = x, y = y), cex = 0.1) +
# theme(axis.line = element_blank(),
# axis.ticks = element_blank(),
# axis.text.x = element_blank(),
# axis.text.y = element_blank(),
# axis.title.x = element_blank(),
# axis.title.y = element_blank())
# if(num2d == 1) p <- p +
# theme(panel.background = element_rect(fill = 'royalblue3'))
# if(num2d == (length(zargs$turns)-1)/2) p <- p +
# theme(panel.background = element_rect(fill = 'maroon3'))
# ggplot_gtable(ggplot_build(p))
# }
#
# zenplot(as.matrix(oliveAcids)[,path], turns = turns, pkg = "grid",
# plot2d = function(zargs) ggplot2d(zargs))
## -----------------------------------------------------------------------------
oliveAcids.by.area <- split(oliveAcids, f = olive$Area)
# Replace the "." by " " in third group's name
names(oliveAcids.by.area)[3] <- gsub("\\.", " ", names(oliveAcids.by.area)[3])
names(oliveAcids.by.area)
## ---- fig.align = "center", fig.width = 6, fig.height = 8---------------------
zenplot(oliveAcids.by.area, labs = list(group = NULL))
## ---- fig.align = "center", fig.width = 6, fig.height = 8---------------------
zenplot(oliveAcids.by.area, lim = "groupwise", labs = list(sep = " - "),
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.8),
plot2d = function(zargs)
points_2d_graphics(zargs, group... = list(sep = "\n - \n")))
## ---- message = FALSE---------------------------------------------------------
library(scagnostics)
Y <- scagnostics(oliveAcids) # compute scagnostics (scatter-plot diagonstics)
X <- Y["Convex",] # pick out component 'convex'
d <- ncol(oliveAcids)
M <- matrix(NA, nrow = d, ncol = d) # matrix with all 'convex' scagnostics
M[upper.tri(M)] <- X # (i,j)th entry = scagnostic of column pair (i,j) of oliveAcids
M[lower.tri(M)] <- t(M)[lower.tri(M)] # symmetrize
round(M, 5)
## -----------------------------------------------------------------------------
zpath <- zenpath(M, method = "strictly.weighted") # list of ordered pairs
head(M[do.call(rbind, zpath)]) # show the largest six 'convexity' measures
## -----------------------------------------------------------------------------
(ezpath <- extract_pairs(zpath, n = c(6, 0))) # extract the first six pairs
## ---- message = FALSE, fig.align = "center", fig.width = 6, fig.height = 6----
library(graph)
library(Rgraphviz)
plot(graph_pairs(ezpath)) # depict the six most convex pairs (edge = pair)
## -----------------------------------------------------------------------------
(cezpath <- connect_pairs(ezpath)) # keep the same order but connect the pairs
## -----------------------------------------------------------------------------
oliveAcids.grouped <- groupData(oliveAcids, indices = cezpath) # group data for (zen)plotting
## ---- fig.align = "center", fig.width = 6, fig.height = 8---------------------
zenplot(oliveAcids.grouped)
## -----------------------------------------------------------------------------
res <- zenplot(olive, plot1d = "layout", plot2d = "layout", draw = FALSE)
str(res)
## -----------------------------------------------------------------------------
res[["path"]][["occupancy"]]
## -----------------------------------------------------------------------------
head(res[["path"]][["positions"]])
## -----------------------------------------------------------------------------
points_2d_graphics
## -----------------------------------------------------------------------------
plot_region
## -----------------------------------------------------------------------------
plot_indices
## -----------------------------------------------------------------------------
n2dcols <- ncol(olive) - 1 # number of faces of the hypercube
uf <- unfold(nfaces = n2dcols)
identical(res, uf) #return FALSE
for(name in names(uf)) {
stopifnot(identical(res[[name]], uf[[name]]))
}
| /scratch/gouwar.j/cran-all/cranData/zenplots/inst/doc/selected_features.R |
---
title: 'Zigzag expanded navigation plots in R: The R package zenplots'
author: M. Hofert and R. W. Oldford
date: '`r Sys.Date()`'
output:
rmarkdown::html_vignette: # lighter version than 'rmarkdown::html_document'; see https://bookdown.org/yihui/rmarkdown/r-package-vignette.html; there is also knitr:::html_vignette but it just calls rmarkdown::html_document with a custom .css
css: style.css # see 3.8 in https://bookdown.org/yihui/rmarkdown/r-package-vignette.html
vignette: >
%\VignetteIndexEntry{Zigzag expanded navigation plots in R: The R package zenplots}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
This vignette accompanies the paper "Zigzag expanded navigation plots in R: The R package zenplots".
Note that sections are numbered accordingly (or omitted). Furthermore, it is
recommended to read the paper to follow this vignette.
```{r setup, message = FALSE}
# attaching required packages
library(PairViz)
library(MASS)
library(zenplots)
```
## 2 Zenplots
As example data, we use the `olive` data set:
```{r, message = FALSE}
data(olive, package = "zenplots")
```
Reproducing the plots of Figure 1:
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(olive)
```
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(olive, plot1d = "layout", plot2d = "layout")
```
Considering the `str()`ucture of `zenplot()` (here formatted for nicer output):
```{r, eval = FALSE}
str(zenplot)
```
```{r, eval = FALSE}
function (x, turns = NULL, first1d = TRUE, last1d = TRUE,
n2dcols = c("letter", "square", "A4", "golden", "legal"),
n2dplots = NULL,
plot1d = c("label", "points", "jitter", "density", "boxplot",
"hist", "rug", "arrow", "rect", "lines", "layout"),
plot2d = c("points", "density", "axes", "label", "arrow",
"rect", "layout"),
zargs = c(x = TRUE, turns = TRUE, orientations = TRUE,
vars = TRUE, num = TRUE, lim = TRUE, labs = TRUE,
width1d = TRUE, width2d = TRUE,
ispace = match.arg(pkg) != "graphics"),
lim = c("individual", "groupwise", "global"),
labs = list(group = "G", var = "V", sep = ", ", group2d = FALSE),
pkg = c("graphics", "grid", "loon"),
method = c("tidy", "double.zigzag", "single.zigzag"),
width1d = if (is.null(plot1d)) 0.5 else 1,
width2d = 10,
ospace = if (pkg == "loon") 0 else 0.02,
ispace = if (pkg == "graphics") 0 else 0.037, draw = TRUE, ...)
```
### 2.1 Layout
To investigate the layout options of zenplots a bit more, we need a larger data set. To this end we
simply double the olive data here (obviously only for illustration purposes):
```{r}
olive2 <- cbind(olive, olive) # just for this illustration
```
Reproducing the plots of Figure 2:
```{r, fig.align = "center", fig.width = 8, fig.height = 13.3}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "single.zigzag")
```
```{r, fig.align = "center", fig.width = 8, fig.height = 8}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "double.zigzag")
```
```{r, fig.align = "center", fig.width = 8, fig.height = 6.6}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "tidy")
```
Note that there is also `method = "rectangular"` (leaving the zigzagging zenplot paradigm but
being useful for laying out 2d plots which are not necessarily connected through a variable; note
that in this case, we omit the 1d plots as the default (labels) is rather confusing in this
example):
```{r, fig.align = "center", fig.width = 8, fig.height = 5.4}
zenplot(olive2, n2dcols = 6, plot1d = "arrow", plot2d = "layout",
method = "rectangular")
```
Reproducing the plots of Figure 3:
```{r, fig.align = "center", fig.width = 6, fig.height = 10}
zenplot(olive, plot1d = "layout", plot2d = "layout", method = "double.zigzag",
last1d = FALSE, ispace = 0.1)
```
```{r, fig.align = "center", fig.width = 6, fig.height = 7}
zenplot(olive, plot1d = "layout", plot2d = "layout", n2dcol = 4, n2dplots = 8,
width1d = 2, width2d = 4)
```
## 3 Zenpaths
A very basic path (standing for the sequence of pairs (1,2), (2,3), (3,4), (4,5)):
```{r}
(path <- 1:5)
```
A zenpath through all pairs of variables (Eulerian):
```{r}
(path <- zenpath(5))
```
If `dataMat` is a five-column matrix, the zenplot of all pairs would then be constructed as follows:
```{r, eval = FALSE}
zenplot(x = dataMat[,path])
```
The `str()`ucture of `zenpath()` (again formatted for nicer output):
```{r, eval = FALSE}
str(zenpath)
```
```{r, eval = FALSE}
function (x, pairs = NULL,
method = c("front.loaded", "back.loaded", "balanced",
"eulerian.cross", "greedy.weighted", "strictly.weighted"),
decreasing = TRUE)
```
Here are some methods for five variables:
```{r}
zenpath(5, method = "front.loaded")
zenpath(5, method = "back.loaded")
zenpath(5, method = "balanced")
```
The following method considers two groups: One of size three, the other of size five.
The sequence of pairs is constructed such that the first variable comes from the first group,
the second from the second.
```{r}
zenpath(c(3,5), method = "eulerian.cross")
```
Reproducing Figure 4:
```{r, fig.align = "center", fig.width = 6, fig.height = 9}
oliveAcids <- olive[, !names(olive) %in% c("Area", "Region")] # acids only
zpath <- zenpath(ncol(oliveAcids)) # all pairs
zenplot(oliveAcids[, zpath], plot1d = "hist", plot2d = "density")
```
## 4 Build your own zenplots
### 4.3 Custom layout and plots -- a spiral of ggplots example
Figure 5 can be reproduced as follows (note that we do not show the plot
here due to a CRAN issue when running this vignette):
```{r, fig.align = "center", fig.width = 8, fig.height = 7.2, eval = FALSE}
path <- c(1,2,3,1,4,2,5,1,6,2,7,1,8,2,3,4,5,3,6,4,7,3,8,4,5,6,7,5,8,6,7,8)
turns <- c("l",
"d","d","r","r","d","d","r","r","u","u","r","r","u","u","r","r",
"u","u","l","l","u","u","l","l","u","u","l","l","d","d","l","l",
"u","u","l","l","d","d","l","l","d","d","l","l","d","d","r","r",
"d","d","r","r","d","d","r","r","d","d","r","r","d","d")
library(ggplot2) # for ggplot2-based 2d plots
stopifnot(packageVersion("ggplot2") >= "2.2.1") # need 2.2.1 or higher
ggplot2d <- function(zargs) {
r <- extract_2d(zargs)
num2d <- zargs$num/2
df <- data.frame(x = unlist(r$x), y = unlist(r$y))
p <- ggplot() +
geom_point(data = df, aes(x = x, y = y), cex = 0.1) +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank())
if(num2d == 1) p <- p +
theme(panel.background = element_rect(fill = 'royalblue3'))
if(num2d == (length(zargs$turns)-1)/2) p <- p +
theme(panel.background = element_rect(fill = 'maroon3'))
ggplot_gtable(ggplot_build(p))
}
zenplot(as.matrix(oliveAcids)[,path], turns = turns, pkg = "grid",
plot2d = function(zargs) ggplot2d(zargs))
```
### 4.4 Data groups
Split the olive data set into three groups (according to their variable `Area`):
```{r}
oliveAcids.by.area <- split(oliveAcids, f = olive$Area)
# Replace the "." by " " in third group's name
names(oliveAcids.by.area)[3] <- gsub("\\.", " ", names(oliveAcids.by.area)[3])
names(oliveAcids.by.area)
```
Reproducing the plots of Figure 6 (note that `lim = "groupwise"` does not
make much sense here as a plot):
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.by.area, labs = list(group = NULL))
```
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.by.area, lim = "groupwise", labs = list(sep = " - "),
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.8),
plot2d = function(zargs)
points_2d_graphics(zargs, group... = list(sep = "\n - \n")))
```
### 4.5 Custom zenpaths
Find the "convexity" scagnostic for each pair of olive acids.
```{r, message = FALSE}
library(scagnostics)
Y <- scagnostics(oliveAcids) # compute scagnostics (scatter-plot diagonstics)
X <- Y["Convex",] # pick out component 'convex'
d <- ncol(oliveAcids)
M <- matrix(NA, nrow = d, ncol = d) # matrix with all 'convex' scagnostics
M[upper.tri(M)] <- X # (i,j)th entry = scagnostic of column pair (i,j) of oliveAcids
M[lower.tri(M)] <- t(M)[lower.tri(M)] # symmetrize
round(M, 5)
```
Show the six pairs with largest "convexity" scagnostic:
```{r}
zpath <- zenpath(M, method = "strictly.weighted") # list of ordered pairs
head(M[do.call(rbind, zpath)]) # show the largest six 'convexity' measures
```
Extract the corresponding pairs:
```{r}
(ezpath <- extract_pairs(zpath, n = c(6, 0))) # extract the first six pairs
```
Reproducing Figure 7 (visualizing the pairs):
```{r, message = FALSE, fig.align = "center", fig.width = 6, fig.height = 6}
library(graph)
library(Rgraphviz)
plot(graph_pairs(ezpath)) # depict the six most convex pairs (edge = pair)
```
Connect them:
```{r}
(cezpath <- connect_pairs(ezpath)) # keep the same order but connect the pairs
```
Build the corresponding list of matrices:
```{r}
oliveAcids.grouped <- groupData(oliveAcids, indices = cezpath) # group data for (zen)plotting
```
Reproducing Figure 8 (zenplot of the six pairs of acids with largest "convexity" scagnostic):
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.grouped)
```
## 5 Advanced features
### 5.1 The structure of a zenplot
Here is the structure of a return object of `zenplot()`:
```{r}
res <- zenplot(olive, plot1d = "layout", plot2d = "layout", draw = FALSE)
str(res)
```
Let's have a look at the components. The occupancy matrix encodes the occupied
cells in the rectangular layout:
```{r}
res[["path"]][["occupancy"]]
```
The two-column matrix `positions` contains in the *i*th row the row and column
index (in the occupancy matrix) of the *i*th plot:
```{r}
head(res[["path"]][["positions"]])
```
### 5.2 Tools for writing 1d and 2d plot functions
Example structure of 2d plot based on `graphics`:
```{r}
points_2d_graphics
```
For setting up the plot region of plots based on `graphics`:
```{r}
plot_region
```
Determining the indices of the two variables to be plotted in the current 1d or 2d plot
(the same for 1d plots):
```{r}
plot_indices
```
Basic check that the return value of `zenplot()` is actually the return value of the
underlying `unfold()` (note that, the output of `unfold` and `res` is not identical since `res` has specific class attributes):
```{r}
n2dcols <- ncol(olive) - 1 # number of faces of the hypercube
uf <- unfold(nfaces = n2dcols)
identical(res, uf) #return FALSE
for(name in names(uf)) {
stopifnot(identical(res[[name]], uf[[name]]))
}
```
| /scratch/gouwar.j/cran-all/cranData/zenplots/inst/doc/selected_features.Rmd |
---
title: Introduction to zenplots
author: M. Hofert and R. W. Oldford
date: '`r Sys.Date()`'
output:
html_vignette:
toc: yes
css: style.css
pdf_document:
keep_tex: yes
latex_engine: xelatex
number_sections: yes
toc: yes
word_document: default
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Introduction to zenplots}
%\VignetteEncoding{UTF-8}
---
```{r, message=FALSE, warning=FALSE}
library(zenplots)
```
# All pairs
A `zenplot` can show the same information as a `pairs` plot but with two
important display differences.
First, the matrix organization of the `pairs` layout is replaced by the
"zig-zag" layout of `zenplot`. Second, the number of plots produced is about
half that of a `pairs` plot allowing each plot in a `zenplot` to be given more
visual space.
## Producing all pairs with `PairViz`
A convenient function to produce all pairs can be found in the `PairViz` package
found on `cran` and installed in `R` via `install.packages("PairViz")`.
```{r, message=FALSE, warning=FALSE}
library(PairViz)
```
We will illustrate this functionality and the difference between a `pairs` plot
and a `zenplot` by first considering a small dataset on earthquakes having only
a few variates. The difference between the two plots becomes much more
important for data having larger numbers of variates -- we illustrate the
difference again using German data on voting patterns in two elections.
### Example: Ground acceleration of earthquakes
The built-in `R` data set called `attenu` contains measurements to estimate the
attenuating effect of distance on the ground acceleration of earthquakes in
California.
There are `r ncol(attenu)` different variates used to describe the peak
acceleration of 23 California earthquakes measured at different observation
stations. The data set contains `r nrow(attenu)` different peak acceleration
measurements and has some missing data. The first few cases of the data set
look like
```{r}
head(attenu)
```
Its variates are
```{r, echo=FALSE}
names(attenu)
```
and we are interested in all pairs of these variates.
To get these, first imagine a graph having as its nodes the variates of the
data. An edge of this graph connects two nodes and hence represents a pair of
variates. If interest lies in all pairs of varates, then the graph is a
complete graph -- it will have an edge between every pair of nodes. An ordering
of variate pairs corresponds to any path on the graph. To have an ordering of
all pairs of variates, the path must visit all edges and is called an Eulerian,
or Euler path. Such a path always exists for complete graphs on an odd number
of nodes; when the number of nodes is even, extra edges must be added to the
graph before an Eulerian can exist.
For a complete graph with n nodes, the function `eseq` (for Euler sequence)
function from the `PairViz` package returns an order in which the nodes
(numbered 1 to n) can be visited to produce an Euler path. It works as follows.
```{r, message=FALSE, warning=FALSE}
## Since attenu has 5 variates, the complete graph has n=5 nodes
## and an Euler sequence is given as
eseq(5)
```
In terms of the variate names of `attenu`, this is:
```{r, message=FALSE, warning=FALSE}
names(attenu)[eseq(5)]
```
As can be seen in the corresponding complete graph below,
```{r, echo=FALSE, message=FALSE, warning=FALSE, fig.align="center" }
library(Rgraphviz)
parOptions <- par(no.readonly = TRUE)
plot(mk_complete_graph(names(attenu)), "circo")
par(parOptions)
```
this sequence traces an Eulerian path on the complete graph and so presents
every variate next to every other variate somewhere in the order.
#### Euler sequences via `zenpath`
This functionality (and more) from `PairViz` has been bundled together in the
`zenplots` package as a single function `zenpath`. For example,
```{r, message=FALSE, warning=FALSE, fig.align="center" }
zenpath(5)
```
This sequence, while still Eulerian, is slightly different than that returned by
`eseq(5)`. The sequence is chosen so that all pairs involving the first index
appear earliest in the sequence, then all pairs involving the second index, and
so on. We call this a "front loaded" sequence and identify it with the
`zenpath` argument `method = "front.loaded"`. Other possibilities are `method =
"back.loaded"` and `method = "balanced"` giving the following sequences:
```{r, message=FALSE, warning=FALSE, fig.align="center" }
## Back loading ensures all pairs appear latest (back) for
## high values of the indices.
zenpath(5, method = "back.loaded")
## Frot loading ensures all pairs appear earliest (front) for
## low values of the indices.
zenpath(5, method = "front.loaded")
## Balanced loading ensures all pairs appear in groups of all
## indices (Hamiltonian paths -> a Hamiltonian decomposition of the Eulerian)
zenpath(5, method = "balanced")
```
The differences are easier to see when there are more nodes. Below, we show the
index ordering (top to bottom) for each of these three methods when the graph
has 15 nodes, here labelled"a" to "o" (to make plotting
easier).
```{r zenpath, echo= FALSE, include=FALSE, fig.align="center"}
parOptions <- par(mfrow=c(1,3), mar=c(4, 2,2,0),oma=rep(0,4))
back <- zenpath(15, method = "back.loaded")
balanced <- zenpath(15, method = "balanced")
front <- zenpath(15, method = "front.loaded")
n <- length(zenpath(15))
plot_chars <- letters[1:15]
plot(back, n - 1:n,type="b", ylab="", xlab="", main="Back loaded",
pch=plot_chars[back], bty="n", xaxt="n", yaxt="n")
plot(balanced, n - 1:n,type="b", ylab="", xlab="", main="Balanced",
pch=plot_chars[balanced], bty="n", xaxt="n", yaxt="n")
plot(front, n - 1:n,type="b", ylab="", xlab="", main="Front loaded",
pch=plot_chars[front], bty="n", xaxt="n", yaxt="n")
par(parOptions)
```
Starting from the bottom (the back of the sequence), "back loading" has the last
index, "o", complete its pairing with every other index before "n" completes
all of its pairings. All of "n"'s pairings complete before those of "m", all of
"m"'s before "l", and so on until the last pairing of "a" and "b" are completed.
Note that the last indices still appear at the end of the sequence (since the
sequence begins at the top of the display and moves down). The term "back
loading" is used here in a double sense - the later (back) indices have their
pairings appear as closely together as possible towards the back of the returned
sequence. A simple reversal, that is `rev(zenpath(15, method = "back.loaded"))`,
would have them appear at the beginning of the sequence. In
this case the "back loading" would only be in one sense, namely that the later
indexed (back) nodes appear first in the reversed sequence.
Analogously, "front loading" has the first (front) indices appear at the front
of the sequence with their pairings appear as closely together as possible.
The "balanced" case ensures that all indices appear in each block of pairings.
In the figure there are 7 blocks.
All three sequences are Eulerian, meaning all pairs appear somewhere in each
sequence.
#### Pairs plots versus zenplots
Eulerian sequences can now be used to compare a `pairs` plot with a `zenplot`
when all pairs of variates are to be displayed.
First a pairs plot:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## We remove the space between plots and suppress the axes
## so as to give maximal space to the individual scatterplots.
## We also choose a different plotting character and reduce
## its size to better distinguish points.
pairs(attenu, oma=rep(0,4), gap=0, xaxt="n", yaxt="n")
```
We now effect a display of all pairs using `zenplot`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Plotting character and size are chosen to match that
## of the pairs plot.
## zenpath ensures that all pairs of variates appear
## in the zenplot.
## The last argument, n2dcol, is chosen so that the zenplot
## has the same number of plots across the page as does the
## pairs plot.
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=4)
```
Each display shows scatterplot of all `choose(5,2) =` `r choose(ncol(attenu),
2)` pairs of variates for this data. Each display occupies the same total area.
With `pairs` each plot is displayed twice and arranged in a symmetric matrix
layout with the variate labels appearing along the diagonal. This makes for
easy look-up but uses a lot of space.
With `zenplot`, each plot appears only once with its coordinate defining
variates appearing as labels on horizontal (top or bottom) and vertical (left or
right) axis positions. The layout follows the order of the variates in which
the variates appear in the call to `zenplot` beginning in the top left corner of
the display and then zig-zagging from top left to bottom right; when the
rightmost boundary or the display is reached, the direction is reversed
horizontally and the zigzag moves from top right to bottom left. The following
display illustrates the pattern (had by simply calling `zenplot`):
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Call zenplot exactly as before, except that each scatterplot is replaced
## by an arrow that shows the direction of the layout.
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow", n2dcol=4)
```
The zig zag pattern of plots appears as follows.
- The top left plot (of either `zenplot` display) has horizontal variate `event`
and vertical variate `mag`.
- To its right is a plot sharing the same vertical variate `mag` but now with
horizontal variate `station`. Note that the variate `station` has some
missing values and this is recorded on its label as `station (some NA)`.
- Below this a plot appears with the same horizontal variate `station` but now
with vertical variate `event`. Since this is the first repeat appearance of
`event` it appears with a suffix as `event.1`.
- To its right is a plot with shared vertical variate `event` and new horizontal
variate `dist`.
- Below this is a plot having shared horizontal variate `dist` and as vertical
variate the first repeat of the variate `mag`.
- To its right is a plot having shared vertical variate `mag` and new horizontal
variate `accel`.
- The right edge of the display is reached and the zigzag changes horizontal
direction repeating the pattern until either the left edge is reached
(whereupon the horizontal direction is reversed) or the variates are
exhausted.
Like the `pairs` plot, the `zenplot` lays its plots out on a two dimensional
grid -- the argument `n2dcol=4` specifies the number of columns for the 2d
plots (e.g. scatterplots). As shown, this can lead to a lot of unused space in
the display.
The `zenplot` layout can be made more compact by different choices of the
argument `n2dcol` (odd values provide a more compact layout). For example,
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=6}
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))], n2dcol=5)
```
By default, `zenplot` tries to determine a value for `n2dcol` that minimizes the
space unused by its zigzag layout.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10}
## The default n2dcol is used
zenplot(attenu[, zenpath(ncol(attenu))])
```
with layout directions as
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=10}
## The directions
zenplot(attenu[, zenpath(ncol(attenu))], plot2d="arrow")
```
As the direction arrows show, the default layout is to zigzag horizontally first
as much as possible.
This is clearly a much more compact display. Again, axes are shared wherever a label appears between plots.
Unless explicitly specified, the value of `n2dcol` is determined by the
aregument `scaling` which can either be a numerical value specifying the ratio
of the height to the width of the `zenplot` layout or be a string describing a
page whose ratio of height to width will be used. The possible strings are
``letter'' (the default), ``square'', ``A4'', ``golden'' (for the golden ratio),
or ``legal''.
### Visual search
The display arrangement of a scatterplot matrix facilitates the lookup of the
scatterplot for any particular pair of variates by simply identifying the
corresponding row and columns.
The scatterplot matrix also simplifies the visual comparison of the one variate
to each of several others by scanning along any single row (or column). Note
however that this single row scan does come at the price of doubling the number
of scatterplots in the display.
These two visual search facilities are diminished by the layout of a `zenplot`.
Although the same information is available in a `zenplot` the layout does not
lend itself to easy lookup from variates to plots. If the `zenplot` layout is
used in an interactive graphical system, other means of interaction could be
implemented to have, for example, all plots containing a particular variate (or
pair of variates) distinguish themselves visually by having their background
colour change temporarily.
On the other hand, the reverse lookup from plot to variates is simpler in a
`zenplot` than in a scatterplot matrix, particularly for large numbers of
variates.
Both layouts allow a visual search for patterns in the point configurations.
Having many plots be presented at once enables a quick visual search over a
large space for the existence of interesting point configurations
(e.g. correlations, outliers, grouping in data, lines, etc.).
When the number of plots is very large, an efficient compact layout can
dramatically increase the size of the visual search space. This is where
`zenplot`'s zigzag layout outperforms the scatterplot matrix.
This could be illustrated this on the following example.
### Example: German election data
In the `zenplots` package the data set `de_elect` contains the district results
of two German federal elections (2002 and 2005) as well as a number of
socio-economic variates as well.
```{r}
## Access the German election data from zenplots package
data(de_elect)
```
There are `r nrow(de_elect)` districts and `r ncol(de_elect)` variates yielding
a possible `choose(68,2) =` `r choose(68,2)` different scatterplots.
This many scatterplots will overwhelm a `pairs` plot. In its most compact form,
the pairs plot for the first 34 variates already occupies a fair bit of space:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## pairs(de_elect[,1:34], oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n")
```
(N.B. We do not execute any of these large plots simply to keep the storage
needs of this vignette to a minimum. We do encourage the reader to execute the
code however on their own.)
If you execute the above code you will see interesting point configurations
including: some very strong positive correlations, some positive and negative
correlations, non-linear relations, the existence of some outlying points,
clustering, striation, etc.
Because this scatterplot matrix is for only half of the variates it shows
`choose(34,2) =` `r choose(ncol(de_elect)/2,2)` different scatterplots, each one
twice. For a display of `r 2* choose(ncol(de_elect)/2,2)` plots, only about one
quarter of all `r choose(ncol(de_elect),2)` pairwise variate scatterplots
available in the data set appear in this display.
A second scatterplot matrix on the remaining 34 variates would also show only a
quarter of the plots. The remaining half, $34 \times 34 = 1156$ plots, are
missing from both plots.
In contrast, the `zenplot` shows all `r choose(ncol(de_elect),2)` plots at once.
In fact, because an Eulerian sequence requires a graph to be even (i.e. each
node has an even number of edges), whenever the number of variates, $p$, is even
`zenpath(...)` will repeat exactly $p/2$ pairs somewhere in the sequence it
returns.
To produce the `zenplot` of all pairs of variates on the German election data we
call `zenplot(de_elect[,zenpath(68)], pch=".")`. (Again, we don't produce it
here so as to minimize the storage footprint of this vignette.)
```{r message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## Try invoking the plot with the following
## zenplot(de_elect[,zenpath(68)], pch=".", n2dcol="square",col=adjustcolor("black",0.5))
```
In approximately the same visual space as the scatterplot matrix (showing only
`r choose(ncol(de_elect)/2,2)` unique plots), the `zenplot` has efficiently and
compactly laid out all `r choose(ncol(de_elect),2)` different plots plus `r
ncol(de_elect)` duplicate plots. This efficient layout means that `zenplot` can
facilitate visual search for interesting point configurations over much larger
collections of variate pairs -- in the case of the German election data, this
all possible pairs of variates are presented simultaneously.
In contrast, all pairs loses most of the detail
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=7, fig.height=7}
## pairs(de_elect, oma=rep(0,4), gap=0, pch=".", xaxt="n", yaxt="n",col=adjustcolor("black",0.5))
```
# Groups of pairwise plots
Zenplots also accomodate a list of data sets whose pairwise contents are to be
displayed. The need for this can arise quite naturally in many applications.
The German election data, for instance, contains socio-economic data whose
variates naturally group together. For example, we might gather variates
related to education into one group and those related to employment into
another.
```{r, message=FALSE, warning=FALSE}
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Employment <- c("Employed", "FFF", "Industry",
"CTT", "OS" )
```
We could plot all pairs for these two groups in a single `zenplot`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=6}
EducationData <- de_elect[, Education]
EmploymentData <- de_elect[, Employment]
## Plot all pairs within each group
zenplot(list(Educ= EducationData[, zenpath(ncol(EducationData))],
Empl= EmploymentData[, zenpath(ncol(EmploymentData))]))
```
All pairs of education variates are plotted first in zigzag order followed by a
blank plot then continuing in the same zigzag pattern by plots all pairs of
employment variates.
## All pairs by group
In addition to the `Education` and `Employment` groups above, a number of
different groupings of variates having a shared context. For example, these
might include the following:
```{r}
## Grouping variates in the German election data
Regions <- c("District", "State", "Density")
PopDist <- c("Men", "Citizens", "Pop.18.25", "Pop.25.35",
"Pop.35.60", "Pop.g.60")
PopChange <- c("Births", "Deaths", "Move.in", "Move.out", "Increase")
Agriculture <- c("Farms", "Agriculture")
Mining <- c("Mining", "Mining.employees")
Apt <- c("Apt.new", "Apt")
Motorized <- c("Motorized")
Education <- c("School.finishers",
"School.wo.2nd", "School.2nd",
"School.Real", "School.UED")
Unemployment <- c("Unemployment.03", "Unemployment.04")
Employment <- c("Employed", "FFF", "Industry", "CTT", "OS" )
Voting.05 <- c("Voters.05", "Votes.05", "Invalid.05", "Valid.05")
Voting.02 <- c("Voters.02", "Votes.02", "Invalid.02", "Valid.02")
Voting <- c(Voting.02, Voting.05)
VotesByParty.02 <- c("Votes.SPD.02", "Votes.CDU.CSU.02", "Votes.Gruene.02",
"Votes.FDP.02", "Votes.Linke.02")
VotesByParty.05 <- c("Votes.SPD.05", "Votes.CDU.CSU.05", "Votes.Gruene.05",
"Votes.FDP.05", "Votes.Linke.05")
VotesByParty <- c(VotesByParty.02, VotesByParty.05)
PercentByParty.02 <- c("SPD.02", "CDU.CSU.02", "Gruene.02",
"FDP.02", "Linke.02", "Others.02")
PercentByParty.05 <- c("SPD.05", "CDU.CSU.05", "Gruene.05",
"FDP.05", "Linke.05", "Others.05")
PercentByParty <- c(PercentByParty.02, PercentByParty.05)
```
The groups can now be used to explore internal group relations for many
different groups in the same plot. Here the following helper function comes in handy.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=11, fig.height=14}
groups <- list(Regions=Regions, Pop=PopDist,
Change = PopChange, Agric=Agriculture,
Mining=Mining, Apt=Apt, Cars=Motorized,
Educ=Education, Unemployed=Unemployment, Employed=Employment#,
# Vote02=Voting.02, Vote05=Voting.05,
# Party02=VotesByParty.02, Party05=VotesByParty.05,
# Perc02=PercentByParty.02, Perc05=PercentByParty.05
)
group_paths <- lapply(groups, FUN= function(g) g[zenpath(length(g), method = "front.loaded")] )
x <- groupData(de_elect, indices=group_paths)
zenplot(x, pch = ".", cex=0.7, col = "grey10")
```
All pairs within each group are presented following the zigzag pattern; each
group is separated by an empty plot. The `zenplot` provides a quick overview of
the pairwise relationships between variates within all groups.
The plot can be improved some by using shorter names for the variates. With a little work we can replace these within each group of `x`.
```{r message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=10}
#
## Grouping variates in the German election data
RegionsShort <- c("ED", "State", "density")
PopDistShort <- c("men", "citizen", "18-25", "25-35", "35-60", "> 60")
PopChangeShort <- c("births", "deaths", "in", "out", "up")
AgricultureShort <- c("farms", "hectares")
MiningShort <- c("firms", "employees")
AptShort <- c("new", "all")
TransportationShort <- c("cars")
EducationShort <- c("finishers", "no.2nd", "2nd", "Real", "UED")
UnemploymentShort<- c("03", "04")
EmploymentShort <- c("employed", "FFF", "Industry", "CTT", "OS" )
Voting.05Short <- c("eligible", "votes", "invalid", "valid")
Voting.02Short <- c("eligible", "votes", "invalid", "valid")
VotesByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
VotesByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke")
PercentByParty.02Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
PercentByParty.05Short <- c("SPD", "CDU.CSU", "Gruene", "FDP", "Linke", "rest")
shortNames <- list(RegionsShort, PopDistShort, PopChangeShort, AgricultureShort,
MiningShort, AptShort, TransportationShort, EducationShort,
UnemploymentShort, EmploymentShort, Voting.05Short, Voting.02Short,
VotesByParty.02Short, VotesByParty.05Short, PercentByParty.02Short,
PercentByParty.05Short)
# Now replace the names in x by these.
nGroups <- length(x)
for (i in 1:nGroups) {
longNames <- colnames(x[[i]])
newNames <- shortNames[[i]]
oldNames <- groups[[i]]
#print(longNames)
#print(newNames)
for (j in 1:length(longNames)) {
for (k in 1:length(newNames)) {
if (grepl(oldNames[k], longNames[j])) {
longNames[longNames == longNames[j]] <- newNames[k]
}
}
}
colnames(x[[i]]) <- longNames
}
zenplot(x, pch = ".", cex=0.75)
```
## Crossing pairs between groups
It can also be of interest to compare variates between groups. For example,
to compare the various levels of education with the employment categories.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=10, fig.height=16}
crossedGroups <- c(Employment, Education)
crossedPaths <- zenpath(c(length(Employment), length(Education)), method="eulerian.cross")
zenplot(de_elect[,crossedGroups][crossedPaths])
```
# Other plots
A `zenplot` can be thought of as taking a data set whose variates are to be
plotted in the order given. A sequence of one dimensional plots, as determined
by the argument `plot1d`, are constructed in the order of the variates. Between
each pair of these `1d` plots, a two dimensional plot is constructed from the
variates of the `1d` plots. One variate provides the vertical `y` values and
the other the horizontal `x` values. If the orientation of the preceding
one-dimensional plot is horizontal, then that variate gives the `x` values; if
it's vertical then the vertical `y` coordinates.
## Built in `1d` and `2d` plots
The actual displays depend on the arguments `plot1d` and `plot2d`. There are
numerous built-in choices provided.
For `plot1d` any of the following strings may be selected to produce a one-dimensional plot:
` "label" `, ` "rug" `, ` "points" `, ` "jitter" `, ` "density" `, ` "boxplot"
`, ` "hist" `, ` "arrow" `, ` "rect" `, ` "lines" `. The first in the list is
the default.
For `plot2d` any of the following strings can be given:
` "points" `, ` "density" `, ` "axes" `, ` "label" `, ` "arrow" `, ` "rect" `.
Again, the first of these is the default value.
## Arbitrary layout using `turns`
For example, we could produce a `boxplot` for the measured variates of the
earthquake data as follows:
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=5, fig.height=2}
earthquakes <- attenu[, c(1,2,4,5)] # ignore the station id
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=5, width2d=1,
turns=c("r","r","r","r","r","r","r"))
```
There are a few things to note here. First that every variate in the data set
has a boxplot of its values presented and that the extent of boxplot display is
that variate's range. Second, the argument specification `plot2d=NULL` causes
a null plot to be produced for each of the variate pairs. Third, the arguments
`width1d` and `width2d` determine the relative widths of the two displays.
Finally, the argument `turns` determines the layout of the plots by specifying
where the next display (`1d` or `2d`) is to appear in relation to the current
one. Here every display appears to the right of the existing display.
An alternative layout of the same boxplots can be had by adjusting the `turns`.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d="boxplot", plot2d=NULL,
width1d=1, width2d=1, # now widths must be the same
turns=c("r","d","d","l","l","u","u"))
```
To better see how the turns work, arrows could be used instead to show
the directions of the turns.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d= "arrow", plot2d="arrow",
width1d=1, width2d=2,
turns=c("r","d","d","l","l","u","u"))
```
Adding a rectangle to outline the drawing space will make the layout a little clearer and illustrate the arguments that are passed on to the pne and two dimensional plot functions.
```{r, message=FALSE, warning=FALSE, fig.align="center", fig.width=4, fig.height=4}
zenplot(earthquakes,
plot1d = function(zargs, ...) {
rect_1d_graphics(zargs, ...)
arrow_1d_graphics(zargs, col="firebrick", lwd=3, add=TRUE, ...)
},
plot2d = function(zargs, ...) {
rect_2d_graphics(zargs, ...)
arrow_2d_graphics(zargs, col="steelblue", lwd=3, lty=2, add=TRUE, ...)
},
width1d = 1, width2d = 2,
turns=c("r","d","d","l","l","u","u"))
```
The red arrows are the turns for the `1d` plots, the blue dashed arrows
for the `2d` plots. The turns are interlaced and begin at the topmost red arrow
for the `1d` plot. It points right, matching the first turn `"r"` in the list
of `turns`. The remaining arrows follow each other in clockwise order. As can
be seen, there is an arrow for each plot: red for the `1d` plots, black for the
`2d` plots.
## Arbitrary plots
The above example also introduces some other important features of `zenplot`.
The value `"arrow"` of `plot2d` argument caused an arrow to be drawn wherever a
`2d` plot was to appear in the direction of the turn associated with that plot.
As the value of `plot1d` here suggests, the argument could also have been a
function.
In fact, when given a string value for `plot2d`, `zenplot` calls a function
whose name is constructed with this string. In the case of `plot2d = "arrow"`,
`zenplot` calls the function `arrow_2d_graphics` to produce a `2d` plot whenever
one is required. The naming convention constructs the function name from the
string supplied, here "arrow", the dimensionality of the plot (here `2d`) and
the `R` graphics package that is being used (here the base `graphics` package).
The function of that name is called on arguments appropriate to draw the plot.
The same construction is also used when a string is given as the value of the
`plot1d` argument. For example `plot1d = "arrow"` causes the function named
`arrow_1d_graphics` to be called to draw the `1d` plots.
Should, for example, the user wish to extend the base functionality of `zenplot`
to include say `"myplot"`, they need only write functions `myplot_1d_graphics`
and/or `myplot_2d_graphics` to allow the value `"myplot"` to be used for
`plot1d` and/or `plot2d` in the base `graphics` package in `R`. Note that two
other `R` plotting packages besides the base `graphics` are supported by
`zenplot`, namely either the highly customizable `grid` package or the highly
interactive `loon` package. The default package is `graphics` but either of the
other two may be specified via the `pkg` argument to `zenplot` as in `pkg =
"grid"` or `pkg = "loon"`.
When `zenplot` is called with `plot1d="arrow"`, say, then one of the functions
`arrow_1d_graphics`, `arrow_1d_grid`, or `arrow_1d_loon` will be called upon
depending on the value of the argument `pkg`. This means that a true extension
of `zenplot` to include, say, `plot1d = "myplot"` would require writing three
functions, namely `myplot_1d_graphics`, `myplot_1d_grid`, and `myplot_1d_loon`,
to complete the functionality.
More often, as shown in the boxplot example, it will be a one-off functionality
that might be required for either `plot2d` or `plot1d`.
In this case, any function passed as the argument value will be used by
`zenplot` to construct the corresponding plots. In the boxplot example, the
default functions `boxplot_1d_graphics` and `arrow_1d_graphics` were both called
so that one could be plotted on top of the other in each `1d` plot of the
`zenplot`.
### Example: mixing plots to assess distributions
`zenplot` can be used to layout graphics produced by any of the three `pkg`
(i.e. `graphics`, `grid`, or `loon`) provided all graphics used are from the
**same** package.
For example, suppose we were interested in the marginal distributions of the
earthquake data. We might craft the following plot to investigate all marginal
distributions and to compare each marginal to every other (i.e. all pairs).
```{r, message=FALSE, warning=FALSE, results="hide", fig.align="center", fig.width=6, fig.height=3}
library(qqtest)
zenplot(earthquakes[,zenpath(ncol(earthquakes))],
width1d = 1, width2d = 2, n2dcol=5,
plot1d = function(zargs, ...) {
r <- extract_1d(zargs) # extract arguments for 1d
col <- adjustcolor(if (r$horizontal) "firebrick" else "steelblue",
alpha.f = 0.7)
hist_1d_graphics(zargs, col=col, ...)
},
plot2d=function(zargs, ...) {
r <- extract_2d(zargs) # extract arguments for 2d
x <- as.matrix(r$x)
xlim <- r$xlim
y <- as.matrix(r$y)
ylim <- r$ylim
qqtest(y, dataTest=x,
xlim=xlim, ylim=ylim,
cex=0.3, col="black", pch=19,
legend=FALSE, main="", axes=FALSE, ...)
})
```
Here we are using the function `qqtest` from the package of that name and whose
display capability is built using only the base `graphics` package. For `2d`
data `qqtest` compares the two empirical distributions by drawing an empirical
quantile-quantile plot which should be near a straight line if the marginal
distributions are of the same shape. The empirical quantile-quantile plot is
supplemented by simulated values of empirical quantiles from the empirical
distribution of the horizontal variate. The results of 1,000 draws from this
distribution are shown in shades of grey on the qqplot. The `1d` plots are
shown as histograms coloured `"grey"` when that histogram was used to generate
the simulated values and in `"steelblue"` when the histogram was not.
As can be seen from the qqplots, since numerous points are outside the gray
envelopes of each plot, no two marginal distributions would appear to be alike.
## Arguments to `plot1d` functions
Every `plot1d` function must take arbitrarily many arguments, accepting at least
the following set:
- `x`, a vector of values for a single variate
- `horizontal`, which is `TRUE` if the `1d` plot is to be horizontal,
- `plotAsp`, the aspect ratio of the plot (i.e. the smaller/larger side ration in [0,1])
- `turn`, the single character turn out from the current plot
- `plotID`, a list containing information on the identification of the `plot`.
If the `plot1d` function is from the package `grid`, then it should also expect
to receive a `vp` or viewport argument; if it is from the package `loon`, it
might also receive a `parent` argument. These arguments should be familiar to
users of either package.
For a `plot1d` function, the `plotID` consists of
- `group`, the number of the group in which this `1d` plot is placed,
- `number.within.group`, the within group index of this variate,
- `index` , the index of the variate among all variates in the data set(s)
- `label`, the variate label, and
- `plotNo`, the number of the `1d` plot being displayed (i.e its position in
order among only those which are `1d`).
All other functions in the ellipsis, `...`, are passed on to the drawing functions.
## Arguments to `plot2d` functions
Every `plot2d` function must take arbitrarily many arguments, accepting at least
the following set:
- `x`, a vector of values for the horizontal variate
- `y`, a vector of values for the vertical variate
- `turn`, the single character turn out from the current plot
- `plotID`, a list containing information on the identification of the `plot`.
If the `plot2d` function is from the package `grid`, then it should also expect
to receive a `vp` or viewport argument; if it is from the package `loon`, it
might also receive a `parent` argument. These arguments should be familiar to
users of either package.
For a `plot2d` function, the `plotID` consists of
- `group`, the number of the group in which this `2d` plot is placed,
- `number.within.group`, the within group index for these variates (same index),
- `index` , the indices of the variates among all variates in the data set(s)
- `label`, the labels of the variates, and
- `plotNo`, the number of the `2d` the plot being displayed (i.e its position
in order among only those which are `2d`).
All other functions in the ellipsis, `...`, are passed on to the drawing
functions.
| /scratch/gouwar.j/cran-all/cranData/zenplots/vignettes/intro.Rmd |
---
title: 'Zigzag expanded navigation plots in R: The R package zenplots'
author: M. Hofert and R. W. Oldford
date: '`r Sys.Date()`'
output:
rmarkdown::html_vignette: # lighter version than 'rmarkdown::html_document'; see https://bookdown.org/yihui/rmarkdown/r-package-vignette.html; there is also knitr:::html_vignette but it just calls rmarkdown::html_document with a custom .css
css: style.css # see 3.8 in https://bookdown.org/yihui/rmarkdown/r-package-vignette.html
vignette: >
%\VignetteIndexEntry{Zigzag expanded navigation plots in R: The R package zenplots}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
This vignette accompanies the paper "Zigzag expanded navigation plots in R: The R package zenplots".
Note that sections are numbered accordingly (or omitted). Furthermore, it is
recommended to read the paper to follow this vignette.
```{r setup, message = FALSE}
# attaching required packages
library(PairViz)
library(MASS)
library(zenplots)
```
## 2 Zenplots
As example data, we use the `olive` data set:
```{r, message = FALSE}
data(olive, package = "zenplots")
```
Reproducing the plots of Figure 1:
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(olive)
```
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(olive, plot1d = "layout", plot2d = "layout")
```
Considering the `str()`ucture of `zenplot()` (here formatted for nicer output):
```{r, eval = FALSE}
str(zenplot)
```
```{r, eval = FALSE}
function (x, turns = NULL, first1d = TRUE, last1d = TRUE,
n2dcols = c("letter", "square", "A4", "golden", "legal"),
n2dplots = NULL,
plot1d = c("label", "points", "jitter", "density", "boxplot",
"hist", "rug", "arrow", "rect", "lines", "layout"),
plot2d = c("points", "density", "axes", "label", "arrow",
"rect", "layout"),
zargs = c(x = TRUE, turns = TRUE, orientations = TRUE,
vars = TRUE, num = TRUE, lim = TRUE, labs = TRUE,
width1d = TRUE, width2d = TRUE,
ispace = match.arg(pkg) != "graphics"),
lim = c("individual", "groupwise", "global"),
labs = list(group = "G", var = "V", sep = ", ", group2d = FALSE),
pkg = c("graphics", "grid", "loon"),
method = c("tidy", "double.zigzag", "single.zigzag"),
width1d = if (is.null(plot1d)) 0.5 else 1,
width2d = 10,
ospace = if (pkg == "loon") 0 else 0.02,
ispace = if (pkg == "graphics") 0 else 0.037, draw = TRUE, ...)
```
### 2.1 Layout
To investigate the layout options of zenplots a bit more, we need a larger data set. To this end we
simply double the olive data here (obviously only for illustration purposes):
```{r}
olive2 <- cbind(olive, olive) # just for this illustration
```
Reproducing the plots of Figure 2:
```{r, fig.align = "center", fig.width = 8, fig.height = 13.3}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "single.zigzag")
```
```{r, fig.align = "center", fig.width = 8, fig.height = 8}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "double.zigzag")
```
```{r, fig.align = "center", fig.width = 8, fig.height = 6.6}
zenplot(olive2, n2dcols = 6, plot1d = "layout", plot2d = "layout",
method = "tidy")
```
Note that there is also `method = "rectangular"` (leaving the zigzagging zenplot paradigm but
being useful for laying out 2d plots which are not necessarily connected through a variable; note
that in this case, we omit the 1d plots as the default (labels) is rather confusing in this
example):
```{r, fig.align = "center", fig.width = 8, fig.height = 5.4}
zenplot(olive2, n2dcols = 6, plot1d = "arrow", plot2d = "layout",
method = "rectangular")
```
Reproducing the plots of Figure 3:
```{r, fig.align = "center", fig.width = 6, fig.height = 10}
zenplot(olive, plot1d = "layout", plot2d = "layout", method = "double.zigzag",
last1d = FALSE, ispace = 0.1)
```
```{r, fig.align = "center", fig.width = 6, fig.height = 7}
zenplot(olive, plot1d = "layout", plot2d = "layout", n2dcol = 4, n2dplots = 8,
width1d = 2, width2d = 4)
```
## 3 Zenpaths
A very basic path (standing for the sequence of pairs (1,2), (2,3), (3,4), (4,5)):
```{r}
(path <- 1:5)
```
A zenpath through all pairs of variables (Eulerian):
```{r}
(path <- zenpath(5))
```
If `dataMat` is a five-column matrix, the zenplot of all pairs would then be constructed as follows:
```{r, eval = FALSE}
zenplot(x = dataMat[,path])
```
The `str()`ucture of `zenpath()` (again formatted for nicer output):
```{r, eval = FALSE}
str(zenpath)
```
```{r, eval = FALSE}
function (x, pairs = NULL,
method = c("front.loaded", "back.loaded", "balanced",
"eulerian.cross", "greedy.weighted", "strictly.weighted"),
decreasing = TRUE)
```
Here are some methods for five variables:
```{r}
zenpath(5, method = "front.loaded")
zenpath(5, method = "back.loaded")
zenpath(5, method = "balanced")
```
The following method considers two groups: One of size three, the other of size five.
The sequence of pairs is constructed such that the first variable comes from the first group,
the second from the second.
```{r}
zenpath(c(3,5), method = "eulerian.cross")
```
Reproducing Figure 4:
```{r, fig.align = "center", fig.width = 6, fig.height = 9}
oliveAcids <- olive[, !names(olive) %in% c("Area", "Region")] # acids only
zpath <- zenpath(ncol(oliveAcids)) # all pairs
zenplot(oliveAcids[, zpath], plot1d = "hist", plot2d = "density")
```
## 4 Build your own zenplots
### 4.3 Custom layout and plots -- a spiral of ggplots example
Figure 5 can be reproduced as follows (note that we do not show the plot
here due to a CRAN issue when running this vignette):
```{r, fig.align = "center", fig.width = 8, fig.height = 7.2, eval = FALSE}
path <- c(1,2,3,1,4,2,5,1,6,2,7,1,8,2,3,4,5,3,6,4,7,3,8,4,5,6,7,5,8,6,7,8)
turns <- c("l",
"d","d","r","r","d","d","r","r","u","u","r","r","u","u","r","r",
"u","u","l","l","u","u","l","l","u","u","l","l","d","d","l","l",
"u","u","l","l","d","d","l","l","d","d","l","l","d","d","r","r",
"d","d","r","r","d","d","r","r","d","d","r","r","d","d")
library(ggplot2) # for ggplot2-based 2d plots
stopifnot(packageVersion("ggplot2") >= "2.2.1") # need 2.2.1 or higher
ggplot2d <- function(zargs) {
r <- extract_2d(zargs)
num2d <- zargs$num/2
df <- data.frame(x = unlist(r$x), y = unlist(r$y))
p <- ggplot() +
geom_point(data = df, aes(x = x, y = y), cex = 0.1) +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank())
if(num2d == 1) p <- p +
theme(panel.background = element_rect(fill = 'royalblue3'))
if(num2d == (length(zargs$turns)-1)/2) p <- p +
theme(panel.background = element_rect(fill = 'maroon3'))
ggplot_gtable(ggplot_build(p))
}
zenplot(as.matrix(oliveAcids)[,path], turns = turns, pkg = "grid",
plot2d = function(zargs) ggplot2d(zargs))
```
### 4.4 Data groups
Split the olive data set into three groups (according to their variable `Area`):
```{r}
oliveAcids.by.area <- split(oliveAcids, f = olive$Area)
# Replace the "." by " " in third group's name
names(oliveAcids.by.area)[3] <- gsub("\\.", " ", names(oliveAcids.by.area)[3])
names(oliveAcids.by.area)
```
Reproducing the plots of Figure 6 (note that `lim = "groupwise"` does not
make much sense here as a plot):
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.by.area, labs = list(group = NULL))
```
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.by.area, lim = "groupwise", labs = list(sep = " - "),
plot1d = function(zargs) label_1d_graphics(zargs, cex = 0.8),
plot2d = function(zargs)
points_2d_graphics(zargs, group... = list(sep = "\n - \n")))
```
### 4.5 Custom zenpaths
Find the "convexity" scagnostic for each pair of olive acids.
```{r, message = FALSE}
library(scagnostics)
Y <- scagnostics(oliveAcids) # compute scagnostics (scatter-plot diagonstics)
X <- Y["Convex",] # pick out component 'convex'
d <- ncol(oliveAcids)
M <- matrix(NA, nrow = d, ncol = d) # matrix with all 'convex' scagnostics
M[upper.tri(M)] <- X # (i,j)th entry = scagnostic of column pair (i,j) of oliveAcids
M[lower.tri(M)] <- t(M)[lower.tri(M)] # symmetrize
round(M, 5)
```
Show the six pairs with largest "convexity" scagnostic:
```{r}
zpath <- zenpath(M, method = "strictly.weighted") # list of ordered pairs
head(M[do.call(rbind, zpath)]) # show the largest six 'convexity' measures
```
Extract the corresponding pairs:
```{r}
(ezpath <- extract_pairs(zpath, n = c(6, 0))) # extract the first six pairs
```
Reproducing Figure 7 (visualizing the pairs):
```{r, message = FALSE, fig.align = "center", fig.width = 6, fig.height = 6}
library(graph)
library(Rgraphviz)
plot(graph_pairs(ezpath)) # depict the six most convex pairs (edge = pair)
```
Connect them:
```{r}
(cezpath <- connect_pairs(ezpath)) # keep the same order but connect the pairs
```
Build the corresponding list of matrices:
```{r}
oliveAcids.grouped <- groupData(oliveAcids, indices = cezpath) # group data for (zen)plotting
```
Reproducing Figure 8 (zenplot of the six pairs of acids with largest "convexity" scagnostic):
```{r, fig.align = "center", fig.width = 6, fig.height = 8}
zenplot(oliveAcids.grouped)
```
## 5 Advanced features
### 5.1 The structure of a zenplot
Here is the structure of a return object of `zenplot()`:
```{r}
res <- zenplot(olive, plot1d = "layout", plot2d = "layout", draw = FALSE)
str(res)
```
Let's have a look at the components. The occupancy matrix encodes the occupied
cells in the rectangular layout:
```{r}
res[["path"]][["occupancy"]]
```
The two-column matrix `positions` contains in the *i*th row the row and column
index (in the occupancy matrix) of the *i*th plot:
```{r}
head(res[["path"]][["positions"]])
```
### 5.2 Tools for writing 1d and 2d plot functions
Example structure of 2d plot based on `graphics`:
```{r}
points_2d_graphics
```
For setting up the plot region of plots based on `graphics`:
```{r}
plot_region
```
Determining the indices of the two variables to be plotted in the current 1d or 2d plot
(the same for 1d plots):
```{r}
plot_indices
```
Basic check that the return value of `zenplot()` is actually the return value of the
underlying `unfold()` (note that, the output of `unfold` and `res` is not identical since `res` has specific class attributes):
```{r}
n2dcols <- ncol(olive) - 1 # number of faces of the hypercube
uf <- unfold(nfaces = n2dcols)
identical(res, uf) #return FALSE
for(name in names(uf)) {
stopifnot(identical(res[[name]], uf[[name]]))
}
```
| /scratch/gouwar.j/cran-all/cranData/zenplots/vignettes/selected_features.Rmd |
#' @title Calculate Confidence Intervals for the Difference of Zero Order and
#' (Semi) Partial Correlation
#'
#' @description The \code{pzconf} function calculates confidence intervals for a
#' zero order correlation minus a (semi) partial correlation (\eqn{\rho.xy -
#' \rho.xy.z}). It is intended to be used after the \code{\link{pzcor}}
#' function.
#'
#' @param pzcor_obj pzcor object (output from pzcor function).
#'
#' @param level numerical. Confidence level used to calculate the confidence
#' interval. This may be a vector so multiple intervals can be determined.
#'
#' @details The \code{pzconf} function calculates confidence intervals based on
#' the bootstrap distribution determined from the \code{\link{pzcor}}
#' function. See \code{?pzcor} for details.
#'
#' @return The confidence interval(s) is(are) displayed in a dataframe with four
#' columns: Level, Lower, Upper, and Warnings. Level refers to the confidence
#' level of the interval. Lower and Upper are the respective lower and upper
#' bounds of the interval. Warnings may say "Max Level Passed" to show that
#' the specified confidence level exceeds the largest confidence interval
#' that can be determined from the test. The largest confidence interval is
#' shown in the last row (named "Max").
#'
#' @seealso \code{\link{pzcor}}
#'
#' @examples
#' require(graphics)
#' require(MASS)
#' # data
#' set.seed(1111)
#' mu <- rep(0,4)
#' Sigma <- matrix(.2, nrow=4, ncol=4) + diag(4)*.8
#' data <- mvrnorm(n=100, mu=mu, Sigma=Sigma)
#'
#' # p.(1,2) = p.(1,2)|(3,4) test
#' test <- pzcor(data[,1], data[,2], data[,c(3,4)], k = 1000)
#' hist(test$distribution)
#' pzconf(test, c(0.9, 0.95, 0.99))
#'
#' @export
pzconf = function(pzcor_obj, level = 0.9){
# As per equation 14.10 on page 185 of "Introduction to the Bootstrap",
# Efron and Tibshirani
if(class(pzcor_obj) != 'pzcor'){
first_arg = match.call()[2]
stop('Must be pzcor object: ', first_arg)
}
if(!is.numeric(level) | !all(0 < level & level < 1)){
stop('level must be numeric between 0 and 1')
}
z_0 <- pzcor_obj$bias
acceleration <- pzcor_obj$acceleration
distribution <- sort(pzcor_obj$distribution)
k_eff <- pzcor_obj$k_eff
test <- pzcor_obj$test
max_level <- get_max_level(k_eff, acceleration, z_0, test)
if(test == 'eq'){
z_alpha <- stats::qnorm((1 - level)/2)
result <- data.frame(Level = level, Lower = z_alpha, Upper = -z_alpha)
max_result <- data.frame(Level = max_level,
Lower = distribution[1],
Upper = distribution[k_eff])
} else {
z_alpha <- stats::qnorm((1 - level))
if(test == 'gt'){
result <- data.frame(Level = level, Lower = z_alpha)
max_result <- data.frame(Level = max_level,
Lower = distribution[1])
} else if(test == 'lt'){
result <- data.frame(Level = level, Upper = -z_alpha)
max_result <- data.frame(Level = max_level,
Upper = distribution[k_eff])
}
}
get_bound <- function(z_alpha){
# As per equation 14.10 on page 185 of "Introduction to the Bootstrap",
# Efron and Tibshirani
BCa_z <- z_0 + (z_0 + z_alpha)/(1 - acceleration*(z_0 + z_alpha))
cum_prop <- stats::pnorm(BCa_z)
bound_ind <- cum_prop * k_eff
bound_ind[which(bound_ind < 1)] <- 1
lower_ind <- which(z_alpha < 0)
upper_ind <- which(z_alpha >= 0)
bound_ind[lower_ind] <- floor(bound_ind[lower_ind])
bound_ind[upper_ind] <- ceiling(bound_ind[upper_ind])
bound <- distribution[bound_ind]
return(bound)
}
result[,-1] <- lapply(result[,-1, drop = FALSE], get_bound)
result <- rbind(result, max_result)
row.names(result)[nrow(result)] <- 'Max'
result$Warnings <- ''
result$Warnings[which(result$Level > max_level)] <- ' Max Level Passed'
return(result)
}
get_max_level = function(k_eff, acceleration, bias, test){
# As per equation 15.34 on page 216 of "Introduction to the Bootstrap",
# Efron and Tibshirani
min <- get_unadjusted_alpha(1/k_eff, acceleration, bias)
max <- get_unadjusted_alpha(1 - 1/k_eff, acceleration, bias)
if(test == 'eq'){
result <- max - min
} else if(test == 'gt'){
result <- 1 - min
} else if(test == 'lt'){
result <- max
}
return(result)
}
get_unadjusted_alpha = function(cum_prop, acceleration, bias){
w_0 <- stats::qnorm(cum_prop)
z_0 <- bias
BCa_z <- (w_0 - z_0)/(1 + acceleration*(w_0 - z_0)) - z_0
alpha <- stats::pnorm(BCa_z)
return(alpha)
}
| /scratch/gouwar.j/cran-all/cranData/zeroEQpart/R/pzconf.R |
#' @title Test for Equal Zero Order and (Semi) Partial Correlation
#'
#'@description Compute a bootstrap test to determine whether zero order
#' correlation is equal to partial or semi-partial correlation.
#'
#'@param x a numeric vector.
#'
#'@param y a numeric vector.
#'
#'@param z a numeric vector (data.frame, matrix, etc.)
#'
#'@param semi logical. If \code{TRUE}, then the semi-partial correlation between
#' \code{x} and \code{y} given \code{z} is used. If \code{FALSE} (default),
#' then the partial correlation between \code{x} given \code{z} and \code{y}
#' given \code{z} is used.
#'
#'@param k the number of bootstrap samples taken (default is 1000).
#'
#'@param method a character string indicating which correlation
#' coefficient is to be computed. One of "pearson" (default), "kendall", or
#' "spearman" can be abbreviated.
#'
#'@param test character string denoting the null hypothesis to be tested. Can
#' be one of the three:
#' \itemize{
#' \item{\code{'eq'} tests \eqn{\rho.xy - \rho.xy.z = 0} (default)}
#' \item{\code{'gt'} tests \eqn{\rho.xy - \rho.xy.z \ge 0}}
#' \item{\code{'lt'} tests \eqn{\rho.xy - \rho.xy.z \le 0}} }
#'
#'@details Uses the bias-corrected and accelerated (BCa) bootstrap method to
#' test if the difference \eqn{\rho.xy - \rho.xy.z} is equal to, above, or
#' below zero where \eqn{\rho.xy} is the zero order correlation between
#' variables \eqn{x} and \eqn{y}, and \eqn{\rho.xy.z} is the (semi) partial
#' correlation between the respective variables after partialing out
#' variables represented by \eqn{z}.
#'
#' If the bootstrap distribution of
#' \eqn{\rho.xy - \rho.xy.z} is strictly above or below zero, then
#' the p-value provided is the most extreme value that can be determined
#' by the test. In the case of highly correlated variables, the
#' covariance matrix may be singular which will lead to \code{k_eff} being
#' less than \code{k} (as \eqn{\rho.xy - \rho.xy.z} would not be computed).
#'
#'@return \item{acceleration}{the acceleration used for the BCa method.}
#'
#' \item{alpha}{the proportion of the bootstrapped distribution below zero.}
#'
#' \item{bias}{the bias used for the BCa method.}
#'
#' \item{call}{shows the function call.}
#'
#' \item{difference}{calculated from the data. Same as \code{p.xy - p.xy.z}.}
#'
#' \item{distribution}{the estimated distribution of the difference as
#' determined through bootstrapping.}
#'
#' \item{k_eff}{the number of successful bootstrap samples. Less than or equal
#' to \code{k}.}
#'
#' \item{method}{the method of correlation used.}
#'
#' \item{p.value}{significance level of the test.}
#'
#' \item{p.xy}{Zero order correlation between \code{x} and \code{y}.}
#'
#' \item{p.xy.z}{(semi) partial correlation between \code{x} and \code{y} while
#' accounting for \code{z}.}
#'
#' \item{semi}{logical. If \code{TRUE}, \code{p.xy.z} is the semi-partial
#' correlation. Otherwise \code{p.xy.z} is the partial correlation.}
#'
#' \item{test}{shows the type of test performed.}
#'
#'@seealso \code{\link{pzconf}}
#'
#' @examples
#' require(graphics)
#' require(MASS)
#' # data
#' set.seed(1111)
#' mu <- rep(0,4)
#' Sigma <- matrix(.2, nrow=4, ncol=4) + diag(4)*.8
#' data <- mvrnorm(n=100, mu=mu, Sigma=Sigma)
#'
#' # p.(1,2) = p.(1,2)|(3,4) test
#' test <- pzcor(data[,1], data[,2], data[,c(3,4)], k = 1000, semi = FALSE,
#' test = 'eq')
#' hist(test$distribution)
#' test
#' @export
pzcor <- function(x, y, z, semi = FALSE, k = 1000, method = "pearson", test = 'eq'){
# generic function for S3 class: pzcor
if(!test %in% c('eq','gt','lt')){
stop("test must be one of 'eq', 'gt', or 'lt'")
}
if(k < 2 | k %% 1 != 0){
stop('k must be an integer of at least 2')
}
if(!semi %in% c(TRUE, FALSE)){
stop('semi must be boolean')
}
UseMethod("pzcor")
}
#' @export
pzcor.default <- function(x, y, z, semi = FALSE, k = 1000, method = "pearson",
test = 'eq'){
# Default method for pzcor
# Calls various helper functions and returns the results in a list
method <- get_cor_method(method)
dist_result <- get_dist(x,y,z,semi,k,method)
alpha <- get_alpha(dist_result$distribution)
bias <- get_bias(dist_result$distribution, dist_result$difference)
acceleration <- get_acceleration(dist_result$jack_distribution)
k_eff <- dist_result$k_eff
p.value <- get_p.value(alpha, acceleration, bias, test, k_eff)
result <- list(
acceleration = acceleration,
alpha = alpha,
bias = bias,
call = match.call(),
distribution = dist_result$distribution,
difference = dist_result$difference,
k_eff = k_eff,
method = method,
p.value = p.value,
p.xy = dist_result$p.xy,
p.xy.z = dist_result$p.xy.z,
semi = semi,
test = test
)
class(result) <- "pzcor"
return(result)
}
#' @export
print.pzcor <- function(x, ...){
# print method for pzcor objects
print(summary(x))
}
#' @export
summary.pzcor <- function(object, ...){
if(object$test == 'eq'){
hyp_op <- '='
} else if(object$test == 'gt'){
hyp_op <- '>'
} else if(object$test == 'lt'){
hyp_op <- '<'
}
hypothesis <- paste('p.xy - p.xy.z ', hyp_op, ' 0')
test_summary <- list(
'Hypothesis ' = hypothesis,
Semi_Partial = object$semi,
Correlation = object$method,
p.xy = object$p.xy,
p.xy.z = object$p.xy.z,
difference = object$difference,
p.value = object$p.value,
Bootstrap_Size = object$k_eff
)
relation <- ''
if(!is.nan(object$p.value)){
relation <- 'equal to'
if(object$alpha %in% c(0,1)){
if(object$p.value < 0.5){
relation <- 'less than'
} else {
relation <- 'greater than'
}
}
}
pval_name <- paste('p.value ', relation)
names(test_summary)[which(names(test_summary)=='p.value')] <- pval_name
distr_summary <- summary(object$distribution)
result <- list(test_summary = test_summary,
distribution_summary = distr_summary,
call = object$call)
class(result) <- 'pzcor_summary'
return(result)
}
#' @export
print.pzcor_summary <- function(x, ...){
# put test_summary in proper format
test_summary <- x$test_summary
b_size <- test_summary$Bootstrap_Size
is.num <- sapply(rbind(test_summary), is.numeric)
form_nums <- formatC(unlist(test_summary[is.num]), digits = 5, format = "f")
test_summary[is.num] <- form_nums
test_summary$Bootstrap_Size <- b_size
test_summary_formatted <- data.frame(cbind(test_summary))
colnames(test_summary_formatted) <- ''
# print summary
print(x$call)
stars <- rep('*', 8, sep='')
cat('\n', stars, 'Test Summary', stars)
print(test_summary_formatted)
stars <- rep('*', 9, sep='')
cat('\n\n', stars, 'Distribution Summary', stars, '*', '\n')
print(x$distribution_summary)
}
get_dist <- function(x, y, z, semi = FALSE, k = 1000, method = "pearson"){
# Estimates distribution function of theta = p_{xy} - p_{xy|z} (or p_{xy} -
# p_{x, y|z} if semi is TRUE) using bootstrap and jackknife (for
# acceleration). Returns a list including both distributions, p_{xy}, p_{xy|z}
# (or p_{x, y|z}), and theta.
# Used as a helper function for pzcor
x <- data.matrix(x)
y <- data.matrix(y)
z <- data.matrix(z)
if(nrow(x)!=nrow(y) | nrow(x)!=nrow(z)){
stop('x,y,z require equal number of rows')
}
zero_ord_cor <- function(ind){
p.xy <- stats::cor(x[ind], y[ind], method = method)
return(p.xy)
}
part_cor <- function(ind){
p.xy.z <- ppcor::pcor.test(x[ind], y[ind], z[ind,], method = method)
return(p.xy.z$estimate)
}
semi_part_cor <- function(ind){
p.xy.z <- ppcor::spcor.test(x[ind], y[ind], z[ind,], method = method)
return(p.xy.z$estimate)
}
n <- length(x)
boot_ind <- data.matrix(replicate(k, sample(1:n, replace = TRUE)))
jack_ind <- data.matrix(utils::combn(x = 1:n, m = n - 1))
difference_p.xy <- zero_ord_cor(1:n)
p.xy <- apply(X = boot_ind, FUN = zero_ord_cor, MARGIN = 2)
jack_p.xy <- apply(X = jack_ind, FUN = zero_ord_cor, MARGIN = 2)
if (semi == TRUE){
difference_p.xy.z <- semi_part_cor(1:n)
p.xy.z <- apply(X = boot_ind, FUN = semi_part_cor, MARGIN = 2)
jack_p.xy.z <- apply(X = jack_ind, FUN = semi_part_cor, MARGIN = 2)
} else {
difference_p.xy.z <- part_cor(1:n)
p.xy.z <- apply(X = boot_ind, FUN = part_cor, MARGIN = 2)
jack_p.xy.z <- apply(X = jack_ind, FUN = part_cor, MARGIN = 2)
}
boot_data = stats::na.omit(data.frame(p.xy, p.xy.z))
jack_data = stats::na.omit(data.frame(jack_p.xy, jack_p.xy.z))
result <- list()
result$distribution <- boot_data[,1] - boot_data[,2]
result$jack_distribution <- jack_data[,1] - jack_data[,2]
result$k_eff <- nrow(boot_data)
result$p.xy <- difference_p.xy
result$p.xy.z <- difference_p.xy.z
result$difference <- difference_p.xy - difference_p.xy.z
return(result)
}
p_less_x <- function(dist, x){
# Returns the proportion of values in dist that are less than x
n <- length(dist)
less_than_x <- length(dist[dist < x])
p_x <- less_than_x/n
return(p_x)
}
get_alpha <- function(dist){
# As per equation 15.31 on page 215 of "Introduction to the Bootstrap",
# Efron and Tibshirani
alpha = p_less_x(dist, 0)
return(alpha)
}
get_acceleration <- function(dist){
# Receives jackknife distribution and determines acceleration for p.value
# adjustment.
# As per equation 14.15 on page 186 of "Introduction to the Bootstrap",
# Efron and Tibshirani
x_dist <- mean(dist) - dist
num <- sum(x_dist^3)
denom <- 6*sum(x_dist^2)^(3/2)
if(denom == 0){
stop('Standard deviation of bootstrap distribution is zero')
}
return(num/denom)
}
get_bias <- function(distribution, difference){
# As per equation 14.14 on page 186 of "Introduction to the Bootstrap",
# Efron and Tibshirani
bias_proportion <- p_less_x(distribution, difference)
bias_z <- stats::qnorm(bias_proportion)
return(bias_z)
}
get_p.value <- function(alpha, acceleration, bias, test, k_eff){
# As per equation 15.34 on page 216 of "Introduction to the Bootstrap",
# Efron and Tibshirani
if(alpha == 0){
alpha <- 1/k_eff
} else if(alpha == 1){
alpha <- 1 - 1/k_eff
}
w_0 <- stats::qnorm(alpha)
z_0 <- bias
BCa_z <- (w_0 - z_0)/(1 + acceleration*(w_0 - z_0)) - z_0
p.value <- 2*stats::pnorm(-1*abs(BCa_z))
if(test == 'gt' & BCa_z > 0 | test == 'lt' & BCa_z < 0){
p.value <- p.value/2
} else if(test != 'eq'){
p.value <- 1 - p.value/2
}
return(p.value)
}
get_cor_method <- function(abr_method){
cors <- c('pearson', 'kendall', 'spearman')
method <- match.arg(abr_method, cors)
return(method)
}
| /scratch/gouwar.j/cran-all/cranData/zeroEQpart/R/pzcor.R |
#' @title Zero Order vs (Semi) Partial Correlation Test and CI
#'
#' @description Calculate the statistical significance of a zero order
#' correlation being equal to a partial or semi-partial correlation using
#' the bias-corrected and accelerated bootstrap method from "An Introduction
#' to the Bootstrap" Efron (1983) <0-412-04231-2>. Confidence intervals for
#' the parameter (zero order minus partial) can also be determined.
#'
#' @section pzcor: The \code{pzcor} function tests one of the following null
#' hypotheses: \itemize{
#' \item{\eqn{\rho.xy - \rho.xy.z = 0} (default)}
#' \item{\eqn{\rho.xy - \rho.xy.z \ge 0}}
#' \item{ \eqn{\rho.xy - \rho.xy.z \le 0}}
#' }
#' See \code{\link{pzcor}} for details.
#'
#' @section pzconf: The \code{pzconf} function computes confidence intervals
#' for the parameter: \eqn{\rho.xy - \rho.xy.z}. To be used with
#' \code{pzcor}. See \code{\link{pzconf}} for details.
#'
"_PACKAGE"
| /scratch/gouwar.j/cran-all/cranData/zeroEQpart/R/zeroEQpart.R |
#' A sample of the UN Comtrade Database.
#'
#' In the following example the original base (comtrade.rda) has only 229,585
#' information on positive bilateral trade flow (greater than zero). However,
#' after expanding this base to also present the bilateral trade flow equal to
#' zero, the new base will have 1,255,892 observations (both positive and zero
#' flow). Note that the final size of the base will depend on the number of
#' years, the number of exporting and importing countries and the items present
#' in the base. Since the distinct number of exporting and importing countries
#' has an important determining factor in the expansion of the base (see the
#' examples with the distinct.rda and same.rda bases).
#'
#' @description A sample of the UN Comtrade Database prepared by the United
#' Nations Department of Statistics with official international trade
#' information.
#' @format A dataframe object.
#' @source Repository UN Comtrade.
#' @keywords comtrade sample trade international.
#' @details A dataset consisting of two years, 24 exporting countries, 24
#' importing countries, 1,241 Harmonized System codes and the value of exports
#' in dollars. The data includes the following fields:
#'
#' * ano - Numeric. Year in which exports were carried out.
#' * ido - String. ISO code corresponding to the exporting country.
#' * idd - String. ISO code corresponding to the importing country.
#' * HS4 - Numeric. HS4 code corresponding to the merchandise sold.
#' * comercio - Numeric. Dollar value of exports.
#'
#' @return a dataframe object contains the five variables passed as parameters
#' to the get_zerotradeflow() function (year, exporter, importer, item, trade)
#' including the bilateral trade flow equal to zero.
#'
#' @examples
#'
#'
#' \donttest{
#'
#' zeroflow <- get_zerotradeflow(comtrade, ano, ido, idd, HS4, comercio)
#'
#' }
#'
#'
"comtrade"
#' Dataset composed of six different countries.
#'
#' @description A dummy dataset to illustrate the final size of the base after
#' expansion.
#' @format A dataframe object.
#' @details A dataset consisting of three years, three exporting countries,
#' three importing countries, three Harmonized System code and value of
#' exports (all data is fictitious). The data includes the following fields:
#'
#' * ano - Numeric. Year in which exports were carried out.
#' * ido - String. ISO code corresponding to the exporting country.
#' * idd - String. ISO code corresponding to the importign country.
#' * HS4 - Numeric. HS4 code corresponding to the merchandise sold.
#' * comercio - Numeric. Dollar value of exports.
#'
#' @return a dataframe object contains the five variables passed as parameters
#' to the get_zerotradeflow() function (year, exporter, importer, item, trade)
#' including the bilateral trade flow equal to zero.
#'
#' @examples
#'
#' # Note that the distinct.rda base has six different countries (three
#' # exporters and three importers). Thus, when expanding this base, we have 81
#' # observations as a result.
#'
#'
#' \donttest{
#'
#' distinctflow <- get_zerotradeflow(distinct, ano, ido, idd, HS4, comercio)
#'
#' }
#'
#'
"distinct"
#' Dataset composed of five different countries (BRA appears as both exporter
#' and importer).
#'
#' @description A dummy dataset to illustrate the final size of the base after
#' expansion.
#' @format A dataframe object.
#' @details A dataset cosisting of three years, three exporting countries,
#' three importing countries, three Harmonized System code and value of exports
#' (all data is fictitious). The data includes the following fields:
#'
#' * ano - Numeric. Year in which exports were carried out.
#' * ido - String. ISO code corresponding to the exporting country.
#' * idd - String. ISO code corresponding to the importing country.
#' * HS4 - Numeric. HS4 code corresponding to the merchandise sold.
#' * comercio - Numeric. Dollar value of exports.
#'
#' @return a dataframe object contains the five variables passed as parameters
#' to the get_zerotradeflow() function (year, exporter, importer, item, trade)
#' including the bilateral trade flow equal to zero.
#'
#' @examples
#'
#' # On the other hand, in the same.rda base, Brazil (BRA) appears as both an
#' # exporter and an importer and, in this case, when expanding the base, there
#' # are 72 observations as a result.
#'
#'
#' \donttest{
#'
#' sameflow <- get_zerotradeflow(same, ano, ido, idd, HS4, comercio)
#'
#' }
#'
#'
"same"
#' Expand the dataset from the passed database as parameters.
#'
#' The zerotradeflow package allows generating the bilateral trade flow equal
#' to zero of each country pair in each year present in the database passed in
#' data parameter. Since, by default, data on bilateral trade flows of countries
#' only report positive trade flows (flows greater than zero).
#'
#' @description Creates zero bilateral trade flow for a given pair of countries.
#' @return a dataframe object contains the five variables passed as parameters
#' to the get_zerotradeflow() function (year, exporter, importer, item, trade)
#' including the bilateral trade flow equal to zero.
#' @details Function to expand the database with the bilateral trade flow equal
#' to zero, passing the following parameters:
#'
#'
#' @param data a data set containing the variables that will be used to guide
#' the expansion of the base including all possible combinations of the reference
#' variables.
#' @param year refers to the column in the database that contains information for
#' the years under review.
#' @param exporter refers to the column with the ISO codes (ISO 3166 standard -
#' Codes for the representation of names of countries and their subdivisions,
#' created and maintains by International Organization for Standardization - ISO)
#' of each exporter country (Ex.: BRA, PRT, ITA, USA,...).
#' @param importer refers to the column with the ISO codes (ISO 3166 standard -
#' Codes for the representation of names of countries and their subdivisions,
#' created and maintains by International Organization for Standardization - ISO)
#' of each importer country (Ex.: BRA, PRT, ITA, USA,...).
#' @param item refers to the column in the database that contains information
#' about Harmonized System (HS) codes, or other classification. Harmonized
#' System is an acronym for Harmonized Commodity Designation and Coding System,
#' and it is a customs nomenclature, used internationally as a standardized
#' system of coding and classification of import and export products, developed
#' and maintained by the World Customs Organization (WCO).
#' @param trade refers to the column in the database that contains information
#' about the value of exports/imports
#'
#'
#' @importFrom magrittr %>%
#' @importFrom magrittr %<>%
#' @importFrom dplyr left_join
#' @importFrom tidyr replace_na
#' @importFrom rlang :=
#' @importFrom purrr lift_vd
#' @importFrom cli cli_abort
#'
#' @export
get_zerotradeflow <- function (data, year, exporter, importer, item, trade) {
df <- data %>% tidyr::expand ({{year}}, {{exporter}}, {{importer}}, {{item}})
year <- deparse (substitute (year))
exporter <- deparse (substitute (exporter))
importer <- deparse (substitute (importer))
item <- deparse (substitute (item))
df %<>% left_join (data, by = c ({{year}}, {{exporter}}, {{importer}}, {{item}}))
df %<>% dplyr::mutate ({{trade}} := replace_na ({{trade}}, 0))
df [df [, {{exporter}}] != df [, {{importer}}], ]
}
"get_zerotradeflow"
| /scratch/gouwar.j/cran-all/cranData/zerotradeflow/R/zerotradeflow.R |
.onAttach <- function(libname, pkgname) {
packageStartupMessage("This is zetadiv 1.2.1")
packageStartupMessage("Package \"zetadiv\" was built under R.4.1.3")
}
##################
##MAIN FUNCTIONS##
##################
#' Zeta diversity decline using Monte Carlo sampling
#'
#' Computes zeta diversity, the number of species shared by multiple assemblages, for a range of orders (number of assemblages or sites), using combinations of sampled sites, and fits the decline to an exponential and a power law relationship.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param xy Site coordinates. This is only used if \code{NON} = TRUE or \code{DIR} = TRUE.
#' @param orders Range of number of assemblages or sites for which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed for each number of assemblages or sites.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param sd.correct.adapt Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) if \code{sam} is higher than the number of possible combinations, or not (using the number of site combinations as the denominator) if \code{sam} is lower than the number of possible combinations. If \code{sd.correct.adapt = TRUE}, it takes precedence over \code{sd.correct}.
#' @param confint.level Percentage for the confidence intervals of the coefficients from the regressions.
#' @param sd.plot Boolean value (TRUE or FALSE) indicating if the standard deviation of each zeta diversity value must be plotted.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param NON Boolean value (TRUE or FALSE) indicating if the number of species in common should only be counted for the nearest neighbours.
#' @param FPO A vector with the coordinates of the fixed point origin from which the zeta diversity will be computed (overrides NON). In that case, \eqn{\zeta_1} is the number of species in the closest site to the FPO, \eqn{\zeta_2} is the number of species shared by the 2 closest sites, etc.
#' @param DIR Boolean value (TRUE or FALSE) indicating if zeta diversity must be computed using a directed nearest neighbour scheme in the direction away from the FPO, starting from any site.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity, and computation errors for the normalized version of zeta due to divisions by 0. Options are "\code{empty}" to let the data untreated, "\code{remove}" to remove the empty rows, 0 to set the normalized zeta to 0 when zeta is divided by 0 during normalization (sites share no species, so are completely dissimilar), and 1 to set the normalized zeta to 1 when zeta is divided by 0 during normalization (i.e. sites are perfectly similar).
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @param silent Boolean value (TRUE or FALSE) indicating if messages must be printed.
#' @details If the number of combinations of sites is lower than the value of the parameter \code{sam}, all the combinations are used and an exact solution is computed. In that case, using the number of site combinations as the denominator may be appropriate to compute the standard deviation, if all sites were sampled and the zeta values. This can be adjusted with parameters \code{sd.correct} and \code{sd.correct.adapt}.
#' @details \code{Zeta.decline.mc} is faster than \code{\link{Zeta.decline.ex}} to compute the exact value of zeta diversity when the number of species is higher than \eqn{C^N_{i}}, where \emph{N} is the total number of sites and \emph{i} is the order of zeta.
#' @details The exponential and the power law fit are performed using linear regressions on log-transformed data (only the zeta values are log-transformed for the exponential fit, and both the orders and the zeta values are log-transformed for the power law fit).
#' @details \code{Zeta.decline.mc} enables accomodating richness heterogeneity by setting \code{normalize = "Jaccard"}, \code{normalize = "Sorensen"} or \code{normalize = "Simpson"}. This cannot be performed by \cr \code{\link{Zeta.decline.ex}}.
#' @return \code{Zeta.decline.mc} returns a list containing the following components:
#' @return \item{zeta.order}{The number of assemblages or sites for which the zeta diversity was computed.}
#' @return \item{combinations}{The number of possible combinations of sites for the chosen orders.}
#' @return \item{zeta.val}{The zeta diversity values.}
#' @return \item{zeta.val.sd}{The zeta diversity standard deviation values.}
#' @return \item{zeta.ratio}{The ratio of zeta diversity values by the zeta diversity values at the lower order \eqn{\zeta_i / \zeta_{i-1}}.}
#' @return \item{zeta.exp}{Object of class "\code{lm}", containing the output of the exponential regression.}
#' @return \item{zeta.exp.confint}{The confidence intervals of the coefficients of the exponential regression.}
#' @return \item{zeta.pl}{Object of class "\code{lm}", containing the output of the power law regression.}
#' @return \item{zeta.pl.confint}{The confidence intervals of the coefficients of the power law regression.}
#' @return \item{aic}{AIC values for \code{zeta.exp} and \code{zeta.pl}.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.order.mc}}, \code{\link{Plot.zeta.decline}}
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new(width = 12, height = 4)
#' zeta.bird <- Zeta.decline.mc(data.spec.bird, xy.bird, orders = 1:5, sam = 100,
#' NON = TRUE)
#' zeta.bird
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new(width = 12, height = 4)
#' zeta.marion <- Zeta.decline.mc(data.spec.marion, orders = 1:5, sam = 100,
#' normalize = "Jaccard")
#' zeta.marion
#'
#' @export
#'
Zeta.decline.mc <- function(data.spec, xy = NULL, orders = 1:10, sam = 1000, sd.correct = TRUE, sd.correct.adapt = FALSE, confint.level = 0.95, sd.plot = TRUE, rescale = FALSE, normalize = FALSE, NON = FALSE, FPO = NULL, DIR = FALSE, empty.row = "empty", plot = TRUE, silent=TRUE){
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(max(orders)>dim(data.spec)[1]){
stop("Error: rrong value for \"orders\": the maximum value must be equal or lower than the number of sites.")
}
if(NON == TRUE && is.null(xy)){
stop("Error: if NON = TRUE, xy must be non null.")
}
if(NON == TRUE && nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if(empty.row == "remove"){
if(length(which(rowSums(data.spec)))>0){
data.spec <- data.spec[-which(rowSums(data.spec)==0),]
}
}
x <- dim(data.spec)[1]
zeta.val <- numeric()
zeta.val.sd <- numeric()
if(is.null(FPO)){
if(NON == FALSE){
for(j in orders){
if (j == 1){
zeta.val[j]<-mean(rowSums(data.spec))
if(sd.correct == TRUE & sd.correct.adapt == FALSE){
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))
}else{
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))*nrow(data.spec)
}
if(rescale == TRUE || normalize != FALSE){
zeta.val[j] <- 1
zeta.val.sd[j] <- zeta.val.sd[j]/mean(rowSums(data.spec))
}
}else{
if(choose(x, j)>sam){
if(silent==FALSE){
print(paste("Monte Carlo sampling for order",j))
}
u <- rep(NA, sam)
for(z in 1:sam){
samp <- sample(1:x, j, replace = FALSE)
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}else{
if(silent==FALSE){
print(paste("Exact solution for order",j))
}
u <- rep(NA, choose(x, j))
samp <- utils::combn(1:x, j)
for(z in 1:dim(samp)[2]){
u[z] <- sum(apply(data.spec[samp[, z], ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp[, z], ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}
if(rescale == TRUE){
z1 <- mean(rowSums(data.spec))
u <- u / z1
}
zeta.val[j]<-mean(u)
if(sd.correct.adapt == FALSE){
if(sd.correct == TRUE){
zeta.val.sd[j] <- stats::sd(u)
}else{
zeta.val.sd[j] <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}
}else{
if(x>sam){
zeta.val.sd[j] <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}else{
zeta.val.sd[j] <- stats::sd(u)
}
}
}
}
}else{
for(j in orders){
if (j == 1){
zeta.val[j]<-mean(rowSums(data.spec))
if(sd.correct == TRUE & sd.correct.adapt == FALSE){
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))
}else{
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))*nrow(data.spec)
}
if(rescale == TRUE || normalize != FALSE){
zeta.val[j] <- 1
zeta.val.sd[j] <- zeta.val.sd[j]/mean(rowSums(data.spec))
}
if(rescale == TRUE || normalize != FALSE){
zeta.val[j] <- 1
zeta.val.sd[j] <- zeta.val.sd[j]/mean(rowSums(data.spec))
}
}else{
if(x>sam){
u <- rep(NA, sam)
samps <- sample(1:x, sam, replace = FALSE)
for(z in 1:sam){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:j])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}else{
u <- rep(NA, x)
samps <- 1:x
for(z in 1:x){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:j])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}
if(rescale == TRUE & normalize == FALSE){
z1 <- mean(rowSums(data.spec))
u <- u / z1
}
zeta.val[j]<-mean(u)
if(sd.correct.adapt == FALSE){
if(sd.correct == TRUE){
zeta.val.sd[j] <- stats::sd(u)
}else{
zeta.val.sd[j] <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}
}else{
if(x>sam){
zeta.val.sd[j] <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}else{
zeta.val.sd[j] <- stats::sd(u)
}
}
}
}
}
}else{
if(DIR == FALSE){
xy.dist <- (FPO[1]-xy[,1])^2+(FPO[2]-xy[,2])^2
for(j in orders){
samp <- order(xy.dist)[1:j]
zeta.val[j] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
zeta.val[j] <- 0
}else if(empty.row == 1){
zeta.val[j] <- 1
}
}else
zeta.val[j] <- zeta.val[j] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
zeta.val[j] <- 0
}else if(empty.row == 1){
zeta.val[j] <- 1
}
}else
zeta.val[j] <- zeta.val[j] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
zeta.val[j] <- 0
}else if(empty.row == 1){
zeta.val[j] <- 1
}
}else
zeta.val[j] <- zeta.val[j] / toto
}
zeta.val.sd[j] <- 0
}
}else{
for(j in orders){
if(j==1){
zeta.val[j]<-mean(rowSums(data.spec))
if(sd.correct == TRUE & sd.correct.adapt == FALSE){
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))
}else{
zeta.val.sd[j] <- stats::sd(rowSums(data.spec))*nrow(data.spec)
}
if(rescale[j] == TRUE || normalize != FALSE){
zeta.val[j] <- 1
zeta.val.sd[j] <- zeta.val.sd/mean(rowSums(data.spec))
}
}else{
xy.FPO <- as.matrix(xy-FPO)
if(x>sam){
u <- rep(NA, sam)
samps <- sample(1:x, sam, replace = FALSE)
for(z in 1:sam){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(j-1)){
samp <- c(samp,order(xy.dist)[1:(j-1)])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",j))
}
u[z] <- NA
}
}
}else{
u <- rep(NA, x)
samps <- 1:x
for(z in 1:(x-j+1)){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(j-1)){
samp <- c(samp,order(xy.dist)[1:(j-1)])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",j))
}
u[z] <- NA
}
}
}
zeta.val[j] <- mean(u,na.rm=TRUE)
if(sd.correct.adapt == FALSE){
if(sd.correct == TRUE){
zeta.val.sd[j] <- stats::sd(u,na.rm=TRUE)
}else{
zeta.val.sd[j] <- stats::sd(u,na.rm=TRUE)*sqrt((length(which(!is.na(u)))-1)/length(which(!is.na(u))))
}
}else{
if(x>sam){
zeta.val.sd[j] <- stats::sd(u,na.rm=TRUE)*sqrt((length(which(!is.na(u)))-1)/length(which(!is.na(u))))
}else{
zeta.val.sd[j] <- stats::sd(u,na.rm=TRUE)
}
}
}
}
}
}
##create a single list for output
zeta <- list()
zeta$zeta.order <- orders
zeta$combinations <- choose(x, orders)
zeta$zeta.val <- zeta.val
zeta$zeta.val.sd <- zeta.val.sd
zeta$ratio <- zeta.val[2:length(zeta.val)]/zeta.val[1:(length(zeta.val)-1)]
##regression - exponential
zeta.val.log <- log10(zeta.val)
zeta.val.log[which(is.infinite(zeta.val.log))] <- NA
zeta.exp <- stats::lm(zeta.val.log ~ c(orders), na.action = stats::na.omit)
zeta$zeta.exp <- zeta.exp
zeta$zeta.exp.confint <- suppressMessages(stats::confint(zeta.exp,level=confint.level))
##regression - power law
zeta.pl <- stats::lm(zeta.val.log ~ log10(c(orders)), na.action = stats::na.omit)
zeta$zeta.pl <- zeta.pl
zeta$zeta.pl.confint <- suppressMessages(stats::confint(zeta.pl,level=confint.level))
zeta$aic <- stats::AIC(zeta$zeta.exp, zeta$zeta.pl)
##Plot zeta and regressions
if(plot == TRUE){
Plot.zeta.decline(zeta, sd.plot=sd.plot)
}
return(zeta)
}
#' Zeta diversity for a specific number of assemblages or sites using Monte Carlo sampling
#'
#' Computes zeta diversity, the number of species shared by multiple assemblages, for a specific order (number of assemblages or sites).
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param xy Site coordinates. This is only used if \code{NON} = TRUE or \code{DIR} = TRUE.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param sd.correct.adapt Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) if \code{sam} is higher than the number of possible combinations, or not (using the number of site combinations as the denominator) if \code{sam} is lower than the number of possible combinations. If \code{sd.correct.adapt == TRUE}, it takes precedence over \code{sd.correct}.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param NON Boolean value (TRUE or FALSE) indicating if the number of species in common should only be counted for the nearest neighbours.
#' @param FPO A vector with the coordinates of the fixed point origin from which the zeta diversity will be computed (overrides NON). In that case, \eqn{\zeta_1} is the number of species in the closest site to the FPO, \eqn{\zeta_2} is the number of species shared by the 2 closest sites, etc.
#' @param DIR Boolean value (TRUE or FALSE) indicating if zeta diversity must be computed using a directed nearest neighbour scheme in the direction away from the FPO, starting from any site.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity, and computation errors for the normalized version of zeta due to divisions by 0. Options are "\code{empty}" to let the data untreated, "\code{remove}" to remove the empty rows, 0 to set the normalized zeta to 0 when zeta is divided by 0 during normalization (sites share no species, so are completely dissimilar), and 1 to set the normalized zeta to 1 when zeta is divided by 0 during normalization (i.e. sites are perfectly similar).
#' @param silent Boolean value (TRUE or FALSE) indicating if messages must be printed.
#' @details If the number of combinations of sites is lower than the value of the parameter \code{sam}, all the combinations are used and an exact solution is computed. In that case, using the number of site combinations as the denominator may be appropriate to compute the standard deviation, if all sites were sampled and the zeta values. This can be adjusted with parameters \code{sd.correct} and \code{sd.correct.adapt}.
#' @details \code{Zeta.order.mc} is faster than \code{\link{Zeta.order.ex}} to compute the exact value of zeta diversity when the number of species is higher than \eqn{C^N_{i}}, where \emph{N} is the total number of sites and \emph{i} is the order of zeta.
#' @details \code{Zeta.order.mc} enables accomodating richness heterogeneity by setting \code{normalize = "Jaccard"}, \code{normalize = "Sorensen"} or \code{normalize = "Simpson"}. This cannot be performed by \cr \code{\link{Zeta.order.ex}}.
#' @return \code{Zeta.order.mc} returns a list containing the following components:
#' @return \item{zeta.order}{The number of assemblages or sites for which the zeta diversity was computed.}
#' @return \item{combinations}{The number of possible combinations of sites for the chosen order.}
#' @return \item{zeta.val}{The zeta diversity values.}
#' @return \item{zeta.val.sd}{The standard deviation of zeta diversity.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}
#' @examples
#'
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' zeta.bird <- Zeta.order.mc(data.spec.bird, order = 3, sam=100)
#' zeta.bird
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' zeta.marion <- Zeta.order.mc(data.spec.marion, xy.marion, order = 3, sam = 100,
#' NON = TRUE)
#' zeta.marion
#'
#' @export
Zeta.order.mc <- function(data.spec, xy=NULL, order = 1, sam = 1000, sd.correct = TRUE, sd.correct.adapt = FALSE, rescale = FALSE, normalize = FALSE, NON = FALSE, FPO = NULL, DIR = FALSE, empty.row = "empty", silent=TRUE){
if (!inherits(data.spec,"data.frame")){
stop("Error: ",paste(deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
if((NON == TRUE || !is.null(FPO)) & is.null(xy)){
stop("Error: if NON = TRUE or !is.null(FPO), xy must be non null.")
}
if((NON == TRUE || !is.null(FPO)) && nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if(empty.row == "remove"){
if(length(which(rowSums(data.spec)))>0){
data.spec <- data.spec[-which(rowSums(data.spec)==0),]
}
}
x <- dim(data.spec)[1]
if (is.null(FPO)){
if(order==1){
zeta.val<-mean(rowSums(data.spec))
if(sd.correct == TRUE & sd.correct.adapt == FALSE){
zeta.val.sd <- stats::sd(rowSums(data.spec))
}else{
zeta.val.sd <- stats::sd(rowSums(data.spec))*nrow(data.spec)
}
if(rescale == TRUE || normalize != FALSE){
zeta.val <- 1
zeta.val.sd <- zeta.val.sd/mean(rowSums(data.spec))
}
}else{
if(NON == FALSE){
if(choose(x, order)>sam){
if(silent==FALSE){
print(paste("Monte Carlo sampling for order",order))
}
u <- rep(NA, sam)
for(z in 1:sam){
samp <- sample(1:x, order, replace = FALSE)
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}else{
if(silent==FALSE){
print(paste("Exact solution for order",order))
}
u <- rep(NA, choose(x, order))
samp <- utils::combn(1:x, order)
for(z in 1:dim(samp)[2]){
u[z] <- sum(apply(data.spec[samp[, z], ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp[, z], ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}
}else{
if(x>sam){
u <- rep(NA, sam)
samps <- sample(1:x, sam, replace = FALSE)
for(z in 1:sam){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:order])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}else{
u <- rep(NA, x)
samps <- 1:x
for(z in 1:x){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:order])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}
}
}
if(rescale == TRUE & normalize == FALSE){
#z1 <- mean(rowSums(data.spec))
#u <- u / z1
u <- u / ncol(data.spec)
}
zeta.val <- mean(u)
if(sd.correct.adapt == FALSE){
if(sd.correct == TRUE){
zeta.val.sd <- stats::sd(u)
}else{
zeta.val.sd <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}
}else{
if(x>sam){
zeta.val.sd <- stats::sd(u)*sqrt((length(u)-1)/length(u))
}else{
zeta.val.sd <- stats::sd(u)
}
}
}
}else{
if(DIR == FALSE){
xy.dist <- (FPO[1]-xy[,1])^2+(FPO[2]-xy[,2])^2
samp <- order(xy.dist)[1:order]
u <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u <- 0
}else if(empty.row == 1){
u <- 1
}
}else
u <- u / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u <- 0
}else if(empty.row == 1){
u <- 1
}
}else
u <- u / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u <- 0
}else if(empty.row == 1){
u <- 1
}
}else
u <- u / toto
}
#zeta.val.sd <- 0
}else{
if(order==1){
zeta.val<-mean(rowSums(data.spec))
if(sd.correct == TRUE & sd.correct.adapt == FALSE){
zeta.val.sd <- stats::sd(rowSums(data.spec))
}else{
zeta.val.sd <- stats::sd(rowSums(data.spec))*nrow(data.spec)
}
if(rescale == TRUE || normalize != FALSE){
zeta.val <- 1
zeta.val.sd <- zeta.val.sd/mean(rowSums(data.spec))
}
}else{
xy.FPO <- as.matrix(xy-FPO)
if(x>sam){
u <- rep(NA, sam)
samps <- sample(1:x, sam, replace = FALSE)
for(z in 1:sam){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(order-1)){
samp <- c(samp,order(xy.dist)[1:(order-1)])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",order))
}
u[z] <- NA
}
}
}else{
u <- rep(NA, x)
samps <- 1:x
for(z in 1:(x-order+1)){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(order-1)){
samp <- c(samp,order(xy.dist)[1:(order-1)])
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",order))
}
u[z] <- NA
}
}
}
}
}
zeta.val <- mean(u,na.rm=TRUE)
if(sd.correct.adapt == FALSE){
if(sd.correct == TRUE){
zeta.val.sd <- stats::sd(u,na.rm=TRUE)
}else{
zeta.val.sd <- stats::sd(u,na.rm=TRUE)*sqrt((length(which(!is.na(u)))-1)/length(which(!is.na(u))))
}
}else{
if(x>sam){
zeta.val.sd <- stats::sd(u,na.rm=TRUE)*sqrt((length(which(!is.na(u)))-1)/length(which(!is.na(u))))
}else{
zeta.val.sd <- stats::sd(u,na.rm=TRUE)
}
}
}
zeta.order <- list()
zeta.order$zeta.order <- order
zeta.order$combinations <- choose(x, order)
zeta.order$zeta.val <- zeta.val
zeta.order$zeta.val.sd <- zeta.val.sd
return(zeta.order)
}
#' Number of species in common between a specific number of assemblages or sites using Monte Carlo sampling, for multiple combinations and several groups of taxa
#'
#' Computes the number of species shared by multiple assemblages, for a specific order (number of assemblages or sites), for multiple combinations and several groups of taxa.
#' @param data.spec A list of site-by-species presence-absence data frames, with sites as rows and species as columns.
#' @param xy Site coordinates. This is only used if \code{NON} = TRUE or \code{DIR} = TRUE.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param sd.correct.adapt Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) if \code{sam} is higher than the number of possible combinations, or not (using the number of site combinations as the denominator) if \code{sam} is lower than the number of possible combinations. If \code{sd.correct.adapt == TRUE}, it takes precedence over \code{sd.correct}.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param NON Boolean value (TRUE or FALSE) indicating if the number of species in common should only be counted for the nearest neighbours.
#' @param FPO A vector with the coordinates of the fixed point origin from which the zeta diversity will be computed (overrides NON). In that case, \eqn{\zeta_1} is the number of species in the closest site to the FPO, \eqn{\zeta_2} is the number of species shared by the 2 closest sites, etc.
#' @param DIR Boolean value (TRUE or FALSE) indicating if zeta diversity must be computed using a directed nearest neighbour scheme in the direction away from the FPO, starting from any site.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity, and computation errors for the normalized version of zeta due to divisions by 0. Options are "\code{empty}" to let the data untreated, "\code{remove}" to remove the empty rows, 0 to set the normalized zeta to 0 when zeta is divided by 0 during normalization (sites share no species, so are completely dissimilar), and 1 to set the normalized zeta to 1 when zeta is divided by 0 during normalization (i.e. sites are perfectly similar).
#' @param silent Boolean value (TRUE or FALSE) indicating if messages must be printed.
#' @details Contrary to \code{Zeta.order.mc}, the number of species shared by the different combinations of assemblages are not averaged, but returned as is. This is useful to then compare local zeta diversity for different groups of taxa.
#' @details As for \code{Zeta.order.mc}, if the number of combinations of sites is lower than the value of the parameter \code{sam}, all the combinations are used and an exact solution is computed. In that case, using the number of site combinations as the denominator may be appropriate to compute the standard deviation, if all sites were sampled and the zeta values. This can be adjusted with parameters \code{sd.correct} and \code{sd.correct.adapt}.
#' @return \code{Zeta.order.mc.mult} returns a list containing the following components:
#' @return \item{zeta.order}{The number of assemblages or sites for which the zeta diversity was computed.}
#' #' @return \item{sites}{A matrix in which each row contains the indices of a given combination, i.e. of the specific \code{sam} assemblages.}
#' @return \item{zeta.val}{A data frame in which each column is the number of species shared by the assemblages.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}
#' @examples
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#'
#' data.spec.marion <- Marion.species[3:33]
#'
#' ##random other communities
#' data.spec.marion2a <- data.spec.marion
#' data.spec.marion2a[which(data.spec.marion2a==1,arr.ind=TRUE)] <- 0
#' for(i in 1:ncol(data.spec.marion2a))
#' data.spec.marion2a[sample(nrow(data.spec.marion2a),8),i] <- 1
#' data.spec.marion2b <- data.spec.marion
#' data.spec.marion2b[which(data.spec.marion2b==1,arr.ind=TRUE)] <- 0
#' for(i in 1:ncol(data.spec.marion2b))
#' data.spec.marion2b[sample(nrow(data.spec.marion2b),8),i] <- 1
#'
#' dat.spec.tot <- list(data.spec.marion,data.spec.marion2a,data.spec.marion2b)
#' zeta.tot <- Zeta.order.mc.mult(data.spec=dat.spec.tot,order=3,sam=200)
#'
#' @export
Zeta.order.mc.mult <- function(data.spec, xy=NULL, order = 1, sam = 1000, sd.correct = TRUE, sd.correct.adapt = FALSE, rescale = FALSE, normalize = FALSE, NON = FALSE, FPO = NULL, DIR = FALSE, empty.row = "empty", silent=TRUE){
if(!inherits(data.spec,"list")){
stop("Error: ",paste(deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a list of ata frames.", sep = ""))
}
if((NON == TRUE || !is.null(FPO)) & is.null(xy)){
stop("Error: if NON = TRUE or !is.null(FPO), xy must be non null.")
}
if((NON == TRUE || !is.null(FPO)) && nrow(data.spec[[1]]) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
x <- dim(data.spec[[1]])[1]
zeta.val <- list()
u <- list()
#sites <- matrix(NA,sam,order)
if (is.null(FPO)){
if(order==1){
for(i in 1:length(data.spec))
zeta.val[[i]]<-(rowSums(data.spec[[i]]))
sites <- matrix(1:length(data.spec),length(data.spec),1)
}else{
if(NON == FALSE){
if(choose(x, order)>sam){
if(silent==FALSE){
print(paste("Monte Carlo sampling for order",order))
}
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, sam)
}
sites <- matrix(NA,sam,order)
for(z in 1:sam){
samp <- sample(1:x, order, replace = FALSE)
sites[z,] <- samp
for(i in 1:length(data.spec)){
u[[i]][z] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}
}else{
if(silent==FALSE){
print(paste("Exact solution for order",order))
}
u <- list()
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, choose(x, order))
}
samp <- utils::combn(1:x, order)
sites <- t(samp)
for(i in 1:length(data.spec)){
for(z in 1:dim(samp)[2]){
u[[i]][z] <- sum(apply(data.spec[[i]][samp[, z], ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp[, z], ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}
}
}else{
if(x>sam){
u <- list()
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, sam)
}
samps <- sample(1:x, sam, replace = FALSE)
sites <- matrix(NA,sam,order)
for(z in 1:sam){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:order])
sites[z,] <- samp
for(i in 1:length(data.spec)){
u[[i]][z] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}
}else{
u <- list()
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, x)
}
samps <- 1:x
sites <- matrix(NA,x,order)
for(z in 1:x){
samp <- samps[z]
xy.dist <- (xy[,1]-xy[samp,1])^2+(xy[,2]-xy[samp,2])^2
samp <- c(samp,order(xy.dist)[2:order])
sites[z,] <- samp
for(i in 1:length(data.spec)){
u[[i]][z] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}
}
}
if(rescale == TRUE & normalize == FALSE){
for(i in 1:length(data.spec)){
u[[i]] <- u[[i]] / ncol(data.spec[[i]][[1]])
}
}
zeta.val <- u
}
}else{
if(DIR == FALSE){
xy.dist <- (FPO[1]-xy[,1])^2+(FPO[2]-xy[,2])^2
samp <- order(xy.dist)[1:order]
sites=samp
for(i in 1:length(data.spec)){
zeta.val[[i]] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
zeta.val[[i]] <- 0
}else if(empty.row == 1){
zeta.val[[i]] <- 1
}
}else
zeta.val[[i]] <- zeta.val[[i]] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
zeta.val[[i]] <- 0
}else if(empty.row == 1){
zeta.val[[i]] <- 1
}
}else
zeta.val[[i]] <- zeta.val[[i]] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
zeta.val[[i]] <- 0
}else if(empty.row == 1){
zeta.val[[i]] <- 1
}
}else
zeta.val[[i]] <- zeta.val[[i]] / toto
}
}
}else{
if(order==1){
for(i in 1:length(data.spec)){
zeta.val[[i]]<-rowSums(data.spec[[i]])
}
}else{
xy.FPO <- as.matrix(xy-FPO)
if(x>sam){
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, sam)
}
samps <- sample(1:x, sam, replace = FALSE)
sites <- matrix(NA,sam,order)
for(z in 1:sam){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(order-1)){
samp <- c(samp,order(xy.dist)[1:(order-1)])
sites[z,] <- samp
for(i in 1:length(data.spec)){
u[[i]][z] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",order))
}
for(i in 1:length(data.spec)){
u[[i]][z] <- NA
}
}
}
}else{
for(i in 1:length(data.spec)){
u[[i]] <- rep(NA, x)
}
samps <- 1:x
sites <- matrix(NA,x,order)
for(z in 1:(x-order+1)){
samp <- samps[z]
xy0 <- xy.FPO[samp,]
no <- sqrt(sum(xy0^2))
R <- matrix(c(xy0[2]/no,xy0[1]/no,-xy0[1]/no,xy0[2]/no),2,2)
xy.FPO.tr <- apply(xy.FPO,1,function(xy.FPO,R,xy0,no){R %*% matrix(xy.FPO,2,1) - c(0,no)},R,xy0,no)
xy.FPO.tr <- as.data.frame(t(xy.FPO.tr))
xy.FPO.tr[samp,] <- c(0,0)
xy.FPO.tr[which(xy.FPO.tr[,2]<=0),] <- NA
xy.dist <- xy.FPO.tr[,1]^2+xy.FPO.tr[,2]^2
if(length(which(!is.na(xy.dist)))>=(order-1)){
samp <- c(samp,order(xy.dist)[1:(order-1)])
sites[z,] <- samp
for(i in 1:length(data.spec)){
u[[i]][z] <- sum(apply(data.spec[[i]][samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec[[i]])-sum(apply((1-data.spec[[i]][samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[[i]][samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[[i]][z] <- 0
}else if(empty.row == 1){
u[[i]][z] <- 1
}
}else
u[[i]][z] <- u[[i]][z] / toto
}
}
}else{
if(silent==FALSE){
print(paste("warning: number of sites away from the FPO too low to compute zeta for order",order))
}
for(i in 1:length(data.spec)){
u[[i]][z] <- NA
}
}
}
}
}
zeta.val <- u
}
}
zeta.order.mult <- list()
zeta.order.mult$zeta.order <- order
zeta.order.mult$sites <- sites
zeta.order.mult$zeta.val <- data.frame(t(matrix(unlist(zeta.val), nrow=length(zeta.val), byrow=T)))
return(zeta.order.mult)
}
#' Expectation of zeta diversity decline
#'
#' Computes the expectation of zeta diversity, the number of species shared by multiple assemblages for a range of orders (number of assemblages or sites), using a formula based on the occupancy of the species, and fits the decline to an exponential and a power law relationship.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param orders Range of number of assemblages or sites for which zeta diversity is computed.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param confint.level Percentage for the confidence intervals of the coefficients from the regressions.
#' @param sd.plot Boolean value (TRUE or FALSE) indicating if the standard deviation of each zeta diversity value must be plotted.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity. Options are "\code{empty}" to let the data untreated or "\code{remove}" to remove the empty rows.
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @details \code{Zeta.decline.ex} is much faster than \code{\link{Zeta.decline.mc}} to compute the exact value of zeta diversity when the number of species is lower than \eqn{C^N_{i}}, where \emph{N} is the total number of sites and \emph{i} is the order of zeta.
#' @details \code{sd.correct} should be set to \code{TRUE} if the assemblages represent a subsample of the whole system. It can be set to \code{FALSE} if the sampling is exhaustive, for example in case of a continuous regular grid covering the whole study area.
#' @details The exponential and the power law fit are performed using linear regressions on log-transformed data (only the zeta values are log-transformed for the exponential fit, and both the orders and the zeta values are log-transformed for the power law fit).
#' @return \code{Zeta.decline.ex} returns a list containing the following components:
#' @return \item{zeta.order}{The number of assemblages or sites for which the zeta diversity was computed.}
#' @return \item{combinations}{The number of possible combinations of sites for the chosen orders.}
#' @return \item{zeta.val}{The zeta diversity values.}
#' @return \item{zeta.val.sd}{The zeta diversity standard deviation values.}
#' @return \item{zeta.ratio}{The ratio of zeta diversity values by the zeta diversity values at the lower order \eqn{\zeta_i / \zeta_{i-1}}.}
#' @return \item{zeta.exp}{Object of class "\code{lm}", containing the output of the exponential regression.}
#' @return \item{zeta.exp.confint}{The confidence intervals of the coefficients of the exponential regression.}
#' @return \item{zeta.pl}{Object of class "\code{lm}", containing the output of the power law regression.}
#' @return \item{zeta.pl.confint}{The confidence intervals of the coefficients of the power law regression.}
#' @return \item{aic}{AIC values for \code{zeta.exp} and \code{zeta.pl}.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references McGeoch M. A., Latombe G., Andrew N. R., Nakagawa S., Nipperess D. A., Roige M., Marzinelli E. M., Campbell A. H., Verges A., Thomas T., Steinberg P. D., Selwood K. E., Henriksen M. V. & Hui C. (2019). Measuring continuous compositional change using decline and decay in zeta diversity. \emph{Ecology}, 100(11), e02832.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.order.ex}}, \code{\link{Plot.zeta.decline}}
#' @examples
#' utils::data(bird.spec.coarse)
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new(width = 12, height = 4)
#' zeta.bird <- Zeta.decline.ex(data.spec.bird, orders = 1:5)
#' zeta.bird
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new(width = 12, height = 4)
#' zeta.marion <- Zeta.decline.ex(data.spec.marion, orders = 1:5)
#' zeta.marion
#'
#' @export
#'
Zeta.decline.ex <- function(data.spec, orders = 1:10, sd.correct = TRUE, confint.level = 0.95, sd.plot = TRUE, rescale = FALSE, empty.row = "empty", plot = TRUE){
if(max(orders)>dim(data.spec)[1]){
stop("Error: wrong value for \"orders\": the maximum value must be equal or lower than the number of sites.")
}
if(empty.row == "remove"){
data.spec <- data.spec[-which(rowSums(data.spec)==0),]
}
data.spec <- as.matrix(data.spec)
intercept_mat <- t(data.spec) %*% data.spec
occupancy <- colSums(data.spec)
zeta.val <- numeric(length=length(orders))
zeta.val.sd <- numeric(length=length(orders))
for(i in orders) {
p <- exp(lchoose(occupancy,i)-lchoose(nrow(data.spec),i))
zeta.val[i] <- sum(p)
varmat <- exp(lchoose(intercept_mat,i)-lchoose(nrow(data.spec),i))
for(j in 1:length(occupancy)) {
for(k in 1:length(occupancy)) {
varmat[j,k] <- varmat[j,k] - p[j]*p[k]
}
}
if(sd.correct == TRUE){
zeta.val.sd[i] <- sqrt(sum(varmat)*choose(nrow(data.spec),i)/(choose(nrow(data.spec),i)-1))
}else{
zeta.val.sd[i] <- sqrt(sum(varmat))
}
}
if(rescale == TRUE){
z1 <- mean(rowSums(data.spec))
zeta.val <- zeta.val / z1
zeta.val.sd <- zeta.val.sd / z1
}
##create a single list for output
zeta <- list()
zeta$zeta.order <- orders
zeta$combinations <- choose(x <- dim(data.spec)[1], orders)
zeta$zeta.val <- zeta.val
zeta$zeta.val.sd <- zeta.val.sd
zeta$ratio <- zeta.val[2:length(zeta.val)]/zeta.val[1:(length(zeta.val)-1)]
##regression - exponential
zeta.val.log <- log10(zeta.val)
zeta.val.log[which(is.infinite(zeta.val.log))] <- NA
zeta.exp <- stats::lm(zeta.val.log ~ c(orders), na.action = stats::na.omit)
zeta$zeta.exp <- zeta.exp
zeta$zeta.exp.confint <- suppressMessages(stats::confint(zeta.exp,level=confint.level))
##regression - power law
zeta.pl <- stats::lm(zeta.val.log ~ log10(c(orders)), na.action = stats::na.omit)
zeta$zeta.pl <- zeta.pl
zeta$zeta.pl.confint <- suppressMessages(stats::confint(zeta.pl,level=confint.level))
zeta$aic <- stats::AIC(zeta$zeta.exp, zeta$zeta.pl)
##Plot zeta and regressions
if(plot == TRUE){
Plot.zeta.decline(zeta, sd.plot=sd.plot)
}
return(zeta)
}
#' Expectation of zeta diversity for a specific number of assemblages or sites
#'
#' Computes the expectation of zeta diversity, the number of species shared by multiple assemblages, for a specific order (number of assemblages or sites) using a formula based on the occupancy of the species.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity. Options are "empty" to let the data untreated or "remove" to remove the empty rows.
#' @details \code{Zeta.order.ex} is much faster than \code{\link{Zeta.order.mc}} to compute the exact value of zeta diversity when the number of species is lower than \eqn{C^N_{i}}, where \emph{N} is the total number of sites and \emph{i} is the order of zeta.
#' @details \code{sd.correct} should be set to \code{TRUE} if the assemblages represent a subsample of the whole system. It can be set to \code{FALSE} if the sampling is exhaustive, for example in case of a continuous regular grid covering the whole study area.
#' @return \code{zeta.order.ex} returns a list containing the following components:
#' @return \item{zeta.order}{The number of assemblages or sites for which the zeta diversity was computed.}
#' @return \item{combinations}{The number of possible combinations of sites for the chosen order.}
#' @return \item{zeta.val}{The zeta diversity values.}
#' @return \item{zeta.val.sd}{The standard deviation of zeta diversity.}
#' @references Hui C. & McGeoch M.A. (2014). zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references McGeoch M. A., Latombe G., Andrew N. R., Nakagawa S., Nipperess D. A., Roige M., Marzinelli E. M., Campbell A. H., Verges A., Thomas T., Steinberg P. D., Selwood K. E., Henriksen M. V. & Hui C. (2019). Measuring continuous compositional change using decline and decay in zeta diversity. \emph{Ecology}, 100(11), e02832.
#' @seealso \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.decline.mc}}
#' @examples
#'
#' utils::data(bird.spec.coarse)
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' zeta.bird <- Zeta.order.ex(data.spec.bird, order = 3)
#' zeta.bird
#'
#' ##########
#'s
#' utils::data(Marion.species)
#' data.spec.marion <- Marion.species[,3:33]
#'
#' zeta.marion <- Zeta.order.ex(data.spec.marion, order = 3)
#' zeta.marion
#'
#' @export
Zeta.order.ex <- function(data.spec, order = 1, sd.correct = TRUE, rescale = FALSE, empty.row="empty"){
if(empty.row == "remove"){
data.spec <- data.spec[-which(rowSums(data.spec)==0),]
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
data.spec <- as.matrix(data.spec)
intercept_mat <- t(data.spec) %*% data.spec
occupancy <- colSums(data.spec)
p <- exp(lchoose(occupancy,order)-lchoose(nrow(data.spec),order))
zeta.val <- sum(p)
varmat <- exp(lchoose(intercept_mat,order)-lchoose(nrow(data.spec),order))
for(j in 1:length(occupancy)) {
for(k in 1:length(occupancy)) {
varmat[j,k] <- varmat[j,k] - p[j]*p[k]
}
}
if(sd.correct == TRUE){
zeta.val.sd <- sqrt(sum(varmat)*choose(nrow(data.spec),order)/(choose(nrow(data.spec),order)-1))
}else{
zeta.val.sd <- sqrt(sum(varmat))
}
zeta.order <- list()
zeta.order$zeta.order <- order
zeta.order$combinations <- choose(x <- dim(data.spec)[1], order)
zeta.order$zeta.val <- zeta.val
zeta.order$zeta.val.sd <- zeta.val.sd
return(zeta.order)
}
#' Zeta diversity decline plotting
#'
#' Plots the output of the functions \code{Zeta.decline.mc} and \code{Zeta.decline.ex}.
#' @param zeta A list produced by the function \code{Zeta.decline.mc} or \code{Zeta.decline.ex}.
#' @param sd.plot Boolean value (TRUE or FALSE) indicating if the standard deviation of each zeta diversity value must be plotted.
#' @param arrange.plots Boolean value (TRUE or FALSE) indicating if the graphics device must be divided into 4 subplots.
#' @return A plot of the zeta decline with 4 subplots displaying (i) the raw decline, (ii) the ratios of the zeta values (computed as \eqn{\zeta_i / \zeta_{i-1}}), (iii) the fit in a log plot and (iv) the fit in a log-log plot.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}
#' @examples
#'
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[1:2]
#' data.spec.bird <- bird.spec.coarse[3:193]
#'
#' dev.new(width = 12, height = 4)
#' zeta.bird <- Zeta.decline.mc(data.spec.bird, orders = 1:5, sam=100, plot = FALSE)
#' Plot.zeta.decline(zeta.bird)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#' data.spec.marion <- Marion.species[3:33]
#'
#' dev.new(width = 12, height = 4)
#' zeta.marion <- Zeta.decline.ex(data.spec.marion, orders = 1:5, plot = FALSE)
#' Plot.zeta.decline(zeta.marion)
#'
#' @export
#'
Plot.zeta.decline <- function(zeta, sd.plot = TRUE, arrange.plots = TRUE){
if(arrange.plots == TRUE){
graphics::par(mfrow = c(1, 4))
}
if (sd.plot == TRUE){
graphics::plot(zeta$zeta.order, zeta$zeta.val, xlab = "Zeta order", ylab = "Zeta diversity", pch = 20, ylim = c(0, zeta$zeta.val[1] + zeta$zeta.val.sd[1]), main = "Zeta diversity decline")
graphics::lines(zeta$zeta.order, zeta$zeta.val)
##sd of zeta as error bars
graphics::lines(zeta$zeta.order,zeta$zeta.val + zeta$zeta.val.sd,lty=2)
graphics::lines(zeta$zeta.order,zeta$zeta.val - zeta$zeta.val.sd,lty=2)
}else{
graphics::plot(zeta$zeta.order, zeta$zeta.val, xlab = "Zeta order", ylab = "Zeta diversity", pch = 20, ylim = c(0, zeta$zeta.val[1]), main = "Zeta diversity decline")
graphics::lines(zeta$zeta.order, zeta$zeta.val)
}
graphics::plot(zeta$zeta.order[1:(length(zeta$zeta.order)-1)],zeta$ratio,pch=20,xlab = "Zeta order", ylab = "Zeta ratio", main = "Ratio of zeta diversity decline")
graphics::lines(zeta$zeta.order[1:(length(zeta$zeta.order)-1)],zeta$ratio)
graphics::plot(zeta$zeta.order, zeta$zeta.val, log = "y", pch = 20, xlab = "Zeta order", ylab = "Zeta diversity", main = "Exponential regression")
graphics::lines(zeta$zeta.order, 10^stats::predict.lm(zeta$zeta.exp, data.frame(zeta$zeta.order)))
graphics::plot(zeta$zeta.order, zeta$zeta.val, log = "xy", pch = 20, xlab = "Zeta order", ylab = "Zeta diversity", main = "Power law regression")
graphics::lines(zeta$zeta.order, 10^stats::predict.lm(zeta$zeta.pl, data.frame(zeta$zeta.order)))
}
#' Sensitivity analysis for the sample size of zeta
#'
#' Computes zeta diversity for a given order (number of assemblages or sites) for a range of sample sizes, to assess the sensitivity to this parameter.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param xy Site coordinates. This is only used if \code{NON} = TRUE or \code{DIR} = TRUE.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam.seq Sequence of samples for which the zeta diversity is computed.
#' @param reps Number of replicates of zeta diversity computations for each sample size.
#' @param sd.correct Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) or not (using the number of site combinations as the denominator).
#' @param sd.correct.adapt Boolean value (TRUE or FALSE) indicating if the standard deviation must be computed with an unbiased estimator (using the number of site combinations - 1 as the denominator) if \code{sam} is higher than the number of possible combinations, or not (using the number of site combinations as the denominator) if \code{sam} is lower than the number of possible combinations. If \code{sd.correct.adapt == TRUE}, it takes precedence over \code{sd.correct}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1.
#' @param NON Boolean value (TRUE or FALSE) indicating if the number of species in common should only be counted for the nearest neighbours.
#' @param FPO A vector with the coordinates of the fixed point origin from which the zeta diversity will be computed (overrides NON). In that case, \eqn{\zeta_1} is the number of species in the closest site to the FPO, \eqn{\zeta_2} is the number of species shared by the 2 closest sites, etc.
#' @param DIR Boolean value (TRUE or FALSE) indicating if zeta diversity must be computed using a directed nearest neighbour scheme in the direction away from the FPO, starting from any site.
#' @param display Boolean value (TRUE or FALSE) indicating if the current value of the sample size must be displayed. Acts as a counter.
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted as a boxplot of the zeta diversity distributions for each sample size
#' @param notch Boolean value (TRUE or FALSE) indicating if the notches must be plotted in the boxplot.
#' @return \code{Zeta.sam.sensitivity} returns a matrix with \code{(sam.max-sam.min)/sam.incr} columns and \code{reps} rows.
#' @details Note that the execution of \code{Zeta.sam.sensitivity} can be quite lengthy, because of the number of replicates needed.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}
#' @examples
#' \donttest{
#' #Note that the sensitivity analyses in the following two examples are quite long to run,
#' #typically around 10 minutes for the first example and 1-2 minutes for the second.
#'
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[1:2]
#' data.spec.bird <- bird.spec.coarse[3:193]
#'
#' dev.new()
#' zeta.sens.bird <- Zeta.sam.sensitivity(data.spec.bird, order = 3,
#' sam.seq = seq(250,1000,250), reps = 20, display = TRUE, plot = TRUE, notch = TRUE)
#' zeta.sens.bird
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#' data.spec.marion <- Marion.species[3:33]
#'
#' dev.new()
#' zeta.sens.marion <- Zeta.sam.sensitivity(data.spec.marion, order = 3,
#' sam.seq = seq(50,250,50), reps = 20, plot = TRUE, notch = TRUE)
#' zeta.sens.marion
#' }
#'
#' @export
Zeta.sam.sensitivity <- function(data.spec, xy = NULL, order = 1, sam.seq, reps = 20, sd.correct = TRUE, sd.correct.adapt = FALSE, rescale = FALSE, normalize = FALSE, NON = FALSE, FPO = NULL, DIR = FALSE, display = TRUE, plot = TRUE, notch = TRUE){
if (!inherits(data.spec,"data.frame")){
stop("Error: ",paste(deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
x <- dim(data.spec)[1]
zeta.val <- matrix(NA, reps, length(sam.seq))
zeta.val.sd <- matrix(NA, reps, length(sam.seq))
i.sam <- 0
for(sam in sam.seq){
if(display == TRUE){print(sam)}
i.sam <- i.sam + 1
for(i in 1:reps){
u <- rep(NA, sam)
for(j in 1:order){
zeta <- Zeta.order.mc(data.spec = data.spec, xy = xy, order = order, sam = sam, sd.correct = sd.correct, sd.correct.adapt = sd.correct.adapt, rescale = rescale, normalize = normalize, NON = NON, FPO = FPO, DIR = DIR, silent=TRUE)
zeta.val[i, i.sam] <- zeta$zeta.val
zeta.val.sd[i, i.sam] <- zeta$zeta.val.sd
}
}
}
if (plot == TRUE){
graphics::boxplot(zeta.val, notch = notch, names = sam.seq, xlab = "number of samples", ylab = paste("zeta ", order, sep = ""), main = "Distributions of zeta diversities for different number of samples")
}
zeta.sens <- zeta.val
return(zeta.sens)
}
#' Multi-site generalised dissimilarity modelling for a set of environmental variables and distances
#'
#' Computes a regression model of zeta diversity for a given order (number of assemblages or sites) against a set of environmental variables and distances between sites. The different regression models available are generalised linear models, generalised linear models with negative constraints, generalised additive models, shape constrained additive models, and I-splines.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param data.env Site-by-variable data frame, with sites as rows and environmental variables as columns.
#' @param xy Site coordinates, to account for distances between sites.
#' @param data.spec.pred Site-by-species presence-absence data frame or list of data frames, with sites as rows and species as columns, for which zeta diversity will be computed and used as a predictor of the zeta diversity of \code{data.spec}.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param reg.type Type of regression used in the multi-site generalised dissimilarity modelling. Options are "\code{glm}" for generalised linear models, "\code{ngls}" for negative linear models, "\code{gam}" for generalised additive models, "\code{scam}" for shape constrained additive models (with monotonic decreasing by default), and "\code{ispline}" for I-spline models (forcing monotonic decline), as recommended in generalised dissimilarity modelling by Ferrier \emph{et al}. (2007).
#' @param family A description of the error distribution and link function to be used in the \code{glm}, \code{gam} and \code{scam} models (see \code{\link[stats]{family}} for details of family functions).
#' @param method.glm Method used in fitting the generalised linear model. The default method \cr "glm.fit.cons" is an adaptation of method \code{glm.fit2} from package \code{glm2} using a constrained least squares regression (default is negative coefficients) in the reweighted least squares. Another option is "glm.fit2", which calls \code{glm.fit2}; see help documentation for glm.fit2 in package \code{glm2}.
#' @param cons type of constraint in the glm if \code{method.glm = "glm.fit.cons"}. Default is -1 for negative coefficients on the predictors. The other option is 1 for positive coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param confint.level Percentage for the confidence intervals of the coefficients from the generalised linear models.
#' @param bs A two-letter character string indicating the (penalized) smoothing basis to use in the scam model. Default is "\code{mpd}" for monotonic decreasing splines. see \code{\link[mgcv]{smooth.terms}} for an overview of what is available.
#' @param kn Number of knots in the GAM and SCAM. Default is -1 for determining kn automatically using Generalized Cross-validation.
#' @param order.ispline Order of the I-spline.
#' @param kn.ispline Number of knots in the I-spline.
#' @param distance.type Method to compute distance. Default is "\code{Euclidean}", for Euclidean distance. The other options are (i) "\code{ortho}" for orthodromic distance, if xy correspond to longitudes and latitudes (orthodromic distance is computed using the \code{geodist} function from package \code{geodist}); and (ii) "\code{custom}", in which case the user must provide a distance matrix for \code{dist.custom}.
#' @param dist.custom Distance matrix provided by the user when \code{distance.type} = \code{"custom"}.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by the total number of species in the dataset, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param rescale.pred Boolean value (TRUE or FALSE) indicating if the spatial distances and differences in environmental variables should be rescaled between 0 and 1.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param method Name of a function (as a string) indicating how to combine the pairwise differences and distances for more than 3 sites. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param silent Boolean value (TRUE or FALSE) indicating if warnings must be printed.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity, and computation errors for the normalized version of zeta due to divisions by 0. Options are "\code{empty}" to let the data untreated, "\code{remove}" to remove the empty rows, 0 to set the normalized zeta to 0 when zeta is divided by 0 during normalization (sites share no species, so are completely dissimilar), and 1 to set the normalized zeta to 1 when zeta is divided by 0 during normalization (i.e. sites are perfectly similar).
#' @param control As for \code{\link{glm}}.
#' @param glm.init Boolean value, indicating if the initial parameters for fitting the glm with constraint on the coefficients signs for \code{reg.type == "ispline"} should be initialised based on the correlation coefficients betwen the zeta values and the environmental difference or distance. \code{glm.init = TRUE} helps preventing the error message: \code{error: cannot find valid starting values:} \cr \code{please specify some}.
#' @return \code{Zeta.msgdm} returns a list whose component vary depending on the regression technique. The list can contain the following components:
#' @return \item{val}{Vector of zeta values used in the MS-GDM.}
#' @return \item{predictors}{Data frame of the predictors used in the MS-GDM.}
#' @return \item{range.min}{Vector containing the minimum values of the numeric variables, used for rescaling the variables between 0 and 1 for I-splines (see Details).}
#' @return \item{range.max}{Vector containing the maximum values of the numeric variables, used for rescaling the variables between 0 and 1 for I-splines (see Details).}
#' @return \item{rescale.factor}{Factor by which the predictors were divided if \code{rescale.pred = TRUE} and \code{order>1}.}
#' @return \item{order.ispline}{The value of the original parameter, to be used in \code{Plot.ispline}.}
#' @return \item{kn.ispline}{The value of the original parameter, to be used in \code{Plot.ispline}.}
#' @return \item{model}{An object whose class depends on the type of regression (\code{glm}, \code{nnnpls}, \code{gam} or \code{scam}; I-splines return and object of class \code{glm}), corresponding to the regression over distance for the number of assemblages or sites specified in \code{order}.}
#' @return \item{confint}{The confidence intervals for the coefficients from generalised linear models with no constraint. \code{confint} is not generated for the other types of regression.}
#' @return \item{vif}{The variance inflation factors for all the variables for the generalised linear regression. \code{vif} is not generated for the other types of regression.}
#' @details The environmental variables can be numeric or factorial.
#' @details If \code{order = 1}, the variables are used as such in the regression, and factorial variables must be dummy for the output of the regression to be interpretable.
#' @details For numeric variables, if \code{order>1} the pairwise difference between sites is computed and combined according to \code{method}. For factorial variables, the distance corresponds to the number of unique values over the number of assemblages of sites specified by \code{order}.
#' @details If \code{xy = NULL}, \code{Zeta.msgdm} only uses environmental variables in the regression. Otherwise, it also computes and uses euclidian distance (average or maximum distance between multiple sites, depending on the parameters \code{method}) as an explanatory variable.
#' @details If \code{rescale.pred = TRUE}, zeta is regressed against the differences of values of the environmental variables divided by the maximum difference for each variable, to be rescaled between 0 and 1. If \code{!is.null(xy)}, distances between sites are also divided by the maximum distance. If \code{order = 1}, the variables are transformed by first subtracting their minimum value, and dividing by the difference of their maximum and minimum values.
#' @details If \code{reg.type = "ispline"}, the variables are rescaled between 0 and 1 prior to computing the I-splines by subtracting their minimum value, and dividing by the difference of their maximum and minimum values.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Ferrier, S., Manion, G., Elith, J., & Richardson, K. (2007). Using generalized dissimilarity modelling to analyse and predict patterns of beta diversity in regional biodiversity assessment. \emph{Diversity and Distributions}, 13(3), 252-264.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Predict.msgdm}},
#' @seealso \code{\link{Ispline}}
#' @import scam
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[1:2]
#' data.spec.bird <- bird.spec.coarse[3:193]
#' utils::data(bird.env.coarse)
#' data.env.bird <- bird.env.coarse[,3:9]
#'
#' zeta.glm <- Zeta.msgdm(data.spec.bird, data.env.bird, sam = 100, order = 3)
#' zeta.glm
#' dev.new()
#' graphics::plot(zeta.glm$model)
#'
#' zeta.ngls <- Zeta.msgdm(data.spec.bird, data.env.bird, xy.bird, sam = 100, order = 3,
#' reg.type = "ngls", rescale = TRUE)
#' zeta.ngls
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#' data.spec.marion <- Marion.species[3:33]
#' utils::data(Marion.env)
#' data.env.marion <- Marion.env[3]
#'
#' zeta.gam <- Zeta.msgdm(data.spec.marion, data.env.marion, sam = 100, order = 3,
#' reg.type = "gam")
#' zeta.gam
#' dev.new()
#' graphics::plot(zeta.gam$model)
#'
#' zeta.ispline <- Zeta.msgdm(data.spec.marion, data.env.marion, xy.marion, sam = 100,
#' order = 3, normalize = "Jaccard", reg.type = "ispline")
#' zeta.ispline
#'
#' zeta.ispline.r <- Return.ispline(zeta.ispline, data.env.marion, distance = TRUE)
#' zeta.ispline.r
#'
#' dev.new()
#' Plot.ispline(isplines = zeta.ispline.r, distance = TRUE)
#'
#' dev.new()
#' Plot.ispline(msgdm = zeta.ispline, data.env = data.env.marion, distance = TRUE)
#'
#' @export
Zeta.msgdm <- function (data.spec, data.env, xy = NULL, data.spec.pred = NULL, order = 1, sam = 1000, reg.type = "glm", family = stats::gaussian(), method.glm = "glm.fit.cons", cons = -1, cons.inter = 1, confint.level = 0.95, bs = "mpd", kn = -1, order.ispline = 2, kn.ispline = 1, distance.type = "Euclidean", dist.custom = NULL, rescale = FALSE, rescale.pred = TRUE, method = "mean", normalize = FALSE, silent = FALSE, empty.row = 0, control = list(), glm.init = FALSE) {
if (nrow(data.spec) != nrow(data.env)) {
stop("Error: data.spec and data.env must have the same number of rows.")
}
if (!is.null(xy)) {
if (nrow(data.spec) != nrow(xy) || nrow(data.env) !=
nrow(xy)) {
stop("Error: data.spec, data.env and xy must have the same number of rows.")
}
}
if (!inherits(data.spec,"data.frame")) {
stop(paste("Error: ", deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if (!inherits(data.env,"data.frame")) {
stop(paste("Error: ", deparse(substitute(data.env)), " is a ", class(data.env), ". It must be a data frame.", sep = ""))
}
if (order > dim(data.spec)[1]) {
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
if (length(which(sapply(data.env, inherits, c("factor", "numeric"))==0)) > 0) {
stop("Error: variables must be numeric or factor")
}
if (order == 1 & (!is.null(xy) | distance.type == "custom")) {
stop("Error: cannot include distance for order = 1")
}
if (silent == FALSE & order == 1 & sum(sapply(data.env, inherits, "factor")) > 0) {
warning("factor variables should be dummy for order = 1")
}
if (silent == FALSE & !is.null(dist.custom)) {
if (!isSymmetric(dist.custom)) {
warning("Distance matrix is not symmetrical")
}
}
if (empty.row == "remove") {
if (length(which(rowSums(data.spec) == 0)) > 0) {
data.env <- data.env[-which(rowSums(data.spec) == 0), ]
if (!is.null(xy))
xy <- xy[-which(rowSums(data.spec) == 0), ]
if (!is.null(data.spec.pred))
if (inherits(data.spec.pred,"data.frame") )
data.spec.pred <- data.spec.pred[-which(rowSums(data.spec) == 0), ]
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) data.spec.pred[[p]] <- data.spec.pred[[p]][-which(rowSums(data.spec) == 0), ]
}
data.spec <- data.spec[-which(rowSums(data.spec) == 0), ]
}
}
if (reg.type == "ispline") {
num <- which(sapply(data.env, inherits, "numeric"))
if (length(num) > 1) {
range.min <- apply(data.env[, num], 2, min)
range.max <- apply(data.env[, num], 2, max)
}else {
range.min <- min(data.env[, num])
range.max <- max(data.env[, num])
}
}
if (reg.type == "ispline") {
data.env.num <- as.data.frame(data.env[, which(sapply(data.env, inherits, "numeric"))])
names(data.env.num) <- names(data.env)[which(sapply(data.env, inherits, "numeric"))]
ts <- matrix(NA, ncol(data.env.num), 2 * order.ispline + kn.ispline)
for (i in 1:ncol(data.env.num)) {
data.env.num[, i] <- (data.env.num[, i] - min(data.env.num[, i]))/(max(data.env.num[, i]) - min(data.env.num[, i]))
ts[i, ] <- c(rep(0, order.ispline), stats::quantile(data.env.num[, i], probs = seq(1/(kn.ispline + 1), 1 - 1/(kn.ispline + 1), 1/(kn.ispline + 1))), rep(1, order.ispline))
}
IE <- matrix(NA, nrow(data.env.num), (ncol(data.env.num) * (order.ispline + kn.ispline)))
k = order.ispline
for (j in 1:ncol(data.env.num)) {
for (i in 1:(order.ispline + kn.ispline)) {
xx <- 0
for (x in data.env.num[, j]) {
xx <- xx + 1
if (x == 1) {
IE[xx, (j - 1) * (order.ispline + kn.ispline) + i] <- 1
}else {
IE[xx, (j - 1) * (order.ispline + kn.ispline) + i] <- .Ii(i, k, x, ts[j, ])
}
}
}
}
IE <- data.frame(IE)
for (i in 1:(ncol(IE)/(order.ispline + kn.ispline))) {
for (j in 1:(order.ispline + kn.ispline)) {
names(IE)[(i - 1) * (order.ispline + kn.ispline) + j] <- paste(names(data.env.num)[i], j, sep = "")
}
}
Fa <- as.data.frame(data.env[, which(sapply(data.env, inherits, "factor"))])
names(Fa) <- names(data.env)[which(sapply(data.env, inherits, "factor"))]
data.env <- cbind(data.frame(IE), Fa)
}
x.dim <- dim(data.spec)[1]
zeta.val <- numeric()
zeta.val.sd <- numeric()
if (order == 1) {
if (nrow(data.spec) < sam) {
zeta.val <- rowSums(data.spec)
data.var <- data.env
}
else {
samp <- sample(nrow(data.spec), sam)
zeta.val <- rowSums(data.spec[samp, ])
data.var <- data.env[samp, ]
}
if (rescale == TRUE || normalize != FALSE) {
zeta.val <- zeta.val/max(zeta.val)
}
}else {
if (choose(x.dim, order) > sam) {
u <- rep(NA, sam)
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2 <- rep(NA, sam)
if (inherits(data.spec.pred,"list")) {
u2 <- list()
for (p in 1:length(data.spec.pred)) u2[[p]] <- rep(NA, sam)
}
}
data.var <- as.data.frame(matrix(NA, sam, dim(data.env)[2]))
distance <- rep(NA, sam)
for (z in 1:sam) {
samp <- sample(1:x.dim, order, replace = FALSE)
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2[z] <- sum(apply(data.spec.pred[samp,
], 2, prod))
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) u2[[p]][z] <- sum(apply(data.spec.pred[[p]][samp, ], 2, prod))
}
}
if (normalize == "Jaccard") {
toto <- (ncol(data.spec) - sum(apply((1 - data.spec[samp, ]), 2, prod)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (ncol(data.spec.pred) - sum(apply((1 - data.spec.pred[samp, ]), 2, prod)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (ncol(data.spec.pred[[p]]) - sum(apply((1 - data.spec.pred[[p]][samp, ]), 2, prod)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}else if (normalize == "Sorensen") {
toto <- (mean(apply(data.spec[samp, ], 1,
sum)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (mean(apply(data.spec.pred[samp, ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (mean(apply(data.spec.pred[[p]][samp, ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}else if (normalize == "Simpson") {
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (min(apply(data.spec.pred[samp, ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (min(apply(data.spec.pred[[p]][samp, ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}
fac <- which(sapply(data.env, inherits, "factor"))
num <- which(sapply(data.env, inherits, "numeric"))
if (order > 2) {
if (length(num) > 1) {
toto <- data.env[samp,num]
rownames(toto) <- c()
data.var[z, num] <- apply(apply(toto, 2, stats::dist), 2, get(method))
}else if (length(num) > 0) {
toto <- data.env[samp,num]
rownames(toto) <- c()
data.var[z, num] <- apply(as.matrix(c(stats::dist(toto))), 2, get(method))
}
}else {
if (length(num) > 1) {
toto <- data.env[samp,num]
rownames(toto) <- c()
data.var[z, num] <- apply(toto, 2, stats::dist)
}else if (length(num) > 0) {
toto <- data.env[samp,num]
rownames(toto) <- c()
data.var[z, num] <- stats::dist(toto)
}
}
if (length(fac) > 1) {
toto <- data.env[samp,fac]
rownames(toto) <- c()
data.var[z, fac] <- apply(toto, 2, function(x) {length(unique(x))}) - 1
}else if (length(fac) > 0) {
toto <- data.env[samp,fac]
rownames(toto) <- c()
data.var[z, fac] <- length(unique(toto)) - 1
}
if (!is.null(xy)) {
if (distance.type == "Euclidean") {
distance[z] <- apply(as.matrix(c(stats::dist(xy[samp, ]))), 2, get(method))
}else if (distance.type == "ortho") {
distance[z] <- apply(as.matrix(c(.gdist_matrix(xy[samp, ]))), 2, get(method))
}else {
stop("Error: invalid distance type")
}
}else if (distance.type == "custom") {
if (is.null(dist.custom)) {
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
distance[z] <- apply(as.matrix(dist.custom[t(utils::combn(sort(samp), 2))]), 2, get(method))
}
}
if (rescale == TRUE & normalize == FALSE) {
u <- u/ncol(data.spec)
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2 <- u2/ncol(data.spec.pred)
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) u2[[p]] <- u2[[p]]/ncol(data.spec.pred[[p]])
}
}
}
}else {
u <- rep(NA, choose(x.dim, order))
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2 <- rep(NA, choose(x.dim, order))
if (inherits(data.spec.pred,"list")) {
u2 <- list()
for (p in 1:length(data.spec.pred)) u2[[p]] <- rep(NA, choose(x.dim, order))
}
}
data.var <- as.data.frame(matrix(NA, choose(x.dim, order), dim(data.env)[2]))
distance <- rep(NA, choose(x.dim, order))
samp <- utils::combn(1:x.dim, order)
for (z in 1:dim(samp)[2]) {
u[z] <- sum(apply(data.spec[samp[, z], ], 2, prod))
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2[z] <- sum(apply(data.spec.pred[samp[, z], ], 2, prod))
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) u2[[p]][z] <- sum(apply(data.spec.pred[[p]][samp[, z], ], 2, prod))
}
}
if (normalize == "Jaccard") {
toto <- (ncol(data.spec) - sum(apply((1 - data.spec[samp[, z], ]), 2, prod)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (ncol(data.spec.pred) - sum(apply((1 - data.spec.pred[samp[, z], ]), 2, prod)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (ncol(data.spec.pred[[p]]) - sum(apply((1 - data.spec.pred[[p]][samp[, z], ]), 2, prod)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}else if (normalize == "Sorensen") {
toto <- (mean(apply(data.spec[samp[, z], ], 1, sum)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (mean(apply(data.spec.pred[samp[, z], ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (mean(apply(data.spec.pred[[p]][samp[, z], ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}else if (normalize == "Simpson") {
toto <- (min(apply(data.spec[samp[, z], ], 1, sum)))
if (toto == 0) {
if (empty.row == 0) {
u[z] <- 0
}else if (empty.row == 1) {
u[z] <- 1
}
}else {
u[z] <- u[z]/toto
}
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
tata <- (min(apply(data.spec.pred[samp[, z], ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[z] <- 0
}else if (empty.row == 1) {
u2[z] <- 1
}
}else {
u2[z] <- u2[z]/tata
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
tata <- (min(apply(data.spec.pred[[p]][samp[, z], ], 1, sum)))
if (tata == 0) {
if (empty.row == 0) {
u2[[p]][z] <- 0
}else if (empty.row == 1) {
u2[[p]][z] <- 1
}
}else {
u2[[p]][z] <- u2[[p]][z]/tata
}
}
}
}
}
fac <- which(sapply(data.env, inherits, "factor"))
num <- which(sapply(data.env, inherits, "numeric"))
if (order > 2) {
if (length(num) > 1) {
toto <- data.env[samp[,z],num]
rownames(toto) <- c()
data.var[z, num] <- apply(apply(toto, 2, stats::dist), 2, get(method))
}else if (length(num) > 0) {
toto <- data.env[samp[,z],num]
rownames(toto) <- c()
data.var[z, num] <- apply(as.matrix(c(stats::dist(toto))), 2, get(method))
}
}else {
if (length(num) > 1) {
toto <- data.env[samp[,z],num]
rownames(toto) <- c()
data.var[z, num] <- apply(toto, 2, stats::dist)
}else if (length(num) > 0) {
toto <- data.env[samp[,z],num]
rownames(toto) <- c()
data.var[z, num] <- stats::dist(toto)
}
}
if (length(fac) > 1) {
toto <- data.env[samp[,z],fac]
rownames(toto) <- c()
data.var[z, fac] <- apply(toto, 2, function(x) {length(unique(x))}) - 1
}else if (length(fac) > 0) {
toto <- data.env[samp[,z],fac]
rownames(toto) <- c()
data.var[z, fac] <- length(unique(toto)) - 1
}
if (!is.null(xy)) {
if (distance.type == "Euclidean") {
distance[z] <- apply(as.matrix(c(stats::dist(xy[samp[, z], ]))), 2, get(method))
}else if (distance.type == "ortho") {
distance[z] <- apply(as.matrix(c(.gdist_matrix(xy[samp[, z], ]))), 2, get(method))
}else {
stop("Error: invalid distance type")
}
}else if (distance.type == "custom") {
if (is.null(dist.custom)) {
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
distance[z] <- apply(as.matrix(dist.custom[t(utils::combn(sort(samp[, z]), 2))]), 2, get(method))
}
}
if (rescale == TRUE & normalize == FALSE) {
u <- u/ncol(data.spec)
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") )
u2 <- u2/ncol(data.spec.pred)
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) u2[[p]] <- u2[[p]]/ncol(data.spec.pred[[p]])
}
}
}
}
zeta.val <- u
}
if (!is.null(xy) | distance.type == "custom") {
distance.raw <- distance
d <- max(distance)
}
if (rescale.pred == TRUE) {
if (order > 1) {
fac <- apply(data.var, 2, max)
data.var <- data.var/matrix(rep(apply(data.var, 2, max), min(choose(x.dim, order), sam)), min(choose(x.dim, order), sam), dim(data.env)[2], byrow = T)
}
else {
if (reg.type != "ispline") {
num <- which(sapply(data.env, inherits, "numeric"))
if (length(num) > 1) {
range.min <- apply(data.var[, num], 2, min)
range.max <- apply(data.var[, num], 2, max)
data.var[, num] <- (data.var[, num] - matrix(rep(apply(data.var[, num], 2, min), min(choose(x.dim, order), sam)), min(choose(x.dim, order), sam), dim(data.var[, num])[2], , byrow = T))/matrix(rep((apply(data.var[, num], 2, max) - apply(data.var[, num], 2, min)), min(choose(x.dim, order), sam)), min(choose(x.dim, order), sam), dim(data.var[, num])[2], byrow = T)
}else {
range.min <- min(data.var[, num])
range.max <- max(data.var[, num])
data.var[, num] <- (data.var[, num] - min(data.var[, num]))/(max(data.var[, num]) - min(data.var[, num]))
}
}
}
if (!is.null(xy) | distance.type == "custom") {
distance <- distance/max(distance)
}
}
names(data.var) <- names(data.env)
if ((!is.null(xy) | distance.type == "custom") & reg.type ==
"ispline") {
dist2 <- distance/max(distance)
ts <- c(rep(0, order.ispline), stats::quantile(dist2, probs = seq(1/(kn.ispline + 1), 1 - 1/(kn.ispline + 1), 1/(kn.ispline + 1))), rep(1, order.ispline))
IE <- matrix(NA, length(distance), (order.ispline + kn.ispline))
k = order.ispline
for (i in 1:(order.ispline + kn.ispline)) {
xx <- 0
for (x in dist2) {
xx <- xx + 1
if (x == 1) {
IE[xx, i] <- 1
}else {
IE[xx, i] <- .Ii(i, k, x, ts)
}
}
}
distance <- data.frame(IE)
for (i in 1:(order.ispline + kn.ispline)) {
names(distance)[i] <- paste("distance", i, sep = "")
}
}
if (reg.type == "ispline") {
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
sp <- 1 - u2
spp <- matrix(sp, length(sp), 1)
ts <- c(rep(0, order.ispline), stats::quantile(sp, probs = seq(1/(kn.ispline + 1), 1 - 1/(kn.ispline + 1), 1/(kn.ispline + 1))), rep(1, order.ispline))
IE <- matrix(NA, length(u2), (order.ispline + kn.ispline))
k = order.ispline
for (i in 1:(order.ispline + kn.ispline)) {
xx <- 0
for (x in sp) {
xx <- xx + 1
if (x == 1) {
IE[xx, i] <- 1
}else {
IE[xx, i] <- .Ii(i, k, x, ts)
}
}
}
sp.prev <- data.frame(IE)
for (i in 1:(order.ispline + kn.ispline)) {
names(sp.prev)[i] <- paste("Biotic", i, sep = "")
}
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
sp <- 1 - u2[[p]]
if (p == 1) {
spp <- matrix(sp, length(sp), 1)
}else {
spp <- cbind(spp, sp)
}
ts <- c(rep(0, order.ispline), stats::quantile(sp, probs = seq(1/(kn.ispline + 1), 1 - 1/(kn.ispline + 1), 1/(kn.ispline + 1))), rep(1, order.ispline))
IE <- matrix(NA, length(u2[[p]]), (order.ispline + kn.ispline))
k = order.ispline
for (i in 1:(order.ispline + kn.ispline)) {
xx <- 0
for (x in sp) {
xx <- xx + 1
if (x == 1) {
IE[xx, i] <- 1
}else {
IE[xx, i] <- .Ii(i, k, x, ts)
}
}
}
if (p == 1) {
sp.prev <- data.frame(IE)
}else {
sp.prev <- cbind(sp.prev, data.frame(IE))
}
}
pp <- 0
for (p in 1:length(data.spec.pred)) {
for (i in 1:(order.ispline + kn.ispline)) {
pp <- pp + 1
names(sp.prev)[pp] <- paste("Biotic_", p, "_", i, sep = "")
}
}
}
}
}else {
if (!is.null(data.spec.pred)) {
if (inherits(data.spec.pred,"data.frame") ){
sp.prev <- data.frame(1 - u2)
names(sp.prev) <- c("Biotic")
}
if (inherits(data.spec.pred,"list")) {
for (p in 1:length(data.spec.pred)) {
if (p == 1) {
sp.prev <- data.frame(1 - u2[[p]])
}else {
sp.prev <- cbind(sp.prev, data.frame(1 - u2[[p]]))
}
}
for (p in 1:length(data.spec.pred)) {
names(sp.prev)[p] <- paste("Biotic", p, sep = "")
}
}
}
}
if (is.null(xy) & distance.type != "custom" & is.null(data.spec.pred)) {
data.tot <- data.var
}else if (is.null(xy) & distance.type != "custom" & !is.null(data.spec.pred)) {
data.tot <- cbind(data.var, sp.prev)
}else if (!is.null(xy) & distance.type != "custom" & is.null(data.spec.pred)) {
data.tot <- cbind(data.var, distance)
}else {
data.tot <- cbind(data.var, sp.prev, distance)
}
zeta.msgdm <- list()
zeta.msgdm$val <- zeta.val
zeta.msgdm$predictors <- data.tot
if (reg.type == "ispline") {
zeta.msgdm$range.min <- range.min
zeta.msgdm$range.max <- range.max
if (!is.null(data.spec.pred))
zeta.msgdm$biotic <- spp
if (!is.null(xy) | distance.type == "custom")
zeta.msgdm$distance <- distance.raw
}
if (rescale.pred == TRUE) {
if (order > 1) {
if (!is.null(xy) | distance.type == "custom") {
zeta.msgdm$rescale.factor <- c(fac, d)
}else {
zeta.msgdm$rescale.factor <- fac
}
}else {
if (reg.type != "ispline") {
num <- which(sapply(data.env, inherits, "numeric"))
if (length(num) > 1) {
zeta.msgdm$range.min <- range.min
zeta.msgdm$range.max <- range.max
}
}
}
}
zeta.msgdm$my.order <- order
zeta.msgdm$order.ispline <- order.ispline
zeta.msgdm$kn.ispline <- kn.ispline
if (reg.type == "glm") {
if (method.glm == "glm.fit.cons") {
zeta.msgdm.model <- glm.cons(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter, control = control)
}else {
zeta.msgdm.model <- glm2::glm2(zeta.val ~ ., data = data.tot, family = family, method = method.glm, control = control)
zeta.msgdm.confint <- suppressMessages(stats::confint(zeta.msgdm.model, level = confint.level))
}
if (dim(data.env)[2] > 1) {
zeta.msgdm.vif <- car::vif(zeta.msgdm.model)
}else {
zeta.msgdm.vif <- NA
}
zeta.msgdm$model <- zeta.msgdm.model
if (method.glm == "glm.fit2")
zeta.msgdm$confint <- zeta.msgdm.confint
zeta.msgdm$vif <- zeta.msgdm.vif
}else if (reg.type == "ngls") {
data.tot2 <- cbind(rep(1, nrow(data.tot)), data.tot)
start <- c(1, rep(-1, ncol(data.tot)))
zeta.msgdm$model <- nnls::nnnpls(as.matrix(data.tot2), zeta.val, con = start)
}else if (reg.type == "gam") {
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ", kn, ") + s(", sep = ""), sep = ""), ", k = ", kn, ")", sep = ""))
zeta.msgdm$model <- mgcv::gam(fm, data = data.tot, family = family)
}else if (reg.type == "scam") {
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ", kn, ", bs = '", bs, "') + s(", sep = ""), sep = ""), ", k = ", kn, ",bs='", bs, "')", sep = ""))
zeta.msgdm$model <- scam::scam(fm, data = data.tot, family = family)
}else if (reg.type == "ispline") {
if (glm.init == TRUE) {
tutu <- stats::cor(data.tot, zeta.val)
tutu[which(tutu > 0)] <- 0
zeta.msgdm$model <- glm.cons(zeta.val ~ ., data = data.tot, family = family, method = "glm.fit.cons", cons = cons, cons.inter = cons.inter, control = control, start = c(-1, tutu))
}else {
zeta.msgdm$model <- glm.cons(zeta.val ~ ., data = data.tot, family = family, method = "glm.fit.cons", cons = cons, cons.inter = cons.inter, control = control)
}
}else {
stop("Error: unknown regression type.")
}
return(zeta.msgdm)
}
#' Fitting Generalized Linear Models with constraint on the coefficients signs
#'
#' \code{glm.cons} is an adaptation of function \code{glm2} from package \{glm2\} in which the least squares estimation is replaced by a regression with signs constraint on the coefficients using function \code{nnnpls} from package \{nnls\}.
#' @param formula as for \code{\link{glm}}
#' @param family as for \code{\link{glm}}
#' @param data as for \code{\link{glm}}
#' @param weights as for \code{\link{glm}}
#' @param subset as for \code{\link{glm}}
#' @param na.action as for \code{\link{glm}}
#' @param start as for \code{\link{glm}}
#' @param etastart as for \code{\link{glm}}
#' @param mustart as for \code{\link{glm}}
#' @param offset as for \code{\link{glm}}
#' @param control as for \code{\link{glm}}
#' @param model as for \code{\link{glm}}
#' @param method the method used in fitting the model. The default method "\code{glm.fit.cons}" uses function {nnnpls} from package nnls instead of \code{lm.fit} to impose the sign of the coefficients. As in \code{glm}, the alternative method "\code{model.frame}" returns the model frame and does no fitting.
#' @param cons type of constraint. Default is -1 for negative coefficients on the predictors. The other option is 1 for positive coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param x as for \code{\link{glm}}
#' @param y as for \code{\link{glm}}
#' @param contrasts as for \code{\link{glm}}
#' @param ... as for \code{\link{glm}}
#' @return The value returned by \code{glm.cons} has exactly the same structure as the value returned by \code{glm} and \code{glm.2}.
#' @references Marschner, I.C. (2011) glm2: Fitting generalized linear models with convergence problems. \emph{The R Journal}, 3(2), 12-15.
#' @seealso \code{\link{glm}}, \code{\link{glm2}}
#' @examples
#' ## Dobson (1990) Page 93: Randomized Controlled Trial :
#' counts <- c(18,17,15,20,10,20,25,13,12)
#' outcome <- gl(3,1,9)
#' treatment <- gl(3,3)
#' print(d.AD <- data.frame(treatment, outcome, counts))
#' glm.D93 <- glm.cons(counts ~ outcome + treatment, family = poisson())
#' glm.D93.ngl <- glm.cons(counts ~ outcome + treatment, family = poisson(),
#' method="glm.fit.cons")
#' summary(glm.D93)
#' summary(glm.D93.ngl)
#' @export
glm.cons <- function (formula, family = stats::gaussian(), data, weights, subset,
na.action, start = NULL, etastart, mustart, offset, control = list(...),
model = TRUE, method = "glm.fit.cons", cons = -1, cons.inter = 1, x = FALSE, y = TRUE, contrasts = NULL,
...)
{
call <- match.call()
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family))
family <- family()
if (is.null(family$family)) {
print(family)
stop("'family' not recognized")
}
if (missing(data))
data <- environment(formula)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action",
"etastart", "mustart", "offset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
if (identical(method, "model.frame"))
return(mf)
if (!is.character(method) && !is.function(method))
stop("invalid 'method' argument")
if (identical(method, "glm.fit.cons"))
control <- do.call("glm.control", control)
mt <- attr(mf, "terms")
Y <- stats::model.response(mf, "any")
if (length(dim(Y)) == 1L) {
nm <- rownames(Y)
dim(Y) <- NULL
if (!is.null(nm))
names(Y) <- nm
}
X <- if (!stats::is.empty.model(mt))
stats::model.matrix(mt, mf, contrasts)
else matrix(, NROW(Y), 0L)
weights <- as.vector(stats::model.weights(mf))
if (!is.null(weights) && !is.numeric(weights))
stop("'weights' must be a numeric vector")
if (!is.null(weights) && any(weights < 0))
stop("negative weights not allowed")
offset <- as.vector(stats::model.offset(mf))
if (!is.null(offset)) {
if (length(offset) != NROW(Y))
stop(gettextf("number of offsets is %d should equal %d (number of observations)",
length(offset), NROW(Y)), domain = NA)
}
mustart <- stats::model.extract(mf, "mustart")
etastart <- stats::model.extract(mf, "etastart")
fit <- eval(call(if (is.function(method)) "method" else method,
x = X, y = Y, weights = weights, cons = cons, cons.inter = cons.inter, start = start, etastart = etastart,
mustart = mustart, offset = offset, family = family,
control = control, intercept = attr(mt, "intercept") >
0L))
if (length(offset) && attr(mt, "intercept") > 0L) {
fit2 <- eval(call(if (is.function(method)) "method" else method,
x = X[, "(Intercept)", drop = FALSE], y = Y, weights = weights, , cons = cons, cons.inter = cons.inter,
offset = offset, family = family, control = control,
intercept = TRUE))
if (!fit2$converged)
warning("fitting to calculate the null deviance did not converge -- increase maxit?")
fit$null.deviance <- fit2$deviance
}
if (model)
fit$model <- mf
fit$na.action <- attr(mf, "na.action")
if (x)
fit$x <- X
if (!y)
fit$y <- NULL
fit <- c(fit, list(call = call, formula = formula, terms = mt,
data = data, offset = offset, control = control, method = method, cons = cons, cons.inter = cons.inter,
contrasts = attr(X, "contrasts"), xlevels = stats::.getXlevels(mt,
mf)))
class(fit) <- c(fit$class, c("glm", "lm"))
fit
}
#' Generalized Linear Models fitting method with negative coefficients constraint
#'
#' \code{glm.fit.cons} is an adaptation of function \code{glm.fit2} from package \{glm2\} in which the least squares estimation is replaced by a non-positive regression using function \code{nnnpls} from package \{nnls\}.
#' @param x as for \code{\link{glm.fit}}
#' @param y as for \code{\link{glm.fit}}
#' @param weights as for \code{\link{glm.fit}}
#' @param cons type of constraint. Default is -1 for negative coefficients on the predictors. The other option is 1 for positive coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param start as for \code{\link{glm.fit}}
#' @param etastart as for \code{\link{glm.fit}}
#' @param mustart as for \code{\link{glm.fit}}
#' @param offset as for \code{\link{glm.fit}}
#' @param family as for \code{\link{glm.fit}}
#' @param control as for \code{\link{glm.fit}}
#' @param intercept as for \code{\link{glm.fit}}
#' @return The value returned by \code{glm.fit.cons} has exactly the same structure as the value returned by \code{glm.fit} and \code{glm.fit2}.
#' @references Marschner, I.C. (2011) glm2: Fitting generalized linear models with convergence problems. \emph{The R Journal}, 3(2), 12-15.
#' @seealso \code{\link{glm.fit}}, \code{\link{glm.fit2}}
#' @examples
#' ## Dobson (1990) Page 93: Randomized Controlled Trial :
#' counts <- c(18,17,15,20,10,20,25,13,12)
#' outcome <- gl(3,1,9)
#' treatment <- gl(3,3)
#' print(d.AD <- data.frame(treatment, outcome, counts))
#' glm.D93 <- glm.cons(counts ~ outcome + treatment, family = poisson())
#' glm.D93.ngl <- glm.cons(counts ~ outcome + treatment, family = poisson(),
#' method="glm.fit.cons")
#' summary(glm.D93)
#' summary(glm.D93.ngl)
#' @export
glm.fit.cons <- function (x, y, weights = rep(1, nobs), cons = -1, cons.inter = 1, start = NULL, etastart = NULL,
mustart = NULL, offset = rep(0, nobs), family = stats::gaussian(),
control = list(), intercept = TRUE)
{
control <- do.call("glm.control", control)
x <- as.matrix(x)
xnames <- dimnames(x)[[2L]]
ynames <- if (is.matrix(y)) rownames(y) else names(y)
conv <- FALSE
nobs <- NROW(y)
nvars <- ncol(x)
EMPTY <- nvars == 0
if (is.null(weights))
weights <- rep.int(1, nobs)
if (is.null(offset))
offset <- rep.int(0, nobs)
variance <- family$variance
linkinv <- family$linkinv
if (!is.function(variance) || !is.function(linkinv))
stop("'family' argument seems not to be a valid family object",
call. = FALSE)
dev.resids <- family$dev.resids
aic <- family$aic
mu.eta <- family$mu.eta
unless.null <- function(x, if.null) if (is.null(x)) if.null else x
valideta <- unless.null(family$valideta, function(eta) TRUE)
validmu <- unless.null(family$validmu, function(mu) TRUE)
if (is.null(mustart)) {
eval(family$initialize)
}
else {
mukeep <- mustart
eval(family$initialize)
mustart <- mukeep
}
if (EMPTY) {
eta <- rep.int(0, nobs) + offset
if (!valideta(eta))
stop("invalid linear predictor values in empty model",
call. = FALSE)
mu <- linkinv(eta)
if (!validmu(mu))
stop("invalid fitted means in empty model", call. = FALSE)
dev <- sum(dev.resids(y, mu, weights))
w <- ((weights * mu.eta(eta)^2)/variance(mu))^0.5
residuals <- (y - mu)/mu.eta(eta)
good <- rep(TRUE, length(residuals))
boundary <- conv <- TRUE
coef <- numeric()
iter <- 0L
}
else {
coefold <- NULL
eta <- if (!is.null(etastart))
etastart
else if (!is.null(start))
if (length(start) != nvars)
stop(gettextf("length of 'start' should equal %d and correspond to initial coefs for %s",
nvars, paste(deparse(xnames), collapse = ", ")),
domain = NA)
else {
coefold <- start
offset + as.vector(if (NCOL(x) == 1L) x*start else x%*%start)
}
else family$linkfun(mustart)
mu <- linkinv(eta)
if (!(validmu(mu) && valideta(eta)))
stop("cannot find valid starting values: please specify some",
call. = FALSE)
devold <- sum(dev.resids(y, mu, weights))
boundary <- conv <- FALSE
for (iter in 1L:control$maxit) {
good <- weights > 0
varmu <- variance(mu)[good]
if (any(is.na(varmu)))
stop("NAs in V(mu)")
if (any(varmu == 0))
stop("0s in V(mu)")
mu.eta.val <- mu.eta(eta)
if (any(is.na(mu.eta.val[good])))
stop("NAs in d(mu)/d(eta)")
good <- (weights > 0) & (mu.eta.val != 0)
if (all(!good)) {
conv <- FALSE
warning("no observations informative at iteration ",
iter)
break
}
z <- (eta - offset)[good] + (y - mu)[good]/mu.eta.val[good]
w <- sqrt((weights[good] * mu.eta.val[good]^2)/variance(mu)[good])
ngoodobs <- as.integer(nobs - sum(!good))
fit.lm <- stats::lm.fit(x=x[good, , drop = FALSE]*w, y=z*w, singular.ok=FALSE, tol=min(1e-07, control$epsilon/1000))
A <- x[good, , drop = FALSE]*w
b <- z*w
fit <- nnls::nnnpls(A = A, b = b,con=c(cons.inter,rep(cons,ncol(A)-1)))
if (any(!is.finite(fit$x))) {
conv <- FALSE
warning(gettextf("non-finite coefficients at iteration %d",
iter), domain = NA)
break
}
if (nobs < fit.lm$rank)
stop(gettextf("X matrix has rank %d, but only %d observations",
fit.lm$rank, nobs), domain = NA)
start[fit.lm$qr$pivot] <- fit$x
eta <- drop(x %*% start)
mu <- linkinv(eta <- eta + offset)
dev <- sum(dev.resids(y, mu, weights))
if (control$trace)
cat("Deviance =", dev, "Iterations -", iter,
"\n")
boundary <- FALSE
if (!is.finite(dev)) {
if (is.null(coefold))
stop("no valid set of coefficients has been found: please supply starting values",
call. = FALSE)
warning("step size truncated due to divergence",
call. = FALSE)
ii <- 1
while (!is.finite(dev)) {
if (ii > control$maxit)
stop("inner loop 1; cannot correct step size",
call. = FALSE)
ii <- ii + 1
start <- (start + coefold)/2
eta <- drop(x %*% start)
mu <- linkinv(eta <- eta + offset)
dev <- sum(dev.resids(y, mu, weights))
}
boundary <- TRUE
if (control$trace)
cat("Step halved: new deviance =", dev, "\n")
}
if (!(valideta(eta) && validmu(mu))) {
if (is.null(coefold))
stop("no valid set of coefficients has been found: please supply starting values",
call. = FALSE)
warning("step size truncated: out of bounds",
call. = FALSE)
ii <- 1
while (!(valideta(eta) && validmu(mu))) {
if (ii > control$maxit)
stop("inner loop 2; cannot correct step size",
call. = FALSE)
ii <- ii + 1
start <- (start + coefold)/2
eta <- drop(x %*% start)
mu <- linkinv(eta <- eta + offset)
}
boundary <- TRUE
dev <- sum(dev.resids(y, mu, weights))
if (control$trace)
cat("Step halved: new deviance =", dev, "\n")
}
if (((dev - devold)/(0.1 + abs(dev)) >= control$epsilon)&(iter>1)) {
if (is.null(coefold))
stop("no valid set of coefficients has been found: please supply starting values",
call. = FALSE)
warning("step size truncated due to increasing deviance", call. = FALSE)
ii <- 1
while ((dev - devold)/(0.1 + abs(dev)) > -control$epsilon) {
if (ii > control$maxit) break
ii <- ii + 1
start <- (start + coefold)/2
eta <- drop(x %*% start)
mu <- linkinv(eta <- eta + offset)
dev <- sum(dev.resids(y, mu, weights))
}
if (ii > control$maxit) warning("inner loop 3; cannot correct step size")
else if (control$trace) cat("Step halved: new deviance =", dev, "\n")
}
if (abs(dev - devold)/(0.1 + abs(dev)) < control$epsilon) {
conv <- TRUE
coef <- start
break
}
else {
devold <- dev
coef <- coefold <- start
}
}
if (!conv)
warning("glm.fit.cons: algorithm did not converge. Try increasing the maximum iterations", call. = FALSE)
if (boundary)
warning("glm.fit.cons: algorithm stopped at boundary value",
call. = FALSE)
eps <- 10 * .Machine$double.eps
if (family$family == "binomial") {
if (any(mu > 1 - eps) || any(mu < eps))
warning("glm.fit.cons: fitted probabilities numerically 0 or 1 occurred",
call. = FALSE)
}
if (family$family == "poisson") {
if (any(mu < eps))
warning("glm.fit.cons: fitted rates numerically 0 occurred",
call. = FALSE)
}
if (fit.lm$rank < nvars)
coef[fit.lm$qr$pivot][seq.int(fit.lm$rank + 1, nvars)] <- NA
xxnames <- xnames[fit.lm$qr$pivot]
residuals <- (y - mu)/mu.eta(eta)
fit.lm$qr$qr <- as.matrix(fit.lm$qr$qr)
nr <- min(sum(good), nvars)
if (nr < nvars) {
Rmat <- diag(nvars)
Rmat[1L:nr, 1L:nvars] <- fit.lm$qr$qr[1L:nr, 1L:nvars]
}
else Rmat <- fit.lm$qr$qr[1L:nvars, 1L:nvars]
Rmat <- as.matrix(Rmat)
Rmat[row(Rmat) > col(Rmat)] <- 0
names(coef) <- xnames
colnames(fit.lm$qr$qr) <- xxnames
dimnames(Rmat) <- list(xxnames, xxnames)
}
names(residuals) <- ynames
names(mu) <- ynames
names(eta) <- ynames
wt <- rep.int(0, nobs)
wt[good] <- w^2
names(wt) <- ynames
names(weights) <- ynames
names(y) <- ynames
if (!EMPTY) names(fit.lm$effects) <- c(xxnames[seq_len(fit.lm$rank)], rep.int("", sum(good) - fit.lm$rank))
wtdmu <- if (intercept) sum(weights * y)/sum(weights) else linkinv(offset)
nulldev <- sum(dev.resids(y, wtdmu, weights))
n.ok <- nobs - sum(weights == 0)
nulldf <- n.ok - as.integer(intercept)
rank <- if (EMPTY) 0 else fit.lm$rank
resdf <- n.ok - rank
aic.model <- aic(y, n.ok, mu, weights, dev) + 2 * rank
list(coefficients = coef, residuals = residuals, fitted.values = mu, effects = if (!EMPTY) fit.lm$effects, R = if (!EMPTY) Rmat, rank = rank, qr = if (!EMPTY) structure(fit.lm$qr[c("qr", "rank", "qraux", "pivot", "tol")], class = "qr"), family = family, linear.predictors = eta, deviance = dev, aic = aic.model, null.deviance = nulldev, iter = iter, weights = wt, prior.weights = weights, df.residual = resdf, df.null = nulldf, y = y, converged = conv, boundary = boundary)
}
#' Transform data using I-splines
#'
#' Evaluates the I-splines for all variables of a data frame, as performed in \code{Zeta.msgdm}.
#' @param dat A data frame whose columns are variables to be transformed using I-splines.
#' @param order.ispline Order of the I-spline.
#' @param kn.ispline Number of knots in the I-spline.
#' @param rescale Indicates how to rescale the values between 0 and 1. Default is 0, which divides the data by the maximum value. Any other value corresponds to setting the minimum value to 0.
#' @return \code{Ispline} returns a data frame with the same number of rows as dat and
#' @return \code{ncol(dat)} * \code{(order.ispline} + \code{kn.ispline)} columns.
#' @references Ramsay, J. O. (1988). Monotone regression splines in action. \emph{Statistical Science}, 425-441.
#' @references Ferrier, S., Manion, G., Elith, J., & Richardson, K. (2007). Using generalized dissimilarity modelling to analyse and predict patterns of beta diversity in regional biodiversity assessment. \emph{Diversity and Distributions}, 13(3), 252-264.
#' @seealso \code{\link{Zeta.msgdm}}
#' @examples
#' utils::data(bird.env.coarse)
#' data.env <- bird.env.coarse[,3:9]
#' data.env.splines <- Ispline(data.env)
#' @export
Ispline <- function(dat, order.ispline = 2, kn.ispline = 1, rescale = 0){
ts <- matrix(NA,ncol(dat),2*order.ispline+ kn.ispline)
for(i in 1:ncol(dat)){
if(rescale == 0){
dat[,i] <- dat[,i]/max(dat[,i])
}else{
dat[,i] <- (dat[,i]-min(dat[,i]))/(max(dat[,i])-min(dat[,i]))
}
ts[i,] <- c(rep(0,order.ispline),stats::quantile(dat[,i],probs=seq(1/(kn.ispline+1),1-1/(kn.ispline+1),1/(kn.ispline+1))),rep(1,order.ispline))
}
IE <- matrix(NA,nrow(dat),(ncol(dat)*(order.ispline+kn.ispline)))
k=order.ispline
for(j in 1:ncol(dat)){
for(i in 1:(order.ispline+kn.ispline)){
xx <- 0
for(x in dat[,j]){
xx <- xx+1
if(x==1){
IE[xx,(j-1)*(order.ispline+kn.ispline)+i] <- 1
}else{
IE[xx,(j-1)*(order.ispline+kn.ispline)+i] <- .Ii(i,k,x,ts[j,])
}
}
}
}
IE <- data.frame(IE)
for(i in 1:(ncol(IE)/(order.ispline+kn.ispline))){
for(j in 1:(order.ispline+kn.ispline)){
names(IE)[(i-1)*(order.ispline+kn.ispline)+j] <- paste(names(dat)[i],j,sep="")
}
}
out <- list()
out$splines <- IE
out$order.ispline = order.ispline
out$kn.ispline = kn.ispline
return(out)
}
#' Perform an I-spline regression
#'
#' Evaluates the I-splines for all variables of a data frame of predictor variables, and perform a generalised linear regression with constraint on the parameters.
#' @param response A vector of numeric values representing the response variable.
#' @param predictor A data frame of numeric variables representing the predictors.
#' @param order.ispline Order of the I-spline.
#' @param kn.ispline Number of knots in the I-spline.
#' @param family A description of the error distribution and link function to be used in the \code{glm} model (see \code{\link[stats]{family}} for details of family functions).
#' @param method.glm Method used in fitting the generalised linear model. The default method \cr "glm.fit.cons" is an adaptation of method \code{glm.fit2} from package \code{glm2} using a constrained least squares regression in the reweighted least squares. Another option is "glm.fit2", which calls \code{glm.fit2}; see help documentation for glm.fit2 in package \code{glm2}.
#' @param cons type of constraint in the glm if \code{method.glm = "glm.fit.cons"}. Default is 1 for positive coefficients on the predictors. The other option is -1 for negative coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param Plot Boolean value indicating if the I-splines must be plotted.
#' @param lty Line types to be used in the plotting. If nothing is provided, \code{lty} is a sequence of integers from 1 to the number of variables used for the computation of \code{msgdm}.
#' @param lwd Line width.
#' @param control As for \code{\link{glm}}.
#' @details \code{Reg.ispline} performs a non-linear regression using a combination of GLM and I-splines. It can, for example, be used to compare regression outputs when using MS-GDM with I-splines on environmental variables and biotic variables as in \code{Zetya.msgdm} to the same regression approach without environmental variables.
#' @return \code{Reg.ispline} returns a list of the following elements:
#' @return \item{splines}{A data frame in which each columns contains the value resulting from the transformation of the predictors into individual I-splines. The number of columns of \code{splines} is the number of predictors times the number of splines (determined as the sum of \code{order.ispline} and \code{kn.ispline}).}
#' @return \item{spline}{A data frame in which each columns contains the value resulting from the combinations of the individual I-splines. This combination is obtained by multiplying the coefficients of \code{model} and the values of the individual I-splines \code{splines}}.
#' @return \item{model}{A \code{\link{glm}} model using \code{response} as the response variable, and \code{splines} as the predictors}.
#' @references Ramsay, J. O. (1988). Monotone regression splines in action. \emph{Statistical Science}, 425-441.
#' @seealso \code{\link{Zeta.msgdm}},\code{\link{Ispline}}
#' @examples
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#'
#' data.spec.marion <- Marion.species[3:33]
#'
#' ##random other communities
#' data.spec.marion2a <- data.spec.marion
#' data.spec.marion2a[which(data.spec.marion2a==1,arr.ind=TRUE)] <- 0
#' for(i in 1:ncol(data.spec.marion2a))
#' data.spec.marion2a[sample(nrow(data.spec.marion2a),8),i] <- 1
#' data.spec.marion2b <- data.spec.marion
#' data.spec.marion2b[which(data.spec.marion2b==1,arr.ind=TRUE)] <- 0
#' for(i in 1:ncol(data.spec.marion2b))
#' data.spec.marion2b[sample(nrow(data.spec.marion2b),8),i] <- 1
#'
#' dat.spec.tot <- list(data.spec.marion,data.spec.marion2a,data.spec.marion2b)
#' zeta.tot <- Zeta.order.mc.mult(data.spec=dat.spec.tot,order=3,sam=200)
#' zeta.splines <- Ispline(zeta.tot$zeta.val[,2:3])
#' data.tot <- data.frame(zeta.val=zeta.tot$zeta.val[,1],zeta.splines$splines)
#'
#' dev.new()
#' Reg.ispline(response = zeta.tot$zeta.val[,1], predictor = zeta.tot$zeta.val[,2:3], lwd=2, cons=1)
#' @export
Reg.ispline <- function(response, predictor, order.ispline = 2, kn.ispline = 1, family = stats::gaussian(), method.glm = "glm.fit.cons", cons = 1, cons.inter = 1, control = list(), Plot = TRUE, lty = NULL, lwd = 1){
if(is.null(lty)){
lty=1:ncol(predictor)
}
n.splines <- order.ispline+kn.ispline
predictor.spline <- Ispline(predictor,order.ispline = order.ispline, kn.ispline = kn.ispline)
data.tot <- data.frame(response=response,predictor=predictor.spline)
reg.model <- glm.cons(response ~ ., data = predictor.spline$splines, family = family, method = method.glm, cons = cons, cons.inter = cons.inter, control = control)
splines <- matrix(NA,nrow(predictor),ncol(predictor))
for(i in 1:ncol(predictor)){
splines[,i] <- rowSums(matrix(reg.model$coefficients[(2+(i-1)*n.splines):(i*n.splines+1)],nrow(predictor.spline$splines),3,byrow = TRUE)*predictor.spline$splines[,(1+(i-1)*n.splines):(i*n.splines)])
}
if(Plot==TRUE){
graphics::plot(sort(predictor[,1]),splines[order(predictor[,1]),1],type="l",xlim=range(predictor),ylim=range(splines),lwd=lwd,lty=lty[1])
if(ncol(predictor)>1){
for(i in 2:ncol(predictor)){
graphics::lines(sort(predictor[,i]),splines[order(predictor[,i]),2],lwd=lwd,lty=lty[i])
}
}
graphics::legend(x="topleft",legend = names(predictor),lwd=lwd,lty=lty,bty="n")
}
out.list <- list()
out.list$splines <- predictor.spline
out.list$spline.tot <- splines
out.list$model <- reg.model
return(out.list)
}
#' Predict zeta values for new environmental and distance data
#'
#' Predict the zeta values for new environmental and distance data from the models returned by \code{Zeta.msgdm}.
#' @param model.msgdm A model returned by \code{Zeta.msgdm}. The class of the model depends on the type of regression used in \code{Zeta.msgdm}.
#' @param reg.type Type of regression used in \code{Zeta.msgdm}. Options are "\code{glm}" for generalised linear models, "\code{ngls}" for negative linear models, "\code{gam}" for generalised additive models, "\code{scam}" for shape constrained additive models (with monotonic decreasing by default), and "\code{ispline}" for I-spline models (forcing monotonic decreasing), as recommended in generalised dissimilarity modelling by Ferrier \emph{et al}. (2007).
#' @param newdata A data frame with the new environmental and distance data. The names of the columns must be the same as the names used in the data frame used in \code{Zeta.msgdm}. For I-splines, the data frame must be generated beforehand from the original data by the function \code{\link{Ispline}}.
#' @param type The type of prediction required, as for \code{predict.glm}. The default is on the scale of the response variable; the alternative "link" is on the scale of the linear predictors.
#' @return \code{Predict.msgdm} returns a vector of predicted zeta values.
#' @references Ramsay, J. O. (1988). Monotone regression splines in action. \emph{Statistical Science}, 425-441.
#' @references Ferrier, S., Manion, G., Elith, J., & Richardson, K. (2007). Using generalized dissimilarity modelling to analyse and predict patterns of beta diversity in regional biodiversity assessment. \emph{Diversity and Distributions}, 13(3), 252-264.
#' @seealso \code{\link{Zeta.msgdm}}
#' @import scam
#' @examples
#' utils::data(bird.spec.fine)
#' xy.bird <- bird.spec.fine[1:500,1:2]
#' data.spec.bird <- bird.spec.fine[1:500,3:192]
#' utils::data(bird.env.fine)
#' data.env.bird <- bird.env.fine[1:500,3:9]
#'
#' zeta.glm <- Zeta.msgdm(data.spec.bird, data.env.bird, sam = 100, order = 3)
#' newdata <- data.frame(matrix(NA,100,ncol(data.env.bird)))
#' names(newdata) <- names(data.env.bird)
#' for(z in 1:100){
#' samp <- sample(1:104, 3, replace = FALSE)
#' newdata[z,] <- apply(apply(bird.env.fine[501:604,3:9][samp,], 2,
#' stats::dist), 2, mean)
#' }
#' ##rescale the data like during MS-GDM
#' newdata <- newdata/matrix(rep(zeta.glm$rescale.factor,100),
#' 100,length(zeta.glm$rescale.factor),byrow=TRUE)
#' new.zeta.glm <- Predict.msgdm(model.msgdm = zeta.glm$model, reg.type = "glm",
#' newdata = newdata)
#'
#'
#'
#' zeta.ngls <- Zeta.msgdm(data.spec.bird, data.env.bird, sam = 100, order = 3,
#' reg.type = "ngls", normalize = "Jaccard")
#' newdata <- data.frame(matrix(NA,100,ncol(data.env.bird)))
#' names(newdata) <- names(data.env.bird)
#' for(z in 1:100){
#' samp <- sample(1:104, 3, replace = FALSE)
#' newdata[z,] <- apply(apply(bird.env.fine[501:604,3:9][samp,], 2, stats::dist),
#' 2, mean)
#' }
#' ##rescale the data like during MS-GDM
#' newdata <- newdata/matrix(rep(zeta.ngls$rescale.factor,100),
#' 100,length(zeta.ngls$rescale.factor),byrow=TRUE)
#' new.zeta.ngls <- Predict.msgdm(model.msgdm = zeta.ngls$model, reg.type = "ngls",
#' newdata = newdata)
#' @export
Predict.msgdm <- function(model.msgdm, reg.type, newdata, type = "response"){
if(reg.type=="glm" || reg.type=="ispline"){
new.zeta <- stats::predict.glm(object = model.msgdm, newdata = newdata, type = type)
}else if(reg.type=="ngls"){
coefs <- stats::coef(model.msgdm)
newdata <- cbind(rep(1,nrow(newdata)), newdata)
new.zeta <- c(coefs%*%t(as.matrix(newdata)))
}else if(reg.type=="gam"){
new.zeta <- mgcv::predict.gam(object = model.msgdm, newdata = newdata, type = type)
}else if(reg.type=="scam"){
new.zeta <- scam::predict.scam(object = model.msgdm, newdata = newdata, type = type)
}else{
stop("Error: unknown regression type.")
}
return(new.zeta)
}
#' Computing splines coordinates from I-spline-based multi-site generalised dissimilarity modelling
#'
#' Stores the coordinates of the I-splines resulting from \code{Zeta.msgdm} for plotting.
#' @param msgdm Output of function \code{Zeta.msgdm} computed with \code{reg.type = ispline}.
#' @param data.env Site-by-variable data frame used for the computation of \code{msgdm}, with sites as rows and environmental variables as columns.
#' @param distance Boolean, indicates is distance was used in the computation of \code{msgdm}.
#' @param biotic Integer, indicates the number of other groups of taxa for which zeta diversity was computed and used in the computation of \code{msgdm}.
#' @details \code{Return.ispline} allows to store the same number of coordinates for all I-splines, to average replicates and obtain confidence intervals.
#' @return \code{Return.ispline} returns a list containing the following components used to plot the I-splines:
#' @return \item{env}{A data frame containing the rescaled environmental (numeric and factor), distance and biotic x-values.}
#' @return \item{Ispline}{A data frame containing the I-spline values corresponding to the rescaled environmental (numeric and factor), distance and biotic x-values.}
#' @seealso \code{\link{Zeta.msgdm}}, \code{\link{Ispline}}
#' @examples
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#' data.spec.marion <- Marion.species[3:33]
#'
#' utils::data(Marion.env)
#' data.env.marion <- Marion.env[3]
#'
#' zeta.ispline <- Zeta.msgdm(data.spec.marion, data.env.marion, xy.marion, sam = 100,
#' order = 3, normalize = "Jaccard", reg.type = "ispline")
#' zeta.ispline
#' zeta.ispline.r <- Return.ispline(zeta.ispline, data.env.marion, distance = TRUE)
#' zeta.ispline.r
#'
#' dev.new()
#' Plot.ispline(isplines = zeta.ispline.r, distance = TRUE)
#'
#' dev.new()
#' Plot.ispline(msgdm = zeta.ispline, data.env = data.env.marion, distance = TRUE)
#'
#' @export
#'
Return.ispline <- function (msgdm, data.env, distance = FALSE, biotic = 0){
##for retro-compatibility
if(biotic==FALSE)
biotic <- 0
if(biotic==TRUE)
biotic <- 1
##
my.order <- msgdm$my.order
order.ispline = msgdm$order.ispline
kn.ispline = msgdm$kn.ispline
num.splines <- order.ispline+kn.ispline
data.env.num <- as.data.frame(data.env[,which(sapply(data.env, inherits, "numeric"))])
names(data.env.num) <- names(data.env)[which(sapply(data.env, inherits, "numeric"))]
Fa <- as.data.frame(data.env[,which(sapply(data.env, inherits, "factor"))])
names(Fa) <- names(data.env)[which(sapply(data.env, inherits, "factor"))]
if(distance == FALSE & biotic == 0){
XX <- as.data.frame(matrix(rep(seq(0,1,0.01),ncol(data.env)),101,ncol(data.env)))
names(XX) <- names(data.env)
}else if(distance == TRUE & biotic == 0){
XX <- as.data.frame(matrix(rep(seq(0,1,0.01),ncol(data.env)+1),101,ncol(data.env)+1))
names(XX) <- c(names(data.env),"Distance")
}else if(distance == FALSE & biotic > 0){
XX <- as.data.frame(matrix(rep(seq(0,1,0.01),ncol(data.env)+biotic),101,ncol(data.env)+biotic))
names(XX) <- c(names(data.env),paste("Biotic",1:biotic,sep=""))
}else{
XX <- as.data.frame(matrix(rep(seq(0,1,0.01),ncol(data.env)+biotic+1),101,ncol(data.env)+biotic+1))
names(XX) <- c(names(data.env),paste("Biotic",1:biotic,sep=""),"Distance")
}
env.ispline <- Ispline(data.env.num,rescale=1, order.ispline = order.ispline, kn.ispline = kn.ispline)$splines
subsamp <- 0
if(length(msgdm$val) < nrow(data.env)){
ind.sel <- sample(nrow(data.env),length(msgdm$val))
env.ispline <- env.ispline[ind.sel,]
data.env <- data.env[ind.sel,]
subsamp <- 1
}
if(distance == TRUE){
d.ind <- c(sample(1:length(msgdm$val),min(nrow(data.env)-2,length(msgdm$val)-2)),which.max(msgdm$distance),which.min(msgdm$distance))
d <- msgdm$distance[d.ind]
d.spline <- msgdm$predictors[d.ind,(ncol(msgdm$predictors)-(num.splines-1)):ncol(msgdm$predictors)]
if(biotic >0){
for(b in 1:biotic){
bio.ind <- c(sample(1:length(msgdm$val),min(nrow(data.env)-2,length(msgdm$val)-2)),which.max(msgdm$biotic[,b]),which.min(msgdm$biotic[,b]))
if(b==1){
bio <- msgdm$biotic[bio.ind,b]
bio <- matrix(bio,length(bio),1)
bio.spline <- msgdm$predictors[bio.ind,(ncol(msgdm$predictors)-((biotic-(b-2))*3-1)):(ncol(msgdm$predictors)-((biotic-(b-1))*3))]
}else{
bio <- cbind(bio,msgdm$biotic[bio.ind,b])
bio.spline <- cbind(bio.spline,msgdm$predictors[bio.ind,(ncol(msgdm$predictors)-((biotic-(b-2))*3-1)):(ncol(msgdm$predictors)-((biotic-(b-1))*3))])
}
}
if(length(which(sapply(data.env, inherits, "factor")))==0){
X.ispline <- cbind(env.ispline,bio.spline,d.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+biotic+1,nrow(data.env))
for(i in 1:(ncol(data.env)+biotic+1)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
}else{
X.ispline <- cbind(env.ispline,matrix(rep(1,ncol(Fa)*nrow(env.ispline)),nrow(env.ispline),ncol(Fa)),bio.spline,d.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+biotic+1,nrow(data.env))
for(i in 1:ncol(data.env.num)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
ii <- 0
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
ii <- ii+1
Isplines.pred[i,] <- -stats::coef(msgdm$model)[(1+ncol(data.env.num)*num.splines)+ii]* X.ispline[,ncol(data.env.num)*num.splines+ii]
}
for(b in 1:biotic){
Isplines.pred[ncol(data.env)+b,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(ncol(data.env.num)+b-1)*num.splines+ncol(Fa)):((ncol(data.env.num)+b)*num.splines+ncol(Fa)+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(ncol(data.env.num)+b-1)*num.splines+ncol(Fa)):((ncol(data.env.num)+b)*num.splines+ncol(Fa))])
}
Isplines.pred[ncol(data.env)+biotic+1,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(ncol(data.env.num)+biotic-1)*num.splines+ncol(Fa)+num.splines):((ncol(data.env.num)+biotic)*num.splines+ncol(Fa)+1+num.splines)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(ncol(data.env.num)+biotic-1)*num.splines+ncol(Fa)+num.splines):((ncol(data.env.num)+biotic)*num.splines+ncol(Fa)+num.splines)])
}
}else{
if(length(which(sapply(data.env, inherits, "factor")))==0){
X.ispline <- cbind(env.ispline,d.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+1,min(nrow(data.env),length(msgdm$val)))
for(i in 1:(ncol(data.env.num)+1)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],min(nrow(data.env),length(msgdm$val)),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
}else{
X.ispline <- cbind(env.ispline,matrix(rep(1,ncol(Fa)*nrow(env.ispline)),nrow(env.ispline),ncol(Fa)),d.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+1,nrow(data.env))
for(i in 1:(ncol(data.env.num)+1)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
ii <- 0
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
ii <- ii+1
Isplines.pred[i,] <- -stats::coef(msgdm$model)[(1+ncol(data.env.num)*num.splines)+ii]* X.ispline[,ncol(data.env.num)*num.splines+ii]
}
Isplines.pred[ncol(data.env)+1,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(ncol(data.env.num))*num.splines+ncol(Fa)):((ncol(data.env.num)+1)*num.splines+ncol(Fa)+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+ncol(data.env.num)*num.splines+ncol(Fa)):((ncol(data.env.num)+1)*num.splines+ncol(Fa))])
}
}
}else{
if(biotic > 0){
for(b in 1:biotic){
bio.ind <- c(sample(1:length(msgdm$val),min(nrow(data.env)-2,length(msgdm$val)-2)),which.max(msgdm$biotic[,b]),which.min(msgdm$biotic[,b]))
if(b==1){
bio <- msgdm$biotic[bio.ind,b]
bio <- matrix(bio,length(bio),1)
bio.spline <- msgdm$predictors[bio.ind,(ncol(msgdm$predictors)-((biotic-(b-1))*3-1)):(ncol(msgdm$predictors)-((biotic-(b))*3))]
}else{
bio <- cbind(bio,msgdm$biotic[bio.ind,b])
bio.spline <- cbind(bio.spline,msgdm$predictors[bio.ind,(ncol(msgdm$predictors)-((biotic-(b-1))*3-1)):(ncol(msgdm$predictors)-((biotic-(b))*3))])
}
}
if(length(which(sapply(data.env, inherits, "factor")))==0){
X.ispline <- cbind(env.ispline,bio.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+biotic,nrow(data.env))
for(i in 1:(ncol(data.env)+biotic)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
}else{
X.ispline <- cbind(env.ispline,matrix(rep(1,ncol(Fa)*nrow(env.ispline)),nrow(env.ispline),ncol(Fa)),bio.spline)
Isplines.pred <- matrix(NA,ncol(data.env)+biotic,nrow(data.env))
for(i in 1:ncol(data.env.num)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
ii <- 0
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
ii <- ii+1
Isplines.pred[i,] <- -stats::coef(msgdm$model)[(1+ncol(data.env.num)*num.splines)+ii]* X.ispline[,ncol(data.env.num)*num.splines+ii]
}
for(b in 1:biotic){
Isplines.pred[ncol(data.env)+b,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(ncol(data.env.num)+b-1)*num.splines+ncol(Fa)):((ncol(data.env.num)+b)*num.splines+ncol(Fa)+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(ncol(data.env.num)+b-1)*num.splines+ncol(Fa)):((ncol(data.env.num)+b)*num.splines+ncol(Fa))])
}
}
}else{
if(length(which(sapply(data.env, inherits, "factor")))==0){
X.ispline <- env.ispline
}else{
X.ispline <- cbind(env.ispline,matrix(rep(1,ncol(Fa)*nrow(env.ispline)),nrow(env.ispline),ncol(Fa)))
}
Isplines.pred <- matrix(NA,ncol(data.env),nrow(data.env))
for(i in 1:ncol(data.env.num)){
Isplines.pred[i,] <- rowSums(matrix(-stats::coef(msgdm$model)[(2+(i-1)*num.splines):(i*num.splines+1)],nrow(data.env),num.splines,byrow=TRUE)* X.ispline[,(1+(i-1)*num.splines):(i*num.splines)])
}
if(length(which(sapply(data.env, inherits, "factor")))>0){
ii <- 0
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
ii <- ii+1
Isplines.pred[i,] <- -stats::coef(msgdm$model)[(1+ncol(data.env.num)*num.splines)+ii]* X.ispline[,ncol(data.env.num)*num.splines+ii]
}
}
}
}
if(subsamp == 1){
env.resc <- data.env.num[ind.sel,]
}else{
env.resc <- data.env.num
}
for(i in 1:ncol(env.resc)){
env.resc[,i] <- (env.resc[i]-min(env.resc[i]))/(max(env.resc[i])-min(env.resc[i]))
}
##create output list
splines.out <- list()
env.resc.out <- env.resc
Isplines.pred.out <- Isplines.pred
for(i in 1:ncol(data.env.num)){
env.resc.out[,i] <- sort(env.resc[,i])
Isplines.pred.out[i,] <- Isplines.pred[i,order(env.resc[,i])]
}
splines.out$env <- data.frame(env.resc.out)
if(ncol(Fa)>0){
Fa.out <- matrix(0,ncol(Fa),ncol(Isplines.pred))
ii <- 0
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
ii <- ii+1
Fa.out[ii,] <- seq(0,1,1/(ncol(Isplines.pred)-1))
Isplines.pred.out[i,] <- seq(0,max(Isplines.pred[i,]),max(Isplines.pred[i,])/(ncol(Isplines.pred)-1))
}
splines.out$env <- cbind(splines.out$env,data.frame(t(Fa.out)))
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
names(splines.out$env)[i] <- paste("Fa",i-ncol(data.env.num),sep="")
}
}
if(biotic > 0){
for(b in 1:biotic){
i <- i+1
bio.out <- sort(bio[,b])
Isplines.pred.out[i,] <- Isplines.pred[i,order(bio[,b])]
splines.out$env <- cbind(splines.out$env,bio.out)
names(splines.out$env)[i] <- paste("biotic",b,sep="")
}
}
if(distance == TRUE){
i <- i+1
d.out <- sort(d/max(d))
Isplines.pred.out[i,] <- Isplines.pred[i,order(d)]
splines.out$env <- cbind(splines.out$env,d.out)
names(splines.out$env)[i] <- "distance"
}
splines.out$Ispline <- data.frame(t(Isplines.pred.out))
names(splines.out$Ispline) <- names(splines.out$env)
splines.out$env.num <- data.env.num
splines.out$Fa <- Fa
splines.out$distance <- distance
splines.out$biotic <- biotic
splines.out$my.order <- my.order
# if(distance == TRUE)
return(splines.out)
}
#' Plots I-splines for Multi-Site Generalised Dissimilarity Modelling
#'
#'Plots I-splines computed by \code{Return.ispline}, or calls \code{Return.ispline} if the outputs from \code{Zeta.msgdm} are provided before plotting.
#' @param isplines Output of function \code{Return.ispline}.
#' @param msgdm Output of function \code{Zeta.msgdm} computed with \code{reg.type = ispline}.
#' @param data.env Site-by-variable data frame used for the computation of \code{msgdm}, with sites as rows and environmental variables as columns.
#' @param distance Boolean, indicates is distance was used in the computation of \code{msgdm}.
#' @param biotic Boolean, indicates is zeta diversity from another community was used in the computation of \code{msgdm}.
#' @param pch Shapes of the points to be used in the plotting. If nothing is provided, \code{pch} is a sequence of integers from 1 to the number of variables used for the computation of \code{msgdm}.
#' @param lty Line types to be used in the plotting. If nothing is provided, \code{lty} is a sequence of integers from 1 to the number of variables used for the computation of \code{msgdm}.
#' @param legend Boolean, indicates if the legend must be drawn.
#' @param lwd Line width.
#' @param cex Point size.
#' @param num.quantiles Number of points to plot on the I-splines. Default is 11 to plot a point every 10 percents of the range of values.
#' @return \code{Plot.ispline} returns a data frame with the same number of rows as dat and \code{ncol(dat)} * \code{(order.ispline} + \code{kn.ispline)} columns.
#' @references Ramsay, J. O. (1988). Monotone regression splines in action. \emph{Statistical Science}, 425-441.
#' @references Ferrier, S., Manion, G., Elith, J., & Richardson, K. (2007). Using generalized dissimilarity modelling to analyse and predict patterns of beta diversity in regional biodiversity assessment. \emph{Diversity and Distributions}, 13(3), 252-264.
#' @seealso \code{\link{Zeta.msgdm}}
#' @examples
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[1:2]
#' data.spec.marion <- Marion.species[3:33]
#'
#' utils::data(Marion.env)
#' data.env.marion <- Marion.env[3]
#'
#' zeta.ispline <- Zeta.msgdm(data.spec.marion, data.env.marion, xy.marion, sam = 100,
#' order = 3, normalize = "Jaccard", reg.type = "ispline")
#' zeta.ispline
#' zeta.ispline.r <- Return.ispline(zeta.ispline, data.env.marion, distance = TRUE)
#' zeta.ispline.r
#'
#' dev.new()
#' Plot.ispline(isplines = zeta.ispline.r, distance = TRUE)
#'
#' dev.new()
#' Plot.ispline(msgdm = zeta.ispline, data.env = data.env.marion, distance = TRUE)
#'
#'
#' @export
#'
Plot.ispline <- function (isplines = NULL,msgdm, data.env, distance = FALSE, biotic = 0, pch = NULL, lty = NULL, legend = TRUE, lwd = 1, cex = 1, num.quantiles = 11){
if(is.null(isplines)){
isplines <- Return.ispline(msgdm=msgdm, data.env=data.env, distance = distance, biotic = biotic)
}
env.resc <- isplines$env
Isplines.pred <- isplines$Ispline
data.env.num <- isplines$env.num
Fa <- isplines$Fa
distance <- isplines$distance
biotic <- isplines$biotic
my.order <- isplines$my.order
if(is.null(pch)){
pch <- 1:ncol(env.resc)
}
if(is.null(lty)){
lty <- 1:ncol(env.resc)
}
graphics::plot(sort(env.resc[,1]),Isplines.pred[order(env.resc[,1]),1], type="l",ylim=c(0,max(Isplines.pred)),main="",xlab="Rescaled range",ylab="I-splines",cex.lab=1.5,cex.main=1.5,cex.axis=1.5,cex=cex,lwd=lwd)
ind.points <- numeric()
for(i in 1:num.quantiles){
ind.points[i] <- which.min(abs(stats::quantile(env.resc[,1],seq(0,1,1/(num.quantiles-1)))[i]-sort(env.resc[,1])))
}
graphics::points(sort(env.resc[,1])[ind.points],Isplines.pred[order(env.resc[,1]),1][ind.points],pch=pch[1],cex=cex,lwd=lwd)
if(ncol(data.env.num) > 1){
for(i in 2:ncol(data.env.num)){
graphics::lines(sort(env.resc[,i]),Isplines.pred[order(env.resc[,i]),i],lty=lty[i],lwd=lwd)
ind.points <- numeric()
for(j in 1:num.quantiles){
ind.points[j] <- which.min(abs(stats::quantile(env.resc[,i],seq(0,1,1/(num.quantiles-1)))[j]-sort(env.resc[,i])))
}
graphics::points(sort(env.resc[,i])[ind.points],Isplines.pred[order(env.resc[,i]),i][ind.points],pch=pch[i],cex=cex,lwd=lwd)
}
}
i <- ncol(data.env.num)
if(!is.null(Fa)){
if(ncol(Fa)>0){
for(i in (ncol(data.env.num)+1):(ncol(data.env.num)+ncol(Fa))){
if(max(Isplines.pred[,i])>0){
graphics::lines(seq(0,1,1/nrow(Isplines.pred)),seq(0,max(Isplines.pred[,i]),max(Isplines.pred[,i])/nrow(Isplines.pred)),lty=lty[i],col="red",lwd=lwd)
graphics::points (seq(0,1,1/(my.order-1)),seq(0,max(Isplines.pred[,i]),max(Isplines.pred[,i])/(my.order-1)),pch=pch[i],col="red",lwd=lwd,cex=cex)
}else{
graphics::lines(c(0,1),c(0,0),lty=lty[i],col="red",lwd=lwd)
graphics::points (seq(0,1,1/(my.order-1)),rep(0,my.order),pch=pch[i],col="red",lwd=lwd,cex=cex)
}
}
}
}
if(biotic >0){
for(b in 1:biotic){
i <- i+1
graphics::lines(env.resc[,i],Isplines.pred[,i],lty=lty[i],lwd=lwd,col="green")
ind.points <- numeric()
for(j in 1:num.quantiles){
ind.points[j] <- which.min(abs(stats::quantile(env.resc[,i],seq(0,1,1/(num.quantiles-1)))[j]-env.resc[,i]))
}
graphics::points(env.resc[ind.points,i],Isplines.pred[ind.points,i],pch=pch[i],cex=cex,lwd=lwd,col="green")
}
}
if(distance == TRUE){
i <- i+1
graphics::lines(env.resc$distance,Isplines.pred$distance,lty=lty[i],lwd=lwd,col="blue")
ind.points <- numeric()
for(j in 1:num.quantiles){
ind.points[j] <- which.min(abs(stats::quantile(env.resc$distance,seq(0,1,1/(num.quantiles-1)))[j]-env.resc$distance))
}
graphics::points(env.resc$distance[ind.points],Isplines.pred$distance[ind.points],pch=pch[i],cex=cex,lwd=lwd,col="blue")
}
if(is.null(Fa) | length(Fa)==0) {
if(distance == FALSE & biotic == 0){
legend.text <- c(names(data.env.num))
col="black"
}else if(distance == TRUE & biotic == 0){
legend.text <- c(names(data.env.num),"Distance")
col=c(rep("black",ncol(data.env.num)),"blue")
}else if(distance == FALSE & biotic > 0){
legend.text <- c(names(data.env.num),paste("Biotic",1:biotic))
col=c(rep("black",ncol(data.env.num)),rep("green",biotic))
}else{
legend.text <- c(names(data.env.num),paste("Biotic",1:biotic),"Distance")
col=c(rep("black",ncol(data.env.num)),rep("green",biotic),"blue")
}
}else{
if(distance == FALSE & biotic == 0){
legend.text <- c(names(data.env.num),names(Fa))
col=c(rep("black",ncol(data.env.num)),rep("red",ncol(Fa)))
}else if(distance == TRUE & biotic == 0){
legend.text <- c(names(data.env.num),names(Fa),"Distance")
col=c(rep("black",ncol(data.env.num)),rep("red",ncol(Fa)),"blue")
}else if(distance == FALSE & biotic > 0){
legend.text <- c(names(data.env.num),names(Fa),paste("Biotic",1:biotic))
col=c(rep("black",ncol(data.env.num)),rep("red",ncol(Fa)),rep("green",biotic))
}else{
legend.text <- c(names(data.env.num),names(Fa),paste("Biotic",1:biotic),"Distance")
col=c(rep("black",ncol(data.env.num)),rep("red",ncol(Fa)),rep("green",biotic),"blue")
}
}
if(legend == TRUE){
#legend("topleft",lty=lty,pch=pch,names(XX),lwd=lwd,cex=cex,bty="n")
legend("topleft",lty=lty,pch=pch,legend=legend.text,lwd=lwd,cex=cex,bty="n",col=col)
}
##create output list
invisible(isplines)
}
#' Zeta distance decay for a specific number of assemblages or sites
#'
#' Computes the distance decay of zeta diversity for a specific order (number of assemblages or sites), using either a generalised linear model with possible constraint on the coefficients, a generalised additive model, or a shape constrained additive model.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param distance.type Method to compute distance. Default is "\code{Euclidean}", for Euclidean distance. The other options are (i) "\code{ortho}" for orthodromic distance, if xy correspond to longitudes and latitudes (orthodromic distance is computed using the \code{geodist} function from package \code{geodist}); and (ii) "\code{custom}", in which case the user must provide a distance matrix for \code{dist.custom}.
#' @param dist.custom Distance matrix provided by the user when \code{distance.type} = \code{"custom"}.
#' @param method Name of a function (as a string) indicating how to combine the pairwise differences and distances for more than 3 sites. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param method.glm Method used in fitting the generalised linear model. The default method \cr "glm.fit.cons" is an adaptation of method \code{glm.fit2} from package \code{glm2} using a negative least squares regression in the reweighted least squares. Another option is "glm.fit2", which calls \code{glm.fit2}.; see help documentation for \code{glm.fit2} in package \code{glm}.
#' @param cons type of constraint in the glm if \code{method.glm = "glm.fit.cons"}. Default is -1 for negative coefficients on the predictors. The other option is 1 for positive coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param reg.type Type of regression. Options are "\code{glm}" for generalised linear models "\code{gam}" for generalised additive models and "\code{scam}" for shape constrained additive models (with monotonic decreasing by default).
#' @param family A description of the error distribution and link function to be used in the \code{glm}, \code{gam} and \code{scam} models (see \code{\link[stats]{family}} for details of family functions).
#' @param confint.level Percentage for the confidence intervals of the coefficients from the generalised linear models.
#' @param kn Number of knots in the GAM and SCAM. Default is -1 for determining kn automatically using Generalized Cross-validation.
#' @param bs A two-letter character string indicating the (penalized) smoothing basis to use in the scam model. Default is "\code{mpd}" for monotonic decreasing splines. see \code{\link[mgcv]{smooth.terms}} for an overview of what is available.
#' @param trsf Name of a function (as a string) indicating how to transform distance.
#' @param cutoff If specified, maximum distance value for which the linear regression must be performed.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param empty.row Determines how to handle empty rows, i.e. sites with no species. Such sites can cause underestimations of zeta diversity, and computation errors for the normalized version of zeta due to divisions by 0. Options are "\code{empty}" to let the data untreated, "\code{remove}" to remove the empty rows, 0 to set the normalized zeta to 0 when zeta is divided by 0 during normalization (sites share no species, so are completely dissimilar), and 1 to set the normalized zeta to 1 when zeta is divided by 0 during normalization (i.e. sites are perfectly similar).
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @return \code{Zeta.ddecay} returns a list containing the following components:
#' @return \item{order}{The order of zeta for which the distance decay was computed.}
#' @return \item{reg.type}{A character string indicating the type of regression that was performed.}
#' @return \item{reg}{An object whose class depends on the type of regression (\code{glm}, \code{gam} or \code{scam}), corresponding to the regression over distance for the number of assemblages or sites specified in 'order'.}
#' @return \item{confint}{The confidence intervals for the coefficients from the generalised linear model. \code{confint} is not generated for generalised additive models and shape constrained additive models.}
#' @return \item{zeta.val}{The values of zeta for the sampled sites used in the regression.}
#' @return \item{distance}{The distances for the sampled sites used in the regression.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.ddecays}},
#' @seealso \code{\link{Plot.zeta.ddecay}}
#' @import scam
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new()
#' zeta.ddecay.bird <- Zeta.ddecay(xy.bird, data.spec.bird, sam = 100, order = 3,
#' method.glm = "glm.fit2", confint.level = 0.95)
#'
#' dev.new()
#' zeta.ddecay.bird <- Zeta.ddecay(data.spec=data.spec.bird, distance.type = "custom",
#' dist.custom = as.matrix(dist(xy.bird)), cutoff = 800000, sam = 100, order = 3,
#' reg.type = "gam", confint.level = 0.95)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new()
#' zeta.ddecay.marion <- Zeta.ddecay(xy.marion, data.spec.marion, sam = 100, order = 3,
#' method.glm = "glm.fit2", confint.level = 0.95, trsf = "log", normalize = "Jaccard")
#'
#' @export
Zeta.ddecay <- function(xy, data.spec, order = 2, sam = 1000, distance.type = "Euclidean", dist.custom = NULL, method = "mean", reg.type = "glm", family = stats::gaussian(), method.glm = "glm.fit.cons", cons = -1, cons.inter = 1, confint.level = 0.95, kn = -1, bs = "mpd", trsf = "NULL", cutoff = NULL, rescale = FALSE, normalize = FALSE, empty.row = "remove", plot = TRUE){
if(distance.type != "custom"){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
if(empty.row == "remove" & distance.type != "custom"){
if(length(which(rowSums(data.spec)==0))>0){
xy <- xy[-which(rowSums(data.spec)==0),]
data.spec <- data.spec[-which(rowSums(data.spec)==0),]
}
}
x <- dim(data.spec)[1]
zeta.val <- numeric()
zeta.val.sd <- numeric()
if(choose(x, order)>sam){
u <- rep(NA, sam)
distance <- rep(NA, sam)
for(z in 1:sam){
samp <- sample(1:x, order, replace = FALSE)
u[z] <- sum(apply(data.spec[samp, ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp, ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp, ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
if(order == 1){
stop("Error: distance decay cannot be computed for zeta 1")
}else {
if(distance.type == "Euclidean"){
distance[z] <- apply(as.matrix(c(stats::dist(xy[samp, ]))),2,get(method))
}else if(distance.type == "ortho"){
distance[z] <- apply(as.matrix(c(.gdist_matrix(xy[samp, ]))),2,get(method))
}else if(distance.type == "custom"){
if(is.null(dist.custom))
{
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
distance[z] <- apply(as.matrix(dist.custom[t(utils::combn(sort(samp),2))]),2,get(method))
}else{
stop("Error: invalid distance type")
}
}
}
}else{
u <- rep(NA, choose(x, order))
distance <- rep(NA, choose(x, order))
samp <- utils::combn(1:x, order)
for(z in 1:dim(samp)[2]){
u[z] <- sum(apply(data.spec[samp[, z], ], 2, prod))
if (normalize == "Jaccard"){
toto <- (ncol(data.spec)-sum(apply((1-data.spec[samp[, z], ]), 2, prod)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Sorensen"){
toto <- (mean(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}else if (normalize == "Simpson"){
toto <- (min(apply(data.spec[samp[, z], ], 1, sum)))
if(toto==0){
if(empty.row == 0){
u[z] <- 0
}else if(empty.row == 1){
u[z] <- 1
}
}else
u[z] <- u[z] / toto
}
if(order == 1){
stop("Error: distance decay cannot be computed for zeta 1")
}else {
if(distance.type == "Euclidean"){
distance[z] <- apply(as.matrix(c(stats::dist(xy[samp[, z], ]))),2,get(method))
}else if(distance.type == "ortho"){
distance[z] <- apply(as.matrix(c(.gdist_matrix(xy[samp[, z], ]))),2,get(method))
}else if(distance.type == "custom"){
if(is.null(dist.custom))
{
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
distance[z] <- apply(as.matrix(dist.custom[t(utils::combn(sort(samp[, z]),2))]),2,get(method))
}
else{
stop("Error: invalid distance type")
}
}
}
}
if(rescale == TRUE & normalize == FALSE){
#z1 <- mean(rowSums(data.spec))
#u <- u / z1
u <- u / ncol(data.spec)
}
zeta.val <- u
distance.reg <- distance
zeta.val.reg <- zeta.val
if(!is.null(cutoff)){
distance.reg <- distance[which(distance <= cutoff)]
zeta.val.reg <- zeta.val.reg[which(distance <= cutoff)]
}
if(trsf != "NULL"){
distance.reg <- c(apply(as.matrix(distance.reg),2,get(trsf)))
}
zeta.ddecay <- list()
zeta.ddecay$order <- order
zeta.ddecay$reg.type <- reg.type
if(reg.type == "glm"){
if(method.glm == "glm.fit.cons")
zeta.ddecay.reg <- glm.cons(zeta.val.reg ~ distance.reg, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
else
zeta.ddecay.reg <- glm2::glm2(zeta.val.reg ~ distance.reg, family = family, method = method.glm)
zeta.ddecay$reg <- zeta.ddecay.reg
if(method.glm == "glm.fit2")
zeta.ddecay$confint <- suppressMessages(stats::confint(zeta.ddecay.reg, level = confint.level))
if(plot == TRUE){
preds <- stats::predict(zeta.ddecay.reg, newdata = data.frame(distance.reg = sort(distance.reg)), type = "link", se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
fit2 <- zeta.ddecay.reg $family$linkinv(fit)
upr2 <- zeta.ddecay.reg $family$linkinv(upr)
lwr2 <- zeta.ddecay.reg $family$linkinv(lwr)
graphics::plot(distance.reg, zeta.val.reg, xlab = "Distance", ylab = paste("Zeta ", order, sep = ""), pch = 16)
graphics::lines(sort(distance.reg), fit2, col = "red", lwd = 2)
graphics::lines(sort(distance.reg), upr2, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(distance.reg), lwr2, col = "red", lty = 2, lwd = 2)
}
}else if(reg.type == "gam"){
fm <- stats::as.formula(paste("zeta.val.reg ~ s(distance.reg, k = ", kn ,")",sep=""))
zeta.ddecay.reg <- mgcv::gam(fm, family = family)
zeta.ddecay$reg <- zeta.ddecay.reg
if(plot == TRUE){
preds <- stats::predict(zeta.ddecay.reg, newdata = data.frame(distance.reg = sort(distance.reg)), se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
graphics::plot(distance.reg, zeta.val.reg, xlab = "Distance", ylab = paste("Zeta ", order, sep = ""), pch = 16)
graphics::lines(sort(distance.reg), fit, col = "red", lwd = 2)
graphics::lines(sort(distance.reg), lwr, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(distance.reg), upr, col = "red", lty = 2, lwd = 2)
}
}else if(reg.type == "scam"){
data.reg <- data.frame(zeta.val.reg,distance.reg)
fm <- stats::as.formula(paste("zeta.val.reg ~ s(distance.reg, k = ", kn ,", bs = '", bs ,"')",sep=""))
zeta.ddecay.reg <- scam::scam(fm,data=data.reg, family = family)
zeta.ddecay$reg <- zeta.ddecay.reg
if(plot == TRUE){
preds <- scam::predict.scam(zeta.ddecay.reg, newdata = data.frame(distance.reg = sort(distance.reg)), se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
graphics::plot(distance.reg, zeta.val.reg, xlab = "Distance", ylab = paste("Zeta ", order, sep = ""), pch = 16)
graphics::lines(sort(distance.reg), fit, col = "red", lwd = 2)
graphics::lines(sort(distance.reg), lwr, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(distance.reg), upr, col = "red", lty = 2, lwd = 2)
}
}else{
stop("Error: unknown regression type.")
}
zeta.ddecay$zeta.val <- zeta.val.reg
zeta.ddecay$distance <- distance.reg
return(zeta.ddecay)
}
#' Zeta distance-decay plotting
#'
#' Plots the output of the function \code{Zeta.ddecay}.
#' @param zeta.ddecay A list produced by the function \code{Zeta.ddecay}.
#' @return A plot of the zeta distance-decay with distance on the x-axis and the value of zeta on the y-axis.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.ddecay}},
#' @seealso \code{\link{Zeta.ddecays}}
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new()
#' zeta.ddecay.bird <- Zeta.ddecay(xy.bird, data.spec.bird, sam = 100, order = 3,
#' confint.level = 0.95,plot=FALSE)
#' Plot.zeta.ddecay(zeta.ddecay.bird)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' zeta.ddecay.marion <- Zeta.ddecay(xy.marion, data.spec.marion, sam = 100, order = 3,
#' confint.level = 0.95, trsf = "log", normalize = "Jaccard",plot=FALSE)
#' dev.new()
#' Plot.zeta.ddecay(zeta.ddecay.marion)
#'
#' @export
Plot.zeta.ddecay <- function(zeta.ddecay){
if(zeta.ddecay$reg.type == "glm"){
preds <- stats::predict(zeta.ddecay$reg, newdata = data.frame(distance.reg = sort(zeta.ddecay$distance)), type = "link", se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
fit2 <- zeta.ddecay$reg $family$linkinv(fit)
upr2 <- zeta.ddecay$reg $family$linkinv(upr)
lwr2 <- zeta.ddecay$reg $family$linkinv(lwr)
graphics::plot(zeta.ddecay$distance, zeta.ddecay$zeta.val, xlab = "Distance", ylab = paste("Zeta ", zeta.ddecay$order, sep = ""), pch = 16)
graphics::lines(sort(zeta.ddecay$distance), fit2, col = "red", lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), upr2, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), lwr2, col = "red", lty = 2, lwd = 2)
}else if(zeta.ddecay$reg.type == "gam"){
preds <- stats::predict(zeta.ddecay$reg, newdata = data.frame(distance.reg = sort(zeta.ddecay$distance)), se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
graphics::plot(zeta.ddecay$distance, zeta.ddecay$zeta.val, xlab = "Distance", ylab = paste("Zeta ", zeta.ddecay$order, sep = ""), pch = 16)
graphics::lines(sort(zeta.ddecay$distance), fit, col = "red", lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), lwr, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), upr, col = "red", lty = 2, lwd = 2)
}else if(zeta.ddecay$reg.type == "scam"){
preds <- scam::predict.scam(zeta.ddecay$reg, newdata = data.frame(distance.reg = sort(zeta.ddecay$distance)), se.fit = TRUE)
critval <- 1.96 ## approx 95% CI
upr <- preds$fit + (critval * preds$se.fit)
lwr <- preds$fit - (critval * preds$se.fit)
fit <- preds$fit
graphics::plot(zeta.ddecay$distance, zeta.ddecay$zeta.val, xlab = "Distance", ylab = paste("Zeta ", zeta.ddecay$order, sep = ""), pch = 16)
graphics::lines(sort(zeta.ddecay$distance), fit, col = "red", lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), lwr, col = "red", lty = 2, lwd = 2)
graphics::lines(sort(zeta.ddecay$distance), upr, col = "red", lty = 2, lwd = 2)
}else{
stop("Error: Unknown regression type.")
}
}
#' Zeta distance decay for a range of numbers of assemblages or sites
#'
#' Computes the distance decay of zeta diversity for a range of orders (number of assemblages or sites), using generalised linear models.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param orders Range of number of assemblages or sites at which zeta diversity is computed. All the orders must be striclty greater than 1.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param family A description of the error distribution and link function to be used in the generalised linear models (see \code{\link[stats]{family}} for details of family functions).
#' @param confint.level Percentage for the confidence intervals of the coefficients from the linear regression.
#' @param distance.type Method to compute distance. Default is "\code{Euclidean}", for Euclidean distance. The other options are (i) "\code{ortho}" for orthodromic distance, if xy correspond to longitudes and latitudes (orthodromic distance is computed using the \code{geodist} function from package \code{geodist}); and (ii) "\code{custom}", in which case the user must provide a distance matrix for \code{dist.custom}.
#' @param dist.custom Distance matrix provided by the user when \code{distance.type} = \code{"custom"}.
#' @param method Name of a function (as a string) indicating how to combine the pairwise differences and distances for more than 3 sites. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param trsf Name of a function (as a string) indicating how to transform distance. Default is "NULL" for the identity transformation.
#' @param cutoff If specified, maximum distance value for which the linear regression must be performed.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @return \code{Zeta.ddecays} returns a list containing the following components:
#' @return \item{orders}{Range of number of assemblages or sites at which zeta diversity was computed.}
#' @return \item{coefs}{A vector of the coefficients from the generalised linear models for the numbers of sites specified by \code{orders}.}
#' @return \item{confint}{The confidence intervals for the coefficients from the generalised linear models.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.ddecay}}
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new()
#' zeta.ddecays.bird <- Zeta.ddecays(xy.bird, data.spec.bird, sam = 100, orders = 2:5,
#' plot = TRUE, confint.level = 0.95)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new()
#' zeta.ddecays.marion <- Zeta.ddecays(xy.marion, data.spec.marion, sam = 100,
#' orders = 2:5, plot = TRUE, confint.level = 0.95)
#'
#' @export
Zeta.ddecays <- function(xy, data.spec, orders = 2:10, sam = 1000, family = stats::gaussian(), distance.type = "Euclidean", dist.custom = NULL, method = "mean", confint.level = 0.95, trsf = "NULL", cutoff = NULL, rescale = FALSE, normalize = FALSE, plot = TRUE){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(max(orders)>dim(data.spec)[1]){
stop("Error: wrong value for \"orders\": the maximum value must be equal or lower than the number of sites.")
}
if(length(which(orders<= 1))>0){stop("Error: orders must be striclty greater than 1")}
zeta.ddecays.coefs <- rep(NA, length(orders))
zeta.ddecays.confint <- matrix(NA, length(orders), 2)
ii <- 0
for (i in orders){
print(i)
ii <- ii + 1
temp <- Zeta.ddecay(xy, data.spec, sam = sam, order = i, distance.type = distance.type, dist.custom = dist.custom, method = method, reg.type = "glm", family = family, method.glm = "glm.fit2", confint.level = confint.level, trsf = trsf, cutoff = cutoff, normalize = normalize, plot = FALSE)
zeta.ddecays.coefs[ii] <- stats::coef(temp$reg)[2]
zeta.ddecays.confint[ii, ] <- temp$confint[2, ]
}
zeta.ddecays <- list()
zeta.ddecays$orders <- orders
zeta.ddecays$coefs <- zeta.ddecays.coefs
zeta.ddecays$confint <- zeta.ddecays.confint
if (plot == TRUE){
graphics::plot(orders, zeta.ddecays$coefs, pch = 16, ylim = c(min(0, range(zeta.ddecays$confint)[1]), max(0, range(zeta.ddecays$confint)[2])), xlab = "Order of zeta", ylab = "Slope", main = "Distance decay of zeta diversity")
graphics::lines(orders, zeta.ddecays$coefs)
suppressWarnings(graphics::arrows(x0 = c(orders), y0 = zeta.ddecays$coefs, x1 = c(orders), y1 = zeta.ddecays$confint[, 1], angle = 90, length = 0.2))
suppressWarnings(graphics::arrows(x0 = c(orders), y0 = zeta.ddecays$coefs, x1 = c(orders), y1 = zeta.ddecays$confint[, 2], angle = 90, length = 0.2))
graphics::lines(0:(max(orders) + 2), rep(0, max(orders) + 3), lty = 2)
}
return(zeta.ddecays)
}
#' Zeta distance-decay plotting for multiple orders
#'
#' Plots the output of the function \code{Zeta.ddecays}.
#' @param zeta.ddecays A list produced by the function \code{Zeta.ddecays}.
#' @return A plot of the zeta distance-decay with the orders on the x-axis and the slope of the linear distance-decays on the y-axis.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.ddecays}},
#' @seealso \code{\link{Zeta.ddecay}}, \code{\link{Plot.zeta.ddecay}}
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#'
#' dev.new()
#' zeta.ddecays.bird <- Zeta.ddecays(xy.bird, data.spec.bird, sam = 100, orders = 2:5,
#' plot = FALSE, confint.level = 0.95)
#' Plot.zeta.ddecays(zeta.ddecays.bird)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new()
#' zeta.ddecays.marion <- Zeta.ddecays(xy.marion, data.spec.marion, sam = 100,
#' orders = 2:5, plot = FALSE, confint.level = 0.95)
#' Plot.zeta.ddecays(zeta.ddecays.marion)
#'
#' @export
Plot.zeta.ddecays <- function(zeta.ddecays){
graphics::plot(zeta.ddecays$orders, zeta.ddecays$coefs, pch = 16, ylim = c(min(0, range(zeta.ddecays$confint)[1]), max(0, range(zeta.ddecays$confint)[2])), xlab = "Order of zeta", ylab = "Slope", main = "Distance decay of zeta diversity")
graphics::lines(zeta.ddecays$orders, zeta.ddecays$coefs)
suppressWarnings(graphics::arrows(x0 = c(zeta.ddecays$orders), y0 = zeta.ddecays$coefs, x1 = c(zeta.ddecays$orders), y1 = zeta.ddecays$confint[, 1], angle = 90, length = 0.2))
suppressWarnings(graphics::arrows(x0 = c(zeta.ddecays$orders), y0 = zeta.ddecays$coefs, x1 = c(zeta.ddecays$orders), y1 = zeta.ddecays$confint[, 2], angle = 90, length = 0.2))
graphics::lines(0:(max(zeta.ddecays$orders) + 2), rep(0, max(zeta.ddecays$orders) + 3), lty = 2)
}
#' Rescaling of data following a hierarchical increase in grain size
#'
#' Increases grain by hierarchically nesting regularly spaced sites.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param data.env Site-by-variable data frame, with sites as rows and environmental variables as columns.
#' @param method Name of a function (as a string) indicating how to combine the coordinates and the environmental variables. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param n Mapping grain (the number of sites combined to generate data at a coarser grain). Regularly spaced sites are grouped as \code{n} x \code{n} sites.
#' @details The sites (plots or quadrates) are aggregated as nearest neighbouring groups of \code{n} x \code{n} sites, using a nested approach, starting from the lowest x and y, to increase the grain. The sites can be spatially contiguous or discontiguous, as long as they are regularly spaced. This function is not suitable for irregularly spaced sites. If the total number of sites is not a multiple of \code{n} x \code{n}, the extra sites are discarded.
#' @return \code{rescale.regular} returns a data frame with the rescaled data.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.scale.regular}}, \code{\link{Zeta.scale.min.dist}}, \code{\link{rescale.min.dist}}
#' @examples
#'
#' utils::data(bird.spec.fine)
#' xy.bird <- bird.spec.fine[1:2]
#' data.spec.bird <- bird.spec.fine[3:192]
#'
#' data.rescale <- rescale.regular(xy.bird, data.spec.bird, n = 4)
#' @export
rescale.regular <- function(xy, data.spec, data.env=NULL, method = "mean", n){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
##sort data according to the plots coordinates
xy <- xy[order(xy[,1], xy[,2]), ]
data.spec <- data.spec[order(xy[,1], xy[,2]), ]
##compute the scale dependence for the specified grains
Ux <- sort(unique(xy[,1]))
Uy <- sort(unique(xy[,2]))
max.x <- Ux[length(Ux) - length(Ux)%%(n^2)]
max.y <- Uy[length(Uy) - length(Uy)%%(n^2)]
if(length(which(xy[,1]>max.x | xy[,2]>max.y))>0){
xy2 <- xy[-which(xy[,1]>max.x | xy[,2]>max.y), ]
data.spec2 <- data.spec[-which(xy[,1]>max.x | xy[,2]>max.y), ]
if(!is.null(data.env)){
data.env2 <- data.env[-which(xy[,1]>max.x | xy[,2]>max.y), ]
}
}else{
xy2 <- xy
data.spec2 <- data.spec
if(!is.null(data.env)){
data.env2 <- data.env
}
}
names <- c(names(xy), names(data.spec))
data2 <- data.frame(stats::setNames(replicate(length(names), numeric(0), simplify = F), names))
for (i in seq(1, length(unique(xy2$x)), n)){
for (j in seq(1, length(unique(xy2$y)), n)){
if(length(which(xy2$x %in% Ux[i:(i + n - 1)] & xy2$y %in% Uy[j:(j + n - 1)]))>0){
temp.xy <- xy2[which(xy2$x %in% Ux[i:(i + n - 1)] & xy2$y %in% Uy[j:(j + n - 1)]), ]
temp.xy <- apply(temp.xy, 2, get(method))
temp.spec <- data.spec2[which(xy2$x %in% Ux[i:(i + n - 1)] & xy2$y %in% Uy[j:(j + n - 1)]), ]
temp.spec <- (apply(temp.spec, 2, sum)>0) * 1
if(!is.null(data.env)){
temp.env <- data.env2[which(xy2$x %in% Ux[i:(i + n - 1)] & xy2$y %in% Uy[j:(j + n - 1)]), ]
temp.env <- apply(temp.env, 2, get(method))
}
## add the vector to the new coarser dataset
if(is.null(data.env)){
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec)))
}else{
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec, temp.env)))
}
}
}
}
if(is.null(data.env)){
names(data2) <- c(names(xy),names(data.spec))
}else{
names(data2) <- c(names(xy),names(data.spec),names(data.env))
}
return(data2)
}
#' Rescaling of data based on the minimum distance between sites
#'
#' Combines sites based on the minimum distance between them.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param data.env Site-by-variable data frame, with sites as rows and environmental variables as columns.
#' @param m Mapping grain (the number of sites combined to generate data at a coarser grain). The \code{m} closest sites are grouped together.
#' @param distance.type Method to compute distance. Default is "\code{Euclidean}", for Euclidean distance. The other options are (i) "\code{ortho}" for orthodromic distance, if xy correspond to longitudes and latitudes (orthodromic distance is computed using the \code{geodist} function from package \code{geodist}); and (ii) "\code{custom}", in which case the user must provide a distance matrix for \code{dist.custom}.
#' @param dist.custom Distance matrix provided by the user when \code{distance.type} = \code{"custom"}.
#' @param method Name of a function (as a string) indicating how to combine the coordinates and the environmental variables. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param shuffle Boolean value (TRUE or FALSE) indicating if the order of the sites must be randomised, which can have an impact on the outputs if some distances are equal.
#' @details The nearest neighbouring sites (plots, quadrates, or areas of varying shapes) are grouped as spatial clusters of 2, 3, 4, etc. sites, based on the minimum distance between them. Since the procedure is based on the relative distance between sites, the site order can have an impact on the output. This function is suitable for both regularly and irregularly spaced sites, contiguous or non contiguous. For regularly spaced sites, the use of \code{\link{rescale.regular}} is recommended.
#' @return \code{rescale.min.dist} returns a data frame with the rescaled data.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}},
#' @seealso \code{\link{Zeta.scale.min.dist}}, \code{\link{Zeta.scale.regular}}, \code{\link{rescale.regular}}
#' @examples
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' data.rescale <- rescale.min.dist(xy.marion, data.spec.marion, m=2)
#'
#' @export
rescale.min.dist <- function(xy, data.spec, data.env = NULL, m,distance.type = "Euclidean", dist.custom = NULL, method = "mean", shuffle =FALSE){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(!is.null(dist.custom)){
if(!isSymmetric(dist.custom)){
stop("Error: distance matrix is not symmetrical")
}
}
##randomize the plot orders
if (shuffle == TRUE){
xy <- xy[sample(nrow(xy)), ]
data.spec <- data.spec[sample(nrow(xy)), ]
}
#pairwise distance
if(distance.type == "Euclidean"){
D <- as.matrix(stats::dist(xy))
}else if(distance.type == "ortho"){
D <- as.matrix(.gdist_matrix(stats::dist(xy)))
}else if(distance.type == "custom"){
if(is.null(dist.custom))
{
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
D <- dist.custom
}else{
stop("Error: invalid distance type")
}
D[which(D == 0)] <- NA
names <- c(names(xy), names(data.spec))
data2 <- data.frame(stats::setNames(replicate(length(names), numeric(0), simplify = F), names))
i.plot <- 1
for(i in 1:floor(dim(xy)[1] / m)){
while(length(which(!is.na(D[, i.plot]))) == 0){
i.plot <- i.plot + 1
}
##select the plots in the group
if(distance.type != "custom"){
temp.xy <- xy[c(i.plot, order(D[, i.plot])[1:(m - 1)]), ]
}
temp.spec <- data.spec[c(i.plot, order(D[, i.plot])[1:(m - 1)]), ]
if(!is.null(data.env)){
temp.env <- data.env[c(i.plot, order(D[, i.plot])[1:(m - 1)]), ]
}
##compute the mean coordinates, the unions of species, and the mean of environmental variables
temp.xy <- apply(temp.xy, 2, get(method))
temp.spec <- (apply(temp.spec, 2, sum)>0) * 1
if(!is.null(data.env)){
temp.env <- apply(temp.env, 2, get(method))
}
## add the vector to the new coarser dataset
if(is.null(data.env)){
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec)))
}else{
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec, temp.env)))
}
##set the column corresponding to the plots to NA in the distance matrix to avoid using them in the following
DD <- D
D[, order(DD[, i.plot])[1:(m - 1)]] <- NA
D[order(DD[, i.plot])[1:(m - 1)], ] <- NA
D[, i.plot] <- NA
D[i.plot, ] <- NA
}
if(is.null(data.env)){
names(data2) <- c(names(xy),names(data.spec))
}else{
names(data2) <- c(names(xy),names(data.spec),names(data.env))
}
return(data2)
}
#' Zeta diversity scaling with sample grain using hierarchical increases in grain size
#'
#' Computes zeta diversity scaling with sample grain for a specific order (number of assemblages or sites), increasing grain by hierarchically nesting of regularly spaced sites.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param n Vector of mapping grains: regularly spaced sites are grouped as \code{n[i]} x \code{n[i]} sites to generate data at a coarser grain.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param method Name of a function (as a string) indicating how to combine the coordinates. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @param zeta.type The function that must be used for the computation of zeta diversity. Default is "\code{exact}" for calling \code{Zeta.order.ex}. Use "\code{monte carlo}" for calling \code{Zeta.order.mc}.
#' @details The sites (plots or quadrates) are incrementally aggregated as nearest neighbouring groups of 4, 9, etc. sites, using a nested approach, starting from the lowest x and y, to increase the grain. The sites can be spatially contiguous or discontiguous, as long as they are regularly spaced (see Scheiner et al., 2011). If the total number of sites is not a multiple of \code{n[i]} x \code{n[i]}, the extra sites are discarded.
#' @return \code{Zeta.scale.regular} returns a list containing the following components:
#' @return \item{order}{The order of zeta.}
#' @return \item{n}{The vector of mapping grains: regularly spaced sites are grouped as \code{n[i]} x \code{n[i]} sites to generate data at a coarser grain.}
#' @return \item{values}{The zeta diversity values for each grain.}
#' @return \item{sd}{The standard deviation of zeta diversity for each grain.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}
#' @seealso \code{\link{Zeta.scale.min.dist}}, \code{\link{rescale.regular}}, \code{\link{rescale.min.dist}}
#' @examples
#' utils::data(bird.spec.fine)
#' xy.bird <- bird.spec.fine[1:400,1:2]
#' data.spec.bird <- bird.spec.fine[1:400,3:192]
#'
#' dev.new()
#' ##sam = 25 is used here for fast execution, but a higher value is advised
#' zeta.scale.reg <- Zeta.scale.regular(xy.bird, data.spec.bird, n = 1:3, order = 3,
#' sam = 25, normalize = "Jaccard", zeta.type="monte carlo")
#' @export
Zeta.scale.regular <- function(xy, data.spec, n, order = 1, sam = 1000, method = "mean", rescale = FALSE, normalize = FALSE, plot = TRUE, zeta.type="exact"){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
n <- sort(n)
n2 <- n
zeta.val <- rep(NA, length(n))
zeta.val.sd <- rep(NA, length(n))
names <- c(names(xy), names(data.spec))
if(n[1] == 1){
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data.spec, order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data.spec, order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[1] <- zeta$zeta.val
zeta.val.sd[1] <- zeta$zeta.val.sd
n2 <- n[2:length(n)]
}
##sort data according to the plots coordinates
xy <- xy[order(xy[,1], xy[,2]), ]
data.spec <- data.spec[order(xy[,1], xy[,2]), ]
##compute the scale dependence for the specified grains
for (nn in 1:length(n2)){
Ux <- sort(unique(xy[,1]))
Uy <- sort(unique(xy[,2]))
max.x <- Ux[length(Ux) - length(Ux)%%n2[nn]]
max.y <- Uy[length(Uy) - length(Uy)%%n2[nn]]
if(length(which(xy[,1]>max.x | xy[,2]>max.y))>0){
xy2 <- xy[-which(xy[,1]>max.x | xy[,2]>max.y), ]
data.spec2 <- data.spec[-which(xy[,1]>max.x | xy[,2]>max.y), ]
}else{
xy2 <- xy
data.spec2 <- data.spec
}
data2 <- data.frame(stats::setNames(replicate(length(names), numeric(0), simplify = F), names))
for (i in seq(1, length(unique(xy2$x)), n2[nn])){
for (j in seq(1, length(unique(xy2$y)), n2[nn])){
if(length(which(xy2$x %in% Ux[i:(i + n2[nn] - 1)] & xy2$y %in% Uy[j:(j + n2[nn] - 1)]))>0){
temp.xy <- xy2[which(xy2$x %in% Ux[i:(i + n2[nn] - 1)] & xy2$y %in% Uy[j:(j + n2[nn] - 1)]), ]
temp.xy <- apply(temp.xy, 2, get(method))
temp.spec <- data.spec2[which(xy2$x %in% Ux[i:(i + n2[nn] - 1)] & xy2$y %in% Uy[j:(j + n2[nn] - 1)]), ]
temp.spec <- (apply(temp.spec, 2, sum)>0) * 1
## add the vector to the new coarser dataset
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec)))
}
}
}
names(data2) <- names
##compute the zeta diversity of the new grain
if(n[1] == 1){
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data2[3:(2 + dim(data.spec)[2])], order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data2[3:(2 + dim(data.spec)[2])], order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[nn + 1] <- zeta$zeta.val
zeta.val.sd[nn + 1] <- zeta$zeta.val.sd
}else{
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data2[3:(2 + dim(data.spec)[2])], order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data2[3:(2 + dim(data.spec)[2])], order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[nn] <- zeta$zeta.val
zeta.val.sd[nn] <- zeta$zeta.val.sd
}
}
if(plot == TRUE){
graphics::plot(n^2, zeta.val, xlab = "Grain", ylab = paste("Zeta ", order, sep = ""), main = "Zeta-Scale Relationship", pch = 16)
graphics::lines(n^2, zeta.val)
}
zeta.scale.reg <- list()
zeta.scale.reg$order <- order
zeta.scale.reg$n <- n
zeta.scale.reg$values <- zeta.val
zeta.scale.reg$sd <- zeta.val.sd
return(zeta.scale.reg)
}
#' Zeta diversity scaling with sample grain dependency based on the minimum distance between sites
#'
#' Computes zeta diversity scaling with sample grain for a specific order (number of assemblages or sites), increasing grain by sequentially adding sites based on the minimum distance between them.
#' @param xy Site-by-coordinate data frame, with sites as rows and coordinates as columns.
#' @param data.spec Site-by-species presence-absence data frame, with sites as rows and species as columns.
#' @param m Vector of mapping grains: \code{m[i]} sites are grouped together to generate data at a coarser grain.
#' @param order Specific number of assemblages or sites at which zeta diversity is computed.
#' @param reorder Number of times the sites are rearranged and grouped together for the computation of zeta (see Details).
#' @param shuffle Boolean value (TRUE or FALSE) indicating if the order of the sites must be randomised, which can have an impact on the outputs if some distances are equal.
#' @param sam Number of samples for which the zeta diversity is computed.
#' @param method Name of a function (as a string) indicating how to combine the coordinates. It can be a basic R-function such as "\code{mean}" or "\code{max}", but also a custom function.
#' @param rescale Boolean value (TRUE or FALSE) indicating if the zeta values should be divided by \eqn{\zeta_1}, to get a range of values between 0 and 1. Has no effect if \code{normalize} != \code{FALSE}.
#' @param normalize Indicates if the zeta values for each sample should be divided by the total number of species for this specific sample (\code{normalize = "Jaccard"}), by the average number of species per site for this specific sample (\code{normalize = "Sorensen"}), or by the minimum number of species in the sites of this specific sample \cr (\code{normalize = "Simpson"}). Default value is \code{FALSE}, indicating that no normalization is performed.
#' @param plot Boolean value (TRUE or FALSE) indicating if the outputs must be plotted.
#' @param sd Boolean value (TRUE or FALSE) indicating if the standard deviation must be plotted for each grain.
#' @param distance.type Method to compute distance. Default is "\code{Euclidean}", for Euclidean distance. The other options are (i) "\code{ortho}" for orthodromic distance, if xy correspond to longitudes and latitudes (orthodromic distance is computed using the \code{geodist} function from package \code{geodist}); and (ii) "\code{custom}", in which case the user must provide a distance matrix for \code{dist.custom}.
#' @param dist.custom Distance matrix provided by the user when \code{distance.type} = \code{"custom"}.
#' @param zeta.type The function that must be used for the computation of zeta diversity. Default is "\code{exact}" for calling \code{Zeta.order.ex}. Use "\code{monte carlo}" for calling \code{Zeta.order.mc}.
#' @details The nearest neighbouring sites (plots, quadrates, or areas of varying shapes) are grouped as spatial clusters of 2, 3, 4, etc. sites, based on the minimum distance between them. Since the procedure is based on the relative distance between sites, the site order can have an impact on the output. The procedure is therefore performed 'reorder' times, for which sites are randomly reordered each time, and the mean zeta is computed. This function is suitable for both regularly and irregularly spaced sites, contiguous or non contiguous (\emph{sensu} Scheiner et al., 2011). For regularly spaced sites, the use of \code{\link{Zeta.scale.regular}} is recommended.
#' @return \code{zeta.scale.min.dist} returns a list containing the following components:
#' @return \item{order}{The order of zeta.}
#' @return \item{m}{The vector of mapping grains: m[i] sites are grouped together to generate data at a coarser grain.}
#' @return \item{values}{A matrix containing the zeta diversity values over the '\code{reorder}' computations, for each grain.}
#' @return \item{sd}{A matrix containing the standard deviation of zeta diversity over the '\code{reorder}' computations, for each grain.}
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}},
#' @seealso \code{\link{Zeta.scale.regular}}, \code{\link{rescale.regular}}
#' @examples
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' dev.new()
#' zeta.scale.irreg.species <- Zeta.scale.min.dist(xy.marion, data.spec.marion, m = 1:3,
#' order = 3, reorder = 3, sam = 50, normalize = "Jaccard")
#'
#' @export
Zeta.scale.min.dist <- function(xy, data.spec, m, order = 1, reorder = 100, shuffle = TRUE, sam = 1000, method = "mean", rescale = FALSE, normalize = FALSE, plot = TRUE, sd = TRUE, distance.type = "Euclidean", dist.custom = NULL, zeta.type="exact"){
if(nrow(data.spec) != nrow(xy)){
stop("Error: data.spec and xy must have the same number of rows.")
}
if (!inherits(data.spec,"data.frame")){
stop(paste("Error: ",deparse(substitute(data.spec)), " is a ", class(data.spec), ". It must be a data frame.", sep = ""))
}
if(order>dim(data.spec)[1]){
stop("Error: wrong value for \"order\": it must be equal or lower than the number of sites.")
}
if(!is.null(dist.custom)){
if(!isSymmetric(dist.custom)){
stop("Error: distance matrix is not symmetrical")
}
}
m <- sort(m)
m2 <- m
zeta.val <- matrix(NA, reorder, length(m))
zeta.val.sd <- matrix(NA, reorder, length(m))
names <- c(names(xy), names(data.spec))
if (m[1] == 1){
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data.spec, order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data.spec, order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[, 1] <- rep(zeta$zeta.val, reorder)
zeta.val.sd[, 1] <- rep(zeta$zeta.val.sd, reorder)
m2 <- m[2:length(m)]
}
##compute the scale dependence for the specified grains
for (nn in 1:length(m2)){
zeta.scale.temp <- rep(NA, reorder)
##repeat 'reorder times'
for(reord in 1:reorder){
##randomize the plot orders
if (shuffle == TRUE){
xy <- xy[sample(nrow(xy)), ]
data.spec <- data.spec[sample(nrow(xy)), ]
}
#pairwise distance
if(distance.type == "Euclidean"){
D <- as.matrix(stats::dist(xy))
}else if(distance.type == "ortho"){
D <- as.matrix(.gdist_matrix(stats::dist(xy)))
}else if(distance.type == "custom"){
if(is.null(dist.custom))
{
stop("Error: a distance matrix must be provided if distance.type = 'custom'")
}
D <- dist.custom
}else{
stop("Error: invalid distance type")
}
D[which(D == 0)] <- NA
data2 <- data.frame(stats::setNames(replicate(length(names), numeric(0), simplify = F), names))
i.plot <- 1
for(i in 1:floor(dim(xy)[1] / m2[nn])){
while(length(which(!is.na(D[, i.plot]))) == 0){
i.plot <- i.plot + 1
}
##select the plots in the group
temp.xy <- xy[c(i.plot, order(D[, i.plot])[1:(m2[nn] - 1)]), ]
temp.spec <- data.spec[c(i.plot, order(D[, i.plot])[1:(m2[nn] - 1)]), ]
##compute the mean coordinates, the unions of species, and the mean of environmental variables
temp.xy <- apply(temp.xy, 2, get(method))
temp.spec <- (apply(temp.spec, 2, sum)>0) * 1
## add the vector to the new coarser dataset
data2 <- rbind(data2, as.vector(c(temp.xy, temp.spec)))
##set the column corresponding to the plots to NA in the distance matrix to avoid using them in the following
DD <- D
D[, order(DD[, i.plot])[1:(m2[nn] - 1)]] <- NA
D[order(DD[, i.plot])[1:(m2[nn] - 1)], ] <- NA
D[, i.plot] <- NA
D[i.plot, ] <- NA
}
names(data2) <- names
##compute the zeta diversity of the new grain
if (m[1] == 1){
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data2[3:(2 + dim(data.spec)[2])], order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data2[3:(2 + dim(data.spec)[2])], order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[reord, nn + 1] <- zeta$zeta.val
zeta.val.sd[reord, nn + 1] <- zeta$zeta.val.sd
}else{
if(zeta.type=="monte carlo"){
zeta <- Zeta.order.mc(data2[3:(2 + dim(data.spec)[2])], order = order, sam = sam, rescale = rescale, normalize = normalize)
}else if (zeta.type=="exact"){
zeta <- Zeta.order.ex(data2[3:(2 + dim(data.spec)[2])], order = order, rescale = rescale)
}else{
stop("Error: unknown method for the computation of zeta")
}
zeta.val[reord, nn] <- zeta$zeta.val
zeta.val.sd[reord, nn] <- zeta$zeta.val.sd
}
}
}
if(plot == TRUE){
graphics::plot(m, apply(zeta.val, 2, mean), ylim = c(apply(zeta.val, 2, mean)[1] - apply(zeta.val, 2, stats::sd)[1], apply(zeta.val, 2, mean)[length(m)] + apply(zeta.val, 2, stats::sd)[length(m)]), xlab = "Grain", ylab = paste("Zeta ", order, sep = ""), main = "Zeta-Scale Relationship", pch = 16)
graphics::lines(m, apply(zeta.val, 2, mean))
if(sd == TRUE){
for(i in m){
suppressWarnings(graphics::arrows(m[i], apply(zeta.val, 2, mean)[i], m[i], apply(zeta.val, 2, mean)[i] + apply(zeta.val, 2, stats::sd)[i], angle = 90, length = 0.1))
suppressWarnings(graphics::arrows(m[i], apply(zeta.val, 2, mean)[i], m[i], apply(zeta.val, 2, mean)[i] - apply(zeta.val, 2, stats::sd)[i], angle = 90, length = 0.1))
}
}
}
zeta.scale.irreg <- list()
zeta.scale.irreg$order <- order
zeta.scale.irreg$m <- m
zeta.scale.irreg$values <- zeta.val
zeta.scale.irreg$sd <- zeta.val.sd
return(zeta.scale.irreg)
}
#' Plotting of zeta diversity scaling with sample grain using hierarchical increases in grain size
#'
#' Plots the output of the function \code{Zeta.scale.regular}.
#' @param zeta.scale.reg A list generated by the function \code{Zeta.scale.regular}.
#' @param size.init initial Size of the plots before aggregation.
#' @param add Boolean value indicating if the graph must be plotted in a new graphics device or added to the active one.
#' @param ylim Numeric vectors of length 2, giving the range of y values.
#' @param col String indicating the color of the graph.
#' @return A plot of the zeta diversity scaling with the mapping grain \code{n} x \code{n} (the number of sites combined to generate data at a coarser grain) on the x-axis and the value of zeta on the y-axis.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}},
#' @seealso \code{\link{Zeta.scale.regular}}, \code{\link{Zeta.scale.min.dist}}, \code{\link{rescale.regular}},
#' @seealso \code{\link{Plot.zeta.scale.min.dist}}
#' @examples
#' utils::data(bird.spec.fine)
#' xy.bird <- bird.spec.fine[1:400,1:2]
#' data.spec.bird <- bird.spec.fine[1:400,3:192]
#'
#' ##sam = 25 is used here for fast execution, but a higher value is advised
#' zeta.scale.reg <- Zeta.scale.regular(xy.bird, data.spec.bird, n = 1:3, order = 3,
#' sam = 25, normalize = "Jaccard",plot=FALSE)
#' dev.new()
#' Plot.zeta.scale.regular(zeta.scale.reg)
#' @export
Plot.zeta.scale.regular <- function(zeta.scale.reg, size.init = 1, add = FALSE, ylim = NULL, col = "black"){
if(is.null(ylim)){
ylim=c(0,max(zeta.scale.reg$values))
}
if(add == FALSE){
graphics::plot((size.init*zeta.scale.reg$n)^2, zeta.scale.reg$values, xlab = "Grain", ylab = paste("Zeta ", zeta.scale.reg$order, sep = ""), main = "Hierarchical scaling of Zeta", pch = 16,ylim=ylim,col = col)
}else{
graphics::points((size.init*zeta.scale.reg$n)^2, zeta.scale.reg$values, pch = 16,ylim=ylim,col = col)
}
graphics::lines((size.init*zeta.scale.reg$n)^2, zeta.scale.reg$values,col = col)
}
#' Plotting of zeta diversity scaling with sample grain dependency based on the minimum distance between sites
#'
#' Plots the output of the function \code{Zeta.scale.min.dist}.
#' @param zeta.scale.irreg A list generated by the function \code{Zeta.scale.min.dist}.
#' @param size.init Initial size of the plots before aggregation.
#' @param add Boolean value indicating if the graph must be plotted in a new graphics device or added to the active one.
#' @param ylim Numeric vectors of length 2, giving the range of y values.
#' @param col String indicating the color of the graph.
#' @return A plot of the zeta diversity scaling with the mapping grain m (the number of sites combined to generate data at a coarser grain) on the x-axis and the value of zeta on the y-axis.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Scheiner S.M., Chiarucci A., Fox G.A., Helmus M.R., McGlinn D.J. & Willig M.R. (2011). The underpinnings of the relationship of species richness with space and time. \emph{Ecological Monographs}, 81, 195-213.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}},
#' @seealso \code{\link{Zeta.scale.min.dist}}, \code{\link{rescale.regular}}, \code{\link{Zeta.scale.regular}}, \code{\link{rescale.regular}},
#' @seealso \code{\link{Plot.zeta.scale.regular}}
#' @examples
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#'
#' zeta.scale.irreg.species <- Zeta.scale.min.dist(xy.marion, data.spec.marion, m = 1:3,
#' order = 3, reorder = 3, sam = 50, normalize = "Jaccard",plot=FALSE)
#' dev.new()
#' Plot.zeta.scale.min.dist(zeta.scale.irreg.species)
#' @export
Plot.zeta.scale.min.dist <- function(zeta.scale.irreg, size.init = 1, add = FALSE, ylim = NULL, col = "black"){
if(is.null(ylim)){
ylim = c(apply(zeta.scale.irreg$values, 2, mean)[1] - apply(zeta.scale.irreg$values, 2, stats::sd)[1], apply(zeta.scale.irreg$values, 2, mean)[length(zeta.scale.irreg$m)] + apply(zeta.scale.irreg$values, 2, stats::sd)[length(zeta.scale.irreg$m)])
}
if(add == FALSE){
graphics::plot(size.init*zeta.scale.irreg$m, apply(zeta.scale.irreg$values, 2, mean), ylim = ylim, xlab = "Grain", ylab = paste("Zeta ", zeta.scale.irreg$order, sep = ""), main = "Hierarchical scaling of Zeta", pch = 16, col = col)
}else{
graphics::points(size.init*zeta.scale.irreg$m, apply(zeta.scale.irreg$values, 2, mean), pch = 16, col = col)
}
graphics::lines(size.init*zeta.scale.irreg$m, apply(zeta.scale.irreg$values, 2, mean), col = col)
for(i in zeta.scale.irreg$m){
suppressWarnings(graphics::arrows(size.init*zeta.scale.irreg$m[i], apply(zeta.scale.irreg$values, 2, mean)[i], size.init*zeta.scale.irreg$m[i], apply(zeta.scale.irreg$values, 2, mean)[i] + apply(zeta.scale.irreg$values, 2, stats::sd)[i], angle = 90, length = 0.1))
suppressWarnings(graphics::arrows(size.init*zeta.scale.irreg$m[i], apply(zeta.scale.irreg$values, 2, mean)[i], size.init*zeta.scale.irreg$m[i], apply(zeta.scale.irreg$values, 2, mean)[i] - apply(zeta.scale.irreg$values, 2, stats::sd)[i], angle = 90, length = 0.1))
}
}
#' Variation partitioning for zeta diversity
#'
#' Variation partitioning of zeta diversity for a specific order (number of assemblages or sites) over distance and environmental variables.
#' @param msgdm.mod An object return by function \code{\link{Zeta.msgdm}}.
#' @param num.part Number of partitions of zeta diversity. Can be 2 or 3.
#' @param reg.type Type of regression for the multi-site generalised dissimilarity modelling. Options are "glm" for generalised linear models, "ngls" for negative linear models, "gam" for generalised additive models, "scam" for shape constrained additive models, and "ispline" for I-spline models, as recommended in generalised dissimilarity modelling by Ferrier \emph{et al}. (2007).
#' @param family A description of the error distribution and link function to be used in the \code{glm}, \code{gam} and \code{scam} models (see \code{\link[stats]{family}} for details of family functions).
#' @param method.glm Method used in fitting the generalised linear model. The default method \cr "glm.fit.cons" is an adaptation of method \code{glm.fit2} from package \code{glm2} using a negative least squares regression in the reweighted least squares. Another option is "glm.fit2", which corresponds to method \code{glm.fit2}; see help documentation for \code{glm.fit2} in package \code{glm}.
#' @param cons type of constraint in the glm if \code{method.glm = "glm.fit.cons"}. Default is -1 for negative coefficients on the predictors. The other option is 1 for positive coefficients on the predictors.
#' @param cons.inter type of constraint for the intercept. Default is 1 for positive intercept, suitable for Gaussian family. The other option is -1 for negative intercept, suitable for binomial family.
#' @param kn Number of knots in the GAM and SCAM. Default is -1 for determining kn automatically using Generalized Cross-validation.
#' @param bs A two-letter character string indicating the (penalized) smoothing basis to use in the scam model. Default is "\code{mpd}" for monotonic decreasing splines. see \code{\link[mgcv]{smooth.terms}} for an overview of what is available.
#' @return \code{Zeta.varpart} returns a data frame with one column containing the variation explained by each component \code{a} (the variation explained by distance alone), \code{b} (the variation explained by either distance or the environment), \code{c} (the variation explained by the environment alone) and \code{d} (the unexplained variation).
#' @details Note that, for a given regression, the variation explained is computed as 1-(RSS/TSS)*(v-1)/(v-p-1), where RSS is the residual sum of squares and TSS is the total sum of squares, v is the number of variables used in the regression (which is greater than the original number of variables for I-splines) and p is the number of samples. 1-(RSS/TSS) corresponds to the classical R-squared for linear regression only, and results for non-linear regressions should be interpreted with caution.
#' @details The environmental variables can be numeric or factorial, and \code{order} must be greater than 1.
#' @details For numeric variables, the pairwise difference between sites is computed and combined according to \code{method}. For factorial variables, the distance corresponds to the number of unique values over the number of assemblages of sites specified by \code{order}.
#' @details Zeta is regressed against the differences of values of the environmental variables divided by the maximum difference for each variable, to be rescaled between 0 and 1. If \code{!is.null(xy)}, distances between sites are also divided by the maximum distance.
#' @references Hui C. & McGeoch M.A. (2014). Zeta diversity as a concept and metric that unifies incidence-based biodiversity patterns. \emph{The American Naturalist}, 184, 684-694.
#' @references Borcard, D., Legendre, P. & Drapeau, P. (1992). Partialling out the spatial component of ecological variation. \emph{Ecology} 73, 1045-1055.
#' @references Legendre, P. & Legendre, L.F. (2012). \emph{Numerical ecology}, 3rd English edition. Elsevier Science BV, Amsterdam.
#' @seealso \code{\link{Zeta.decline.mc}}, \code{\link{Zeta.order.mc}}, \code{\link{Zeta.decline.ex}}, \code{\link{Zeta.order.ex}}, \code{\link{Zeta.msgdm}}, \code{\link{pie.neg}}
#' @import scam
#' @examples
#' utils::data(bird.spec.coarse)
#' xy.bird <- bird.spec.coarse[,1:2]
#' data.spec.bird <- bird.spec.coarse[,3:193]
#' utils::data(bird.env.coarse)
#' data.env.bird <- bird.env.coarse[,3:9]
#'
#' zeta.bird <- Zeta.msgdm(data.spec.bird, data.env.bird, xy.bird, sam = 100, order = 3)
#' zeta.varpart.bird <- Zeta.varpart(zeta.bird, method.glm = "glm.fit2")
#' zeta.varpart.bird
#' dev.new()
#' pie.neg(zeta.varpart.bird[4:7,1], density = c(4, 0, 8, -1),
#' angle = c(90, 0, 0, 0),
#' labels = c("distance", "undistinguishable", "environment", "unexplained"),
#' radius = 0.9)
#'
#' ##########
#'
#' utils::data(Marion.species)
#' xy.marion <- Marion.species[,1:2]
#' data.spec.marion <- Marion.species[,3:33]
#' utils::data(Marion.env)
#' data.env.marion <- Marion.env[3:4]
#'
#' zeta.marion <- Zeta.msgdm(data.spec.marion, data.env.marion, xy.marion, sam = 100,
#' order = 3, normalize = "Jaccard")
#' zeta.varpart.marion <- Zeta.varpart(zeta.marion, method.glm = "glm.fit2")
#' zeta.varpart.marion
#' dev.new()
#' pie.neg(zeta.varpart.marion[4:7,1], density = c(4, 0, 8, -1),
#' angle = c(90, 0, 0, 0),
#' labels = c("distance", "undistinguishable", "environment", "unexplained"),
#' radius = 0.9)
#'
#' @export
Zeta.varpart <- function(msgdm.mod, num.part = 2, reg.type = "glm", family = stats::gaussian(), method.glm = "glm.fit.cons", cons = -1, cons.inter = 1, kn = -1, bs="mpd"){
zeta.val <- msgdm.mod$val
data.tot <- msgdm.mod$predictors
if(reg.type == "ispline"){
if(num.part==2){
data.var <- data.tot[,1:(ncol(data.tot)-3)]
distance <- data.tot[,(ncol(data.tot)-2):ncol(data.tot)]
}else{
data.var <- data.tot[,1:(ncol(data.tot)-6)]
sp.pred <- data.tot[,(ncol(data.tot)-5):(ncol(data.tot)-3)]
distance <- data.tot[,(ncol(data.tot)-2):ncol(data.tot)]
data.var.sp <- data.tot[,1:(ncol(data.tot)-3)]
data.var.dist <- data.tot[,c(1:(ncol(data.tot)-6),(ncol(data.tot)-2):ncol(data.tot))]
data.sp.dist <- data.tot[,(ncol(data.tot)-5):ncol(data.tot)]
}
}else{
if(num.part==2){
data.var <- data.tot[,1:(ncol(data.tot)-1),drop=FALSE]
distance <- data.tot[,ncol(data.tot)]
}else{
data.var <- data.tot[,1:(ncol(data.tot)-2),drop=FALSE]
sp.pred <- data.tot[,ncol(data.tot)-1,drop=FALSE]
distance <- data.tot[,ncol(data.tot)]
data.var.sp <- data.tot[,1:(ncol(data.tot)-1),drop=FALSE]
data.var.dist <- data.tot[,c(1:(ncol(data.tot)-2),ncol(data.tot)),drop=FALSE]
data.sp.dist <- data.tot[,(ncol(data.tot)-1):ncol(data.tot),drop=FALSE]
}
}
if(num.part == 2){
if(reg.type == "glm"){
if(method.glm == "glm.fit.cons"){
abc <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
ab <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ distance, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
bc <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = data.var, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
}else{
abc <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = data.tot, family = family, method = method.glm))$r.squared,0)
bc <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = data.var, family = family, method = method.glm))$r.squared,0)
ab <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ distance, family = family, method = method.glm))$r.squared,0)
}
b <- max(ab+bc-abc,0)
a <- max(ab-b,0)
c <- max(bc-b,0)
}else if(reg.type == "gam"){
##create formula to be used in gam
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
abc <- max(summary(mgcv::gam(fm, data = data.tot, family = family))$r.sq,0)
ab <- max(summary(mgcv::gam(zeta.val ~ s(distance, k = kn), family = family,))$r.sq,0)
xnam <- names(data.var)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
bc <- max(summary(mgcv::gam(fm, data = data.var, family = family))$r.sq,0)
b <- max(ab+bc-abc,0)
a <- max(ab-b,0)
c <- max(bc-b,0)
}else if(reg.type == "scam"){
##create formula to be used in scam
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
abc <- max(summary(scam::scam(fm, data = data.tot, family = family))$r.sq,0)
ab <- max(summary(scam::scam(zeta.val ~ s(distance, k=kn, bs=bs), data=as.data.frame(distance), family = family))$r.sq,0)
xnam <- names(data.var)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
bc <- max(summary(scam::scam(fm, data = data.var, family = family))$r.sq,0)
b <- max(ab+bc-abc,0)
a <- max(ab-b,0)
c <- max(bc-b,0)
}else if(reg.type == "ngls"){
TSS <- sum((zeta.val - mean(zeta.val))^2)
toto <- rep(NA,ncol(data.tot))
for(i in 1:ncol(data.tot)){
toto[i] <- (paste("b",i,"*",names(data.tot)[i],sep=""))
}
X <- rep(1,nrow(data.tot))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.tot)+1))
start.names <- rep(NA,ncol(data.tot))
for(i in 1:(ncol(data.tot)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.tot,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.tot))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
abc <- 1-(1-R2)*(nrow(data.tot))/(nrow(data.tot)-ncol(data.tot)-1)
start <- data.frame(matrix(NA,1,1+1))
start.names <- rep(NA,1)
for(i in 1:(1+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(zeta.val ~ b0 * X + b1 * distance, start=start,algorithm="port",upper=c(Inf,0))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
ab <- 1-(1-R2)*(nrow(data.tot))/(nrow(data.tot)-1-1)
start <- data.frame(matrix(NA,1,ncol(data.var)+1))
start.names <- rep(NA,ncol(data.var))
for(i in 1:(ncol(data.var)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
toto <- rep(NA,ncol(data.var))
for(i in 1:ncol(data.var)){
toto[i] <- (paste("b",i,"*",names(data.var)[i],sep=""))
}
X <- rep(1,nrow(data.var))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
m <- stats::nls(fm, data=data.tot,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.var))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
bc <- 1-(1-R2)*(nrow(data.tot))/(nrow(data.tot)-ncol(data.tot)-1)
abc <- max(abc,0)
ab <- max(ab,0)
bc <- max(bc,0)
b <- max(ab+bc-abc,0)
a <- max(ab-b,0)
c <- max(bc-b,0)
}else if(reg.type == "ispline"){
toto <- glm.cons(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
abc <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.tot)-1)/(nrow(data.tot)-ncol(data.tot)-1)
toto <- glm.cons(zeta.val ~ ., data = distance, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
ab <- 1 - (toto$deviance/toto$null.deviance)*(nrow(distance)-1)/(nrow(distance)-ncol(distance)-1)
toto <- glm.cons(zeta.val ~ ., data = data.var, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
bc <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.var)-1)/(nrow(data.var)-ncol(data.var)-1)
b <- max(ab+bc-abc,0)
a <- max(ab-b,0)
c <- max(bc-b,0)
}else{
stop("Error: Unknwon regression type.")
}
}else{
if(reg.type == "glm"){
if(method.glm == "glm.fit.cons"){
ABC <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
AB <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ data.var.sp, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
AC <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ data.var.dist, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
BC <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ data.sp.dist, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
A <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = data.var, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
B <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = sp.pred, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
C <- max(vegan::RsquareAdj(glm.cons(zeta.val ~ ., data = distance, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
}else{
ABC <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter))$r.squared,0)
AB <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ data.var.sp, family = family, method = method.glm))$r.squared,0)
AC <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ data.var.dist, family = family, method = method.glm))$r.squared,0)
BC <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ data.sp.dist, family = family, method = method.glm))$r.squared,0)
A <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = data.var, family = family, method = method.glm))$r.squared,0)
B <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = sp.pred, family = family, method = method.glm))$r.squared,0)
C <- max(vegan::RsquareAdj(glm2::glm2(zeta.val ~ ., data = distance, family = family, method = method.glm))$r.squared,0)
}
g <- max(A+B+C-AB-AC-BC+ABC,0)
d <- max(A+B-AB-g,0)
e <- max(B+C-BC,0)
f <- max(A+C-AC,0)
a <- max(A-d-f-g,0)
b <- max(B-d-e-g,0)
c <- max(C-e-f-g,0)
}else if(reg.type == "gam"){
##create formula to be used in gam
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
ABC <- max(summary(mgcv::gam(fm, data = data.tot, family = family))$r.sq,0)
xnam <- names(data.var.sp)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
AB <- max(summary(mgcv::gam(fm, data = data.var.sp, family = family))$r.sq,0)
xnam <- names(data.var.dist)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
AC <- max(summary(mgcv::gam(fm, data = data.var.dist, family = family))$r.sq,0)
xnam <- names(data.sp.dist)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
BC <- max(summary(mgcv::gam(fm, data = data.sp.dist, family = family))$r.sq,0)
xnam <- names(data.var)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
A <- max(summary(mgcv::gam(fm, data = data.var, family = family))$r.sq,0)
xnam <- names(sp.pred)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
B <- max(summary(mgcv::gam(fm, data = sp.pred, family = family))$r.sq,0)
xnam <- names(distance)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,") + s(",sep=""),sep=""), ", k = ",kn,")",sep=""))
C <- max(summary(mgcv::gam(fm, data = distance, family = family))$r.sq,0)
g <- max(A+B+C-AB-AC-BC+ABC,0)
d <- max(A+B-AB-g,0)
e <- max(B+C-BC,0)
f <- max(A+C-AC,0)
a <- max(A-d-f-g,0)
b <- max(B-d-e-g,0)
c <- max(C-e-f-g,0)
}else if(reg.type == "scam"){
##create formula to be used in scam
xnam <- names(data.tot)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
ABC <- max(summary(scam::scam(fm, data = data.tot, family = family))$r.sq,0)
xnam <- names(data.var.sp)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
AB <- max(summary(scam::scam(fm, data = data.var.sp, family = family))$r.sq,0)
xnam <- names(data.var.dist)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
AC <- max(summary(scam::scam(fm, data = data.var.dist, family = family))$r.sq,0)
xnam <- names(data.sp.dist)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
BC <- max(summary(scam::scam(fm, data = data.sp.dist, family = family))$r.sq,0)
xnam <- names(data.var)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
A <- max(summary(scam::scam(fm, data = data.var, family = family))$r.sq,0)
xnam <- names(sp.pred)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
B <- max(summary(scam::scam(fm, data = sp.pred, family = family))$r.sq,0)
xnam <- names(distance)
fm <- stats::as.formula(paste("zeta.val ~ s(", paste(xnam, collapse = paste(", k = ",kn,", bs = '", bs ,"') + s(",sep=""),sep=""),", k = ",kn, ",bs='", bs, "')",sep=""))
C <- max(summary(scam::scam(fm, data = distance, family = family))$r.sq,0)
g <- max(A+B+C-AB-AC-BC+ABC,0)
d <- max(A+B-AB-g,0)
e <- max(B+C-BC,0)
f <- max(A+C-AC,0)
a <- max(A-d-f-g,0)
b <- max(B-d-e-g,0)
c <- max(C-e-f-g,0)
}else if(reg.type == "ngls"){
TSS <- sum((zeta.val - mean(zeta.val))^2)
toto <- rep(NA,ncol(data.tot))
for(i in 1:ncol(data.tot)){
toto[i] <- (paste("b",i,"*",names(data.tot)[i],sep=""))
}
X <- rep(1,nrow(data.tot))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.tot)+1))
start.names <- rep(NA,ncol(data.tot))
for(i in 1:(ncol(data.tot)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.tot,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.tot))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
ABC <- 1-(1-R2)*(nrow(data.tot))/(nrow(data.tot)-ncol(data.tot)-1)
toto <- rep(NA,ncol(data.var.sp))
for(i in 1:ncol(data.var.sp)){
toto[i] <- (paste("b",i,"*",names(data.var.sp)[i],sep=""))
}
X <- rep(1,nrow(data.var.sp))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.var.sp)+1))
start.names <- rep(NA,ncol(data.var.sp))
for(i in 1:(ncol(data.var.sp)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.var.sp,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.var.sp))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
AB <- 1-(1-R2)*(nrow(data.var.sp))/(nrow(data.var.sp)-ncol(data.var.sp)-1)
toto <- rep(NA,ncol(data.var.dist))
for(i in 1:ncol(data.var.dist)){
toto[i] <- (paste("b",i,"*",names(data.var.dist)[i],sep=""))
}
X <- rep(1,nrow(data.var.dist))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.var.dist)+1))
start.names <- rep(NA,ncol(data.var.dist))
for(i in 1:(ncol(data.var.dist)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.var.dist,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.var.dist))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
AC <- 1-(1-R2)*(nrow(data.var.dist))/(nrow(data.var.dist)-ncol(data.var.dist)-1)
toto <- rep(NA,ncol(data.sp.dist))
for(i in 1:ncol(data.sp.dist)){
toto[i] <- (paste("b",i,"*",names(data.sp.dist)[i],sep=""))
}
X <- rep(1,nrow(data.sp.dist))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.sp.dist)+1))
start.names <- rep(NA,ncol(data.sp.dist))
for(i in 1:(ncol(data.sp.dist)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.sp.dist,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.sp.dist))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
BC <- 1-(1-R2)*(nrow(data.sp.dist))/(nrow(data.sp.dist)-ncol(data.sp.dist)-1)
toto <- rep(NA,ncol(data.var))
for(i in 1:ncol(data.var)){
toto[i] <- (paste("b",i,"*",names(data.var)[i],sep=""))
}
X <- rep(1,nrow(data.var))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(data.var)+1))
start.names <- rep(NA,ncol(data.var))
for(i in 1:(ncol(data.var)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=data.var,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(data.var))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
A <- 1-(1-R2)*(nrow(data.var))/(nrow(data.var)-ncol(data.var)-1)
toto <- rep(NA,ncol(sp.pred))
for(i in 1:ncol(sp.pred)){
toto[i] <- (paste("b",i,"*",names(sp.pred)[i],sep=""))
}
X <- rep(1,nrow(sp.pred))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(sp.pred)+1))
start.names <- rep(NA,ncol(sp.pred))
for(i in 1:(ncol(sp.pred)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=sp.pred,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(sp.pred))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
B <- 1-(1-R2)*(nrow(sp.pred))/(nrow(sp.pred)-ncol(sp.pred)-1)
toto <- rep(NA,ncol(distance))
for(i in 1:ncol(distance)){
toto[i] <- (paste("b",i,"*",names(distance)[i],sep=""))
}
X <- rep(1,nrow(distance))
fm <- stats::as.formula(paste("zeta.val ~ b0*X +",paste(toto,collapse=" + ",sep=""),sep=""))
start <- data.frame(matrix(NA,1,ncol(distance)+1))
start.names <- rep(NA,ncol(distance))
for(i in 1:(ncol(distance)+1)){
start[1,i] <- -1
start.names[i] <- (paste("b",i-1,sep=""))
}
names(start) <- start.names
start <- as.list(start)
start[[1]] <- 1
m <- stats::nls(fm, data=distance,start=start,algorithm="port",upper=c(Inf,rep(0,ncol(distance))))
RSS.p <- sum(stats::residuals(m)^2)
R2 <- 1 - (RSS.p/TSS)
C <- 1-(1-R2)*(nrow(distance))/(nrow(distance)-ncol(distance)-1)
ABC <- max(ABC,0)
AB <- max(AB,0)
AC <- max(AC,0)
BC <- max(BC,0)
g <- max(A+B+C-AB-AC-BC+ABC,0)
d <- max(A+B-AB-g,0)
e <- max(B+C-BC,0)
f <- max(A+C-AC,0)
a <- max(A-d-f-g,0)
b <- max(B-d-e-g,0)
c <- max(C-e-f-g,0)
}else if(reg.type == "ispline"){
toto <- glm.cons(zeta.val ~ ., data = data.tot, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
ABC <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.tot)-1)/(nrow(data.tot)-ncol(data.tot)-1)
toto <- glm.cons(zeta.val ~ ., data = data.var.sp, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
AB <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.var.sp)-1)/(nrow(data.var.sp)-ncol(distance)-1)
toto <- glm.cons(zeta.val ~ ., data = data.var.dist, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
BC <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.var.dist)-1)/(nrow(data.var.dist)-ncol(data.var.dist)-1)
toto <- glm.cons(zeta.val ~ ., data = data.var, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
A <- 1 - (toto$deviance/toto$null.deviance)*(nrow(data.var)-1)/(nrow(data.var)-ncol(data.var)-1)
toto <- glm.cons(zeta.val ~ ., data = sp.pred, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
B <- 1 - (toto$deviance/toto$null.deviance)*(nrow(sp.pred)-1)/(nrow(sp.pred)-ncol(sp.pred)-1)
toto <- glm.cons(zeta.val ~ ., data = distance, family = family, method = method.glm, cons = cons, cons.inter = cons.inter)
C <- 1 - (toto$deviance/toto$null.deviance)*(nrow(distance)-1)/(nrow(distance)-ncol(distance)-1)
g <- max(A+B+C-AB-AC-BC+ABC,0)
d <- max(A+B-AB-g,0)
e <- max(B+C-BC,0)
f <- max(A+C-AC,0)
a <- max(A-d-f-g,0)
b <- max(B-d-e-g,0)
c <- max(C-e-f-g,0)
}else{
stop("Error: Unknwon regression type.")
}
}
if(num.part==2){
zeta.varpart <- data.frame(c(abc,ab,bc,a,b,c,1-abc))
row.names(zeta.varpart) <- c("[abc]","[ab]","[bc]","[a]","[b]","[c]","[d]")
names(zeta.varpart) <- "Adjusted Rsq"
}else{
zeta.varpart <- data.frame(c(ABC,AB,AC,BC,A,B,C,a,b,c,d,e,f,g,1-ABC))
row.names(zeta.varpart) <- c("[abcdefg]","[abdefg]","[acefg]","[bcefg]","[adfg]","[bdeg]","[cefg]","[a]","[b]","[c]","[d]","[e]","[f]","[g]","[h]")
names(zeta.varpart) <- "Adjusted Rsq"
}
return(zeta.varpart)
}
#' Pie Chart, considering negative values as zeros
#'
#' Plots a pie chart, considering negative values as zeros, for the purpose of illustrating variation partitioning.
#' @param x A vector of non-negative numerical quantities. The values in x are displayed as the areas of pie slices.
#' @param labels One or more expressions or character strings giving names for the slices. Other objects are coerced by \code{\link[grDevices]{as.graphicsAnnot}}. For empty or NA (after coercion to character) labels, no label nor pointing line is drawn.
#' @param edges The circular outline of the pie is approximated by a polygon with this many edges.
#' @param radius The pie is drawn centered in a square box whose sides range from -1 to 1. If the character strings labeling the slices are long it may be necessary to use a smaller radius.
#' @param clockwise Logical indicating if slices are drawn clockwise or counter clockwise (i.e., mathematically positive direction, used by default).
#' @param init.angle number specifying the starting angle (in degrees) for the slices. Defaults to 0 (i.e., '3 o'clock') unless clockwise is true where init.angle defaults to 90 (degrees), (i.e., '12 o'clock').
#' @param density The density of shading lines, in lines per inch. The default value of NULL means that no shading lines are drawn. Non-positive values of density also inhibit the drawing of shading lines.
#' @param angle The slope of shading lines, given as an angle in degrees (counter-clockwise).
#' @param col A vector of colors to be used in filling or shading the slices. If missing a set of 6 pastel colours is used, unless density is specified when par("fg") is used.
#' @param border,lty (possibly vectors) arguments passed to polygon which draws each slice.
#' @param main An overall title for the plot.
#' @param warning Boolean value. Set to FALSE to avoid displaying a warning if some values are negative and set to 0.
#' @param ... Graphical parameters can be given as arguments to pie. They will affect the main title and labels only.
#' @details This function is identical to the function \code{\link[graphics]{pie}} in \{graphics\}, except that it considers all negative values as zeros, to allow for plotting variation partitioning outputs. The original \code{\link[graphics]{pie}} function returns an error when negative values are present. However, variation partitioning can return negative values, which can then be treated as zeros (Legendre & Legendre, 2008). This function allows direct use of the results from \code{\link{Zeta.varpart}} without editing the data.
#' @seealso \code{\link[graphics]{pie}}, \code{\link{Zeta.varpart}}
#' @references Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988). \emph{The new S language}. Wadsworth & Brooks/Cole.
#' @references Cleveland, W. S. (1985). \emph{The elements of graphing data}. Wadsworth: Monterey, CA, USA.
#' @references Legendre, P. & Legendre, L.F. (2012). \emph{Numerical ecology}, 3rd English edition. Elsevier Science BV, Amsterdam.
#' @examples
#' pie.neg(rep(1, 24), col = rainbow(24), radius = 0.9)
#' @export
pie.neg <- function (x, labels = names(x), edges = 200, radius = 0.8, clockwise = FALSE,
init.angle = if (clockwise) 90 else 0, density = NULL, angle = 45,
col = NULL, border = NULL, lty = NULL, main = NULL, warning = TRUE, ...)
{
if (!is.numeric(x) || any(is.na(x)))
stop("Error: 'x' values must be numeric.")
if (sum(x < 0)>0){
x[which(x<0)] <- 0
warning("Negative values set to 0.")
}
if (is.null(labels))
labels <- as.character(seq_along(x))
else labels <- grDevices::as.graphicsAnnot(labels)
x <- c(0, cumsum(x) / sum(x))
dx <- diff(x)
nx <- length(dx)
graphics::plot.new()
pin <- graphics::par("pin")
xlim <- ylim <- c(-1, 1)
if (pin[1L] > pin[2L])
xlim <- (pin[1L] / pin[2L]) * xlim
else ylim <- (pin[2L] / pin[1L]) * ylim
grDevices::dev.hold()
on.exit(grDevices::dev.flush())
graphics::plot.window(xlim, ylim, "", asp = 1)
if (is.null(col))
col <- if (is.null(density))
c("white", "lightblue", "mistyrose", "lightcyan",
"lavender", "cornsilk")
else graphics::par("fg")
if (!is.null(col))
col <- rep_len(col, nx)
if (!is.null(border))
border <- rep_len(border, nx)
if (!is.null(lty))
lty <- rep_len(lty, nx)
angle <- rep(angle, nx)
if (!is.null(density))
density <- rep_len(density, nx)
twopi <- if (clockwise)
-2 * pi
else 2 * pi
t2xy <- function(t) {
t2p <- twopi * t + init.angle * pi / 180
list(x = radius * cos(t2p), y = radius * sin(t2p))
}
for (i in 1L:nx) {
n <- max(2, floor(edges * dx[i]))
P <- t2xy(seq.int(x[i], x[i + 1], length.out = n))
graphics::polygon(c(P$x, 0), c(P$y, 0), density = density[i], angle = angle[i],
border = border[i], col = col[i], lty = lty[i])
P <- t2xy(mean(x[i + 0:1]))
lab <- as.character(labels[i])
if (!is.na(lab) && nzchar(lab)) {
graphics::lines(c(1, 1.05) * P$x, c(1, 1.05) * P$y)
graphics::text(1.1 * P$x, 1.1 * P$y, labels[i], xpd = TRUE,
adj = ifelse(P$x < 0, 1, 0), ...)
}
}
graphics::title(main = main, ...)
invisible(NULL)
}
####################
##HELPER FUNCTIONS##
####################
.gdist_matrix <- function(xy){
xy <- as.matrix(xy)
return(stats::as.dist(geodist::geodist(xy)))
}
.Mi <- function(i,k,x,ts){
MM <- NA
if(k==1){
if(ts[i]<=x && x<ts[i+1]){MM <- 1/(ts[i+1]-ts[i])}
else{MM <- 0}
}else{
tss <-ts[i+k]
if(i+k > length(ts)){tss <- 1}
if(tss-ts[i]==0){
MM <- 0
}else{
MM <- k*((x-ts[i])*.Mi(i,k-1,x,ts)+(tss-x)*.Mi(i+1,k-1,x,ts))/((k-1)*(tss-ts[i]))
}
}
return(MM)
}
.Ii <- function(i,k,x,ts){
j <- which(ts >= x)[1]-1
II <- 0
if((j-k+1)>i){
II <- 1
}else if(i <= j){
for(m in i:j){
if(m+k+1 > length(ts)){
II <- II+(1-ts[m])*.Mi(m,k+1,x,ts)/(k+1)
}else{
II <- II+(ts[m+k+1]-ts[m])*.Mi(m,k+1,x,ts)/(k+1)
}
}
}
return(II)
}
####################
##DATA DESCRIPTION##
####################
#' South-East Australia Environmental Dataset at Coarse Scale
#'
#' Projected coordinates and environmental variables in 123, 100 x 100 km sites.
#'
#'
#' The data set contains the following variables:
#'
#' \itemize{
#' \item{x}: x-position in meters in UTM 53 South projection
#' \item{y}: y-position in meters in UTM 53 South projection
#' \item{Natural}: Proportion of area of conservation and natural environments
#' \item{Irrigated}: Proportion of area of production from irrigated agriculture and plantations
#' \item{Water}: Proportion of area of water features
#' \item{Elevation}: Elevation
#' \item{ApP}: Area per person
#' \item{Temp}: Temperature
#' \item{Precip}: Precipitation
#' }
#'
#' Location: Australia -- 51° 27' 2.27" S, 135° 21' 35.19" E
#'
#' Data owners: ABARES, Australian Bureau of Statistics,GEBCO, WorldClim
#' @name bird.env.coarse
#' @usage data(bird.env.coarse)
#' @docType data
#' @references http://data.daff.gov.au/anrdl/metadata_files/pa_luav4g9abl07811a00.xml
#' @references http://www.gebco.net/
#' @references http://www.abs.gov.au/AUSSTATS/[email protected]/DetailsPage/1270.0.55.0072011?
#' @references http://www.worldclim.org/
#' @references Hijmans, R.J., Cameron, S.E., Parra, J.L., Jones, P.G. & Jarvis, A. (2005) Very high resolution interpolated climate surfaces for global land areas. International journal of climatology, 25, 1965-1978.
#' @keywords data
#' @format A data frame with 123 rows (sites) and 9 columns (xy coordinates and environmental variables).
"bird.env.coarse"
#' South-East Australia Environmental Dataset at Fine Scale
#'
#' Projected coordinates and environmental variables in 604, 25 x 25 km contiguous sites.
#'
#'
#' The data set contains the following variables:
#'
#' \itemize{
#' \item{x}: x-position in meters in UTM 53 South projection
#' \item{y}: y-position in meters in UTM 53 South projection
#' \item{Natural}: Proportion of area of conservation and natural environments
#' \item{Irrigated}: Proportion of area of production from irrigated agriculture and plantations
#' \item{Water}: Proportion of area of water features
#' \item{Elevation}: Elevation
#' \item{ApP}: Area per person
#' \item{Temp}: Temperature
#' \item{Precip}: Precipitation
#' }
#'
#' Location: Australia -- 50° 33' 5.03" S, 135° 21' 10.40" E
#'
#' Data owners: ABARES, Australian Bureau of Statistics,GEBCO, WorldClim
#' @name bird.env.fine
#' @usage data(bird.env.fine)
#' @docType data
#' @references http://data.daff.gov.au/anrdl/metadata_files/pa_luav4g9abl07811a00.xml
#' @references http://www.gebco.net/
#' @references http://www.abs.gov.au/AUSSTATS/[email protected]/DetailsPage/1270.0.55.0072011?
#' @references http://www.worldclim.org/
#' @references Hijmans, R.J., Cameron, S.E., Parra, J.L., Jones, P.G. & Jarvis, A. (2005) Very high resolution interpolated climate surfaces for global land areas. International journal of climatology, 25, 1965-1978.
#' @keywords data
#' @format A data frame with 604 rows (sites) and 9 columns (xy coordinates and environmental variables).
"bird.env.fine"
#' Australia Bird Atlas Species Occurrence Dataset at Coarse Scale over South-East Australia
#'
#' Inventory of bird species occurrence in 123, 100 x 100 km sites.
#'
#'\itemize{
#' \item{x}: x-position in meters in UTM 53 South projection
#' \item{y}: y-position in meters in UTM 53 South projection
#' \item{columns 3-193}: bird species occurrence
#' }
#'
#' The original bird occurrence data were arranged into a continuous grid covering South-East Australia. Only cells whose richness was within 10 percents of real estimated richness are included here, so that the data corresponds to presence-absence data.
#'
#' Location: Australia -- 51° 27' 2.27" S, 135° 21' 35.19" E
#'
#' Data owner: BirdLife Australia
#' @name bird.spec.coarse
#' @usage data(bird.spec.coarse)
#' @docType data
#' @references Barrett, G., Silcocks, A., Barry, S., Cunningham, R. & Poulter, R. (2003) The new atlas of Australian birds. Royal Australasian Ornithologists Union, Melbourne, 1-824.
#' @keywords data
#' @format A data frame with 123 rows (sites) and 193 columns (xy coordinates and species).
"bird.spec.coarse"
#' Australia Bird Atlas Species Occurrence Dataset at Fine Scale over South-East Australia
#'
#' Inventory of bird species occurrence in 604, 25 x 25 km sites.
#'
#' \itemize{
#' \item{x}: x-position in meters in UTM 53 South projection
#' \item{y}: y-position in meters in UTM 53 South projection
#' \item{columns 3-192}: bird species occurrence
#' }
#'
#' Location: Australia -- 50° 33' 5.03" S, 135° 21' 10.40" E
#'
#' Data owner: BirdLife Australia
#'
#' The original bird occurrence data were arranged into a continuous grid covering South-East Australia. Only cells whose richness was within 10 percents of real estimated richness are included here, so that the data corresponds to presence-absence data.
#'
#' @name bird.spec.fine
#' @usage data(bird.spec.fine)
#' @docType data
#' @references Barrett, G., Silcocks, A., Barry, S., Cunningham, R. & Poulter, R. (2003) The new atlas of Australian birds. Royal Australasian Ornithologists Union, Melbourne, 1-824.
#' @keywords data
#' @format A data frame with 604 rows (sites) and 193 columns (xy coordinates and species).
"bird.spec.fine"
#' Marion Island Species Presence-Absence Dataset
#'
#' Inventory of springtails and mite species presence-absence in 12 plots (4 transects and 3 altitudes) on Marion Island.
#'
#' The data set contains the following variables:
#'
#' \itemize{
#' \item{x}: x-position in meters in UTM 37 South projection
#' \item{y}: y-position in meters in UTM 37 South projection
#' \item{columns 3-24}: mite species presence absence
#' \item{columns 25-33}: springtail species presence absence
#' }
#'
#' Location: Marion Island -- 46° 53' 34.2" S, 37 degrees 45' 02.3" E
#'
#' Data owner: Melodie A. McGeoch
#' @name Marion.species
#' @usage data(Marion.species)
#' @docType data
#' @references Nyakatya, M.J. & McGeoch, M.A. (2008). Temperature variation across Marion Island associated with a keystone plant species (\emph{Azorella selago} Hook. (Apiaceae)). Polar Biology, 31, 139-151.
#' @references McGeoch, M.A., Le Roux, P.C., Hugo, E.A. & Nyakatya, M.J. (2008). Spatial variation in the terrestrial biotic system. The Prince Edward Islands: Land-Sea Interactions in a Changing World (ed. by S.L. Chown and P.W. Froneman), pp. 245-276. African SunMedia, Stellenbosch.
#' @keywords data
#' @format A data frame with 12 rows (plots) and 33 columns (species).
"Marion.species"
#' Marion Island Environmental Dataset
#'
#' Geographic coordinates, altitude and island side (East, West) at 12 plots (4 transects and 3 altitudes) on Marion Island.
#'
#' The data set contains the following variables:
#'
#' \itemize{
#' \item{x}: x-position in meters in UTM 37 projection
#' \item{y}: y-position in meters in UTM 37 projection
#' \item{Altitude}: mean elevation
#' \item{Side}: cardinal (East or West) side of the island
#' }
#'
#' Location: Marion Island -- 46° 53' 34.2" S, 37 degrees 45' 02.3" E
#'
#' Data owner: Melodie A. McGeoch
#' @name Marion.env
#' @usage data(Marion.env)
#' @docType data
#' @references Nyakatya, M.J. & McGeoch, M.A. (2008). Temperature variation across Marion Island associated with a keystone plant species (\emph{Azorella selago} Hook. (Apiaceae)). Polar Biology, 31, 139-151.
#' @references McGeoch, M.A., Le Roux, P.C., Hugo, E.A. & Nyakatya, M.J. (2008). Spatial variation in the terrestrial biotic system. The Prince Edward Islands: Land-Sea Interactions in a Changing World (ed. by S.L. Chown and P.W. Froneman), pp. 245-276. African SunMedia, Stellenbosch.
#' @keywords data
#' @format A data frame with 12 rows (plots) and 4 columns (variables).
"Marion.env"
| /scratch/gouwar.j/cran-all/cranData/zetadiv/R/zetadiv.R |
#' Example data for zfa
#' @usage data(zfa.example)
#' @description Example data for \code{"zfa"} function.
#' @format The \code{zfa.example} contains the following objects:
#'
#' \code{X}
#'
#' a numeric genotype matrix of 1800 individuals and 512 rare variants. Each row represents a different individual, and each column represents a different rare genetic variant. Genotypes are coded as 0,1 or 2.
#'
#' \code{y}
#'
#' a numeric vector of binary phenotypes, among which there are 343 cases and 1457 controls.
#'
#' @seealso \code{\link{zfa}}
"zfa.example"
| /scratch/gouwar.j/cran-all/cranData/zfa/R/data.R |
zooming.fast<-function(data,y,obj,test=c("wtest","SKAT","SKATO","burden")) {
lower<-1
upper<-ncol(data)
mid<-ncol(data)
if (test=="wtest") {
pvalue<-wtest(data[,c(lower:upper)],y)
} else if (test=="SKAT") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower:upper)]),obj)$p.value
} else if (test=="SKATO") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower:upper)]),obj,method="SKATO")$p.value
} else if (test=="burden") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower:upper)]),obj,method="Burden")$p.value
}
pvalue.all<-pvalue
upper.all<-upper
lower.all<-lower
while (mid>2){
mid<-mid/2
if (test=="wtest") {
pvalue.left<-wtest(data[,c(lower:(lower+mid-1))],y)
pvalue.right<-wtest(data[,c((upper-mid+1):upper)],y)
} else if (test=="SKAT") {
pvalue.left<-(SKAT::SKATBinary(as.matrix(data[,c(lower:(lower+mid-1))]),obj)$p.value)
pvalue.right<-(SKAT::SKATBinary(as.matrix(data[,c((upper-mid+1):upper)]),obj)$p.value)
} else if (test=="SKATO") {
pvalue.left<-(SKAT::SKATBinary(as.matrix(data[,c(lower:(lower+mid-1))]),obj,method="SKATO")$p.value)
pvalue.right<-(SKAT::SKATBinary(as.matrix(data[,c((upper-mid+1):upper)]),obj,method="SKATO")$p.value)
} else if (test=="burden") {
pvalue.left<-(SKAT::SKATBinary(as.matrix(data[,c(lower:(lower+mid-1))]),obj,method="Burden")$p.value)
pvalue.right<-(SKAT::SKATBinary(as.matrix(data[,c((upper-mid+1):upper)]),obj,method="Burden")$p.value)
}
pvalue<-min(pvalue.left,pvalue.right)
if (pvalue==pvalue.left){
upper<-upper-mid
} else if (pvalue==pvalue.right){
lower<-lower+mid
}
pvalue<-ifelse(pvalue>1,1,pvalue)
pvalue.all<-c(pvalue.all,pvalue)
upper.all<-c(upper.all,upper)
lower.all<-c(lower.all,lower)
}
pvalue.final<-min(pvalue.all)
upper.final<-upper.all[which(pvalue.all==pvalue.final)[1]]
lower.final<-lower.all[which(pvalue.all==pvalue.final)[1]]
pvalue.final<-pvalue.final
pvalue.final<-ifelse(pvalue.final>1,1,pvalue.final)
result<-cbind(lower.final,upper.final,pvalue.final)
colnames(result)<-c("lower","upper","corrected.pvalue")
rm(pvalue,pvalue.all,pvalue.final,upper,upper.all,upper.final,lower,lower.all,lower.final,data,y)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/fast.zoom.function.R |
focusing<-function(result,data,y,fast.path,filter.pval,bin,i,obj,test=c("wtest","SKAT","SKATO","burden")) {
filter.pval<-ifelse(is.null(filter.pval),1,filter.pval)
if (result[,"corrected.pvalue"]<=filter.pval){
d<-result[,"upper"]-result[,"lower"]+1
if (d==2) {
inward<-0
outward<-2*d
} else {
inward<-d/4
outward<-d/2
}
pvalue.left<-NULL
lb.all<-NULL
for (j in (-outward):(inward)) {
lb.new<-result[,"lower"]+j
if (lb.new>0) {
lb.all<-rbind(lb.all,lb.new)
if (test=="wtest") {
pvalue.left<-rbind(pvalue.left,wtest(data[,c(lb.new:result[,"upper"])],y))
} else if (test=="SKAT") {
pvalue.left<-rbind(pvalue.left,SKAT::SKATBinary(as.matrix(data[,c(lb.new:result[,"upper"])]),obj)$p.value)
} else if (test=="SKATO") {
pvalue.left<-rbind(pvalue.left,SKAT::SKATBinary(as.matrix(data[,c(lb.new:result[,"upper"])]),obj,method="SKATO")$p.value)
} else if (test=="burden") {
pvalue.left<-rbind(pvalue.left,SKAT::SKATBinary(as.matrix(data[,c(lb.new:result[,"upper"])]),obj,method="Burden")$p.value)
}
}
}
lb.final<-lb.all[which(pvalue.left==min(pvalue.left))][1]
rm(pvalue.left,lb.new)
pvalue.right<-NULL
ub.all<-NULL
for (j in (-inward):(outward)) {
ub.new<-result[,"upper"]+j
if (ub.new<(ncol(data)+1)) {
ub.all<-rbind(ub.all,ub.new)
if (test=="wtest") {
pvalue.right<-rbind(pvalue.right,wtest(data[,c(lb.final:ub.new)],y))
} else if (test=="SKAT") {
pvalue.right<-rbind(pvalue.right,SKAT::SKATBinary(as.matrix(data[,c(lb.final:ub.new)]),obj)$p.value)
} else if (test=="SKATO") {
pvalue.right<-rbind(pvalue.right,SKAT::SKATBinary(as.matrix(data[,c(lb.final:ub.new)]),obj,method="SKATO")$p.value)
} else if (test=="burden") {
pvalue.right<-rbind(pvalue.right,SKAT::SKATBinary(as.matrix(data[,c(lb.final:ub.new)]),obj,method="Burden")$p.value) }
}
}
ub.final<-ub.all[which(pvalue.right==min(pvalue.right))][1]
k<-length(c(lb.all,ub.all))-2
if (fast.path) {
pvalue.right.corrected<-pvalue.right*(bin/2+log2(bin)-1+k)
} else {
pvalue.right.corrected<-pvalue.right*(bin-1+k)
}
pvalue.right.corrected<-ifelse(pvalue.right.corrected>1,1,pvalue.right.corrected)
result<-cbind(lb.final+bin*(i-1),ub.final+bin*(i-1),ub.final-lb.final+1,min(pvalue.right.corrected)[1])
colnames(result)<-c("lower.bound","upper.bound","opt.region.size","corrected.pvalue")
rm(pvalue.right,pvalue.right.corrected,ub.all,ub.new)
} else {
if (fast.path) {
result[,"corrected.pvalue"]<-result[,"corrected.pvalue"]*(bin/2+log2(bin)-1)
result[,"corrected.pvalue"]<-ifelse(result[,"corrected.pvalue"]>1,1,result[,"corrected.pvalue"])
} else {
result[,"corrected.pvalue"]<-result[,"corrected.pvalue"]/(bin/(result[,"upper"]-result[,"lower"]+1))*(bin-1)
result[,"corrected.pvalue"]<-ifelse(result[,"corrected.pvalue"]>1,1,result[,"corrected.pvalue"])
}
result<-t(c(result[,"lower"]+bin*(i-1),result[,"upper"]+bin*(i-1),result[,"upper"]-result[,"lower"]+1,result[,"corrected.pvalue"]))
colnames(result)<-c("lower.bound","upper.bound","opt.region.size","corrected.pvalue")
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/focus.function.R |
zooming.full<-function(data,y,obj,test=c("wtest","SKAT","SKATO","burden")) {
P<-ncol(data)
R<-floor(log2(P))
r<-c(1:R)
nr<-c(2^(r-1))
d<-P/nr
result.all<-NULL
for (j in 1:R) {
d1<-d[j]
nr1<-nr[j]
c<-c(1:nr1)
lower.all<-d1*(c-1)+1
upper.all<-d1*c
pvalue.all<-NULL
for (k in 1:nr1){
if (test=="wtest") {
pvalue<-wtest(data[,c(lower.all[k]:upper.all[k])],y)*nr1
} else if (test=="SKAT") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower.all[k]:upper.all[k])]),obj)$p.value*nr1
} else if (test=="SKATO") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower.all[k]:upper.all[k])]),obj,method="SKATO")$p.value*nr1
} else if (test=="burden") {
pvalue<-SKAT::SKATBinary(as.matrix(data[,c(lower.all[k]:upper.all[k])]),obj,method="Burden")$p.value*nr1
}
pvalue<-ifelse(pvalue>1,1,pvalue)
pvalue.all<-c(pvalue.all,pvalue)
}
result<-cbind(lower.all,upper.all,pvalue.all)
result.all<-rbind(result.all,result)
}
pvalue.final<-result.all[,3]
pvalue.final<-ifelse(pvalue.final>1,1,pvalue.final)
result.all<-cbind(result.all[,1:2],pvalue.final)
colnames(result.all)<-c("lower","upper","corrected.pvalue")
order.pvalue<-order(result.all[,"corrected.pvalue"],decreasing=F)
min.pvalue<-t(result.all[order.pvalue[1],])
rm(order.pvalue,result.all,result)
return(min.pvalue)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/full.zoom.function.R |
maf<-function(data){
p<-colMeans(data)/2
p[p>0.5]<-1-p[p>0.5]
result.maf<-p
return(result.maf)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/maf.R |
#' @export
print.zfa<-function(x, ...){
cat("No.regions:\n")
print(x$n.region)
cat("\nNo.rare:\n")
print(x$n.rare)
cat("\nNo.common:\n")
print(x$n.common)
cat("\nResults:\n")
print(x$results)
cat("Bon.sig.level:\n")
print(x$Bon.sig.level)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/print.method.R |
#'@useDynLib zfa, .registration = TRUE
table.e1<-function(x,y){
.Call("table_e1",x,y)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/table.function.R |
wtest<-function(data,y){
y<-as.matrix(y)
all.table<-apply(data,2,table.e1,y)
sum.table<-matrix(rowSums(all.table),ncol=2)
cont.table<-sum.table[rowSums(sum.table)!=0,]
rm(all.table,sum.table)
if(0 %in% cont.table)
cont.table<-cont.table+0.5
hf<-matrix(c(0.5,1,0.667,2),nrow=2,ncol=2,byrow=T)
result.x2<-x2(cont.table)
rm(cont.table)
x2.column<-1
df.column<-x2.column+1
w.value<-result.x2[x2.column]*hf[result.x2[df.column],1]
p.value<-pchisq(w.value,df=hf[result.x2[df.column],2],lower.tail=F)
result.all<-c(result.x2,w.value,p.value)
rm(result.x2)
result.wtest<-result.all[4]
rm(result.all,w.value,p.value)
return(result.wtest)
}
x2<-function(cont.table){
df<-NROW(cont.table)-1
o<-cont.table
cont.table<-t(t(cont.table)/colSums(cont.table))
p<-cont.table/(1-cont.table)
OR<-p[,2]/p[,1]
o<-cbind(o,t(colSums(o)-t(o)))
sd<-sqrt(rowSums(1/o))
x2.value=sum((log(OR)/sd)^2)
x2.result<-c(x2.value,df)
return(x2.result)
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/wtest.R |
#' Zoom-Focus Algorithm
#'
#' @description This function performs the Zoom-Focus Algorithm (ZFA) to locate optimal testing regions for rare variant association tests and performs the test based on the optimized regions. The package is suitable to be applied on sequencing data set that is composed of variants with minor allele frequency less than 0.01 (rare variants). The package calls existing rare variant test functions to conduct rare variant test.
#'
#' ZFA consists of two steps: Zooming and Focusing. In the first step Zooming, a given genomic region is partitioned by an order of two, and the best partition is located using multiple testing corrected p-values returned by desired rare variant test. In the second step Focusing, the boundaries of the zoomed region are refined by allowing them to expand or shrink at micro-level. The computation complexity is linear to the number of variants for Zooming (when the option fast.path=FALSE); a fast-Zoom version can further reduce the complexity to the logarithm of data size (fast.path=TRUE, default).
#'
#' @param data a data frame or numeric matrix. Genotypes should be coded as 0,1 or 2.
#' @param y a numeric vector with two levels. Phenotype values are coded as 0 or 1.
#' @param bin a numeric integer taking value of power of two, namely, 2, 4, 8, 16, 32, 64, 128, 256, 512 etc. The bin size specifies the initial window size P to perform the Zoom-Focus Algorithm. Default bin =256.
#' @param fast.path a logical value indicating whether or not to use the fast-Zoom approach. The fast-Zoom performs a binary search instead of exhaustive search, such that at each partition order, the region is divided into two parts, only the part with smaller p-value is continued for the next level search. Default = TRUE.
#' @param filter.pval a p-value threshold to select zoomed regions for conducting focusing step. When specified, only zoomed regions with p-value smaller than the threshold will be passed to focusing step. Default=0.01. Set filter.pval=NULL for conducting focusing step with all the zoomed regions.
#' @param output.pval a p-value threshold for filtering the output. If set NULL, all the results will be listed; otherwise, the function will only output the regions with p-values smaller than output.pval. Default=0.05.
#' @param CommonRare_Cutoff MAF cutoff to define common and rare variants. Default=0.01.
#' @param test a character to choose the rare variant method that combines with the Zoom-Focus Algorithm.If test = "SKAT", the SKAT of variance component test is applied. If test = "SKATO", the SKAT-O of combination method test is applied. If test = "burden", the weighted burden test is applied. If test = "wtest", the W-test of burden test category is applied.
#' @return The \code{"zfa"} function returns a list with the following components:
#'
#' \item{n.regions}{Total number of regions to which the input genotype data is divided by initial bin size P.}
#'
#' \item{n.rare}{Total number of rare variants used for the analysis.}
#'
#' \item{n.common}{Total number of common variants excluded in the analysis.}
#'
#' \item{results}{The testing results consist of several elements: 1) \code{lower.bound and upper.bound} represent variant information which indicates the lower and upper bound of optimized testing region; 2) \code{opt.region.size} denotes the size of optimal testing region after performing ZFA; 3) \code{corrected.pvalue} displays the multiple testing (Bonferroni) corrected p-value of the optimal testing region.}
#'
#' \item{Bon.sig.level}{Suggested Bonferroni corrected significance level for the input data at threshold alpha=0.05, which equals to 0.05 / # of regions.}
#'
#' \item{variants}{The variants contained in each output optimal region.}
#'
#' Note that the \code{variants} in the optimized region will not be printed in default. User can can extract the information by calling details of results. See an example in \strong{Examples} section.
#'
#' The zfa optimizes the testing region according to input variant sequence and assumes that they are arranged by chromosome positions. If variants from non-adjacent genomic regions are input as one data, the zfa will still treat them as adjacent. In this case, the user should be careful in interpreting the results: when an optimized region consists of distant variants, the region may not be biologically meaningful; when an optimized region consists of variants from two neighboring genes, the results may be meaningful.
#'
#' @details The algorithm divides sequencing data into multiple fixed genomic regions with a certain initial bin size. ZFA is conducted in each bin. Current version includes 4 existing rare variant tests. The SKAT, SKAT-O and weighted burden test are called from \code{'SKAT'} package, and the W-test Collapsing method is self-contained.
#'
#' @author Haoyi Weng & Maggie Wang
#'
#' @references M. H. Wang., H. Weng., et al. (2017) A Zoom-Focus algorithm (ZFA) to locate the optimal testing region for rare variant association tests. Bioinformatics.
#'
#' M. H. Wang., R. Sun., et al. (2016) A fast and powerful W-test for pairwise epistasis testing. Nucleic Acids Research.doi:10.1093/nar/gkw347.
#'
#' R. Sun., H. Weng., et al. (2016) A W-test collapsing method for rare-variant association testing in exome sequencing data. Genetic Epidemiology, 40(7): 591-596.
#'
#' Wu, M. C., Lee, S., et al. (2011) Rare Variant Association Testing for Sequencing Data Using the Sequence Kernel Association Test (SKAT). American Journal of Human Genetics, 89, 82-93.
#'
#' Lee, S., Emond, M.J., et al. (2012) Optimal unified approach for rare variant association testing with application to small sample case-control whole-exome sequencing studies. American Journal of Human Genetics, 91, 224-237.
#'
#' Lee, S., Fuchsberger, C., et al. (2015) An efficient resampling method for calibrating single and gene-based rare variant association analysis in case-control studies. Biostatistics, kxv033.
#'
#' @examples
#' data(zfa.example)
#' attach(zfa.example)
#'
#' # fast-zoom with wtest, all zoomed regions passed to focusing step, and output all results
#' zfa.result1<-zfa(X,y,bin = 32,fast.path = TRUE,filter.pval=NULL,output.pval=NULL,test = "wtest")
#'
#' # zooming with wtest, select zoomed regions for focusing and output regions with both p-value<0.01
#' zfa.result2<-zfa(X,y,bin = 32,fast.path = FALSE,filter.pval=0.01,output.pval=0.01,test = "wtest")
#'
#' ## an example to view the detail of variants in each output optimal region
#' result1.detail<-zfa.result1$variants
#'
#' @export
#' @importFrom stats pchisq
zfa<-function(data,y,bin=256,fast.path=TRUE,filter.pval=0.01,output.pval=0.05,CommonRare_Cutoff=0.01,test=c("SKAT","SKATO","burden","wtest")) {
if (is.data.frame(y))
y<-as.matrix(y)
if (any(is.na(data)))
stop ("NA occurs in data")
if (!all(data %in% c(0,1,2)))
stop ("all the genotypes in 'data' must be 0, 1 or 2")
n.col<-ncol(data)
if (n.col<2)
stop ("'data' must contain at least two variants")
if (any(is.na(y)))
stop ("NA occurs in y")
if (!all(y %in% c(0,1)))
stop ("all the phenotypes in 'y' must be 0 or 1")
if (length(y)!=nrow(data))
stop ("'data' and 'y' must have the same length")
if (!bin %in% 2^c(1:10))
stop ("initial fixed window size must be an integer which belongs to the power of two, such as 4, 18 , 16, 32, 64, 128, 256, ...")
if (CommonRare_Cutoff>0.5)
stop ("The MAF cutoff should be a numeric value between 0 and 0.5")
maf.data<-maf(data)
if (any(maf.data>CommonRare_Cutoff)) {
data<-data[,-c(which(maf.data>CommonRare_Cutoff))]
n.common<-length(which(maf.data>CommonRare_Cutoff))
n.rare<-n.col-n.common
warning ("Common variants found in 'data', which were excluded from the analysis")
} else {
n.common<-0
n.rare<-n.col
}
if (ncol(data)<bin) {
bin<-2^c(1:10)
bin<-bin[which(ncol(data)-bin>0)]
bin<-bin[which.min(ncol(data)-bin)]
}
num.fix.window<-floor(ncol(data)/bin)
result.final<-NULL
if (test!="wtest") {obj<-SKAT::SKAT_Null_Model(y ~ 1, out_type="D")}
if (fast.path) {
for (i in 1:num.fix.window) {
data1<-data[,c((bin*(i-1)+1):(bin*i))]
result<-zooming.fast(data1,y,obj,test)
result.final<-data.frame(rbind(result.final,focusing(result,data1,y,fast.path,filter.pval,bin,i,obj,test)))
rm(data1,result)
}
} else {
for (i in 1:num.fix.window) {
data1<-data[,c((bin*(i-1)+1):(bin*i))]
result<-zooming.full(data1,y,obj,test)
result.final<-data.frame(rbind(result.final,focusing(result,data1,y,fast.path,filter.pval,bin,i,obj,test)))
rm(data1,result)
}
}
if (bin*num.fix.window!=ncol(data)) {
total.region<-num.fix.window+1
tail<-c(bin*num.fix.window+1,ncol(data))
if (test=="wtest") {
result.tail<-cbind(tail[1],tail[2],tail[2]-tail[1]+1,wtest(data[,tail[1]:tail[2]],y))
} else if (test=="SKAT") {
result.tail<-cbind(tail[1],tail[2],tail[2]-tail[1]+1,SKAT::SKATBinary(as.matrix(data[,tail[1]:tail[2]]),obj)$p.value)
} else if (test=="SKATO") {
result.tail<-cbind(tail[1],tail[2],tail[2]-tail[1]+1,SKAT::SKATBinary(as.matrix(data[,tail[1]:tail[2]]),obj,method="SKATO")$p.value)
} else if (test=="burden") {
result.tail<-cbind(tail[1],tail[2],tail[2]-tail[1]+1,SKAT::SKATBinary(as.matrix(data[,tail[1]:tail[2]]),obj,method="Burden")$p.value)
}
colnames(result.tail)<-c("lower.bound","upper.bound","opt.region.size","corrected.pvalue")
result.final<-data.frame(rbind(result.final,result.tail))
rm(tail,result.tail)
} else {
total.region<-num.fix.window
}
if(!is.null(output.pval)) {
l.output.pval<-which(result.final[,"corrected.pvalue"]<=output.pval)
result.final<-result.final[l.output.pval,]
}
if (nrow(result.final)==0) {
out<-list(n.regions=total.region,n.rare=n.rare,n.common=n.common,results=NULL,Bon.sig.level=0.05/total.region,variants=NULL)
} else {
marker.info<-colnames(data.frame(data))
region.num<-paste("region",rownames(result.final),sep = " ")
variant.detail<-apply(result.final,1,function(x) marker.info[c(x[1]:x[2])])
if (length(region.num)==1) {
variant.detail<-list(variant.detail)
}
names(variant.detail)<-c(region.num)
result.final[,1]<-marker.info[result.final[,1]]
result.final[,2]<-marker.info[result.final[,2]]
out<-list(n.regions=total.region,n.rare=n.rare,n.common=n.common,results=result.final,Bon.sig.level=0.05/total.region,variants=variant.detail)
}
class(out)<-"zfa"
out
}
| /scratch/gouwar.j/cran-all/cranData/zfa/R/zfa.R |
#' Create a pipe-friendly version of a function
#'
#' @description
#' These functions all serve the role of rearranging the arguments of other
#' functions, in order to create pipe-friendly versions.
#'
#' `zfunction()` rearranges the arguments of any function moving the specified
#' argument to the front of the list, so that this argument becomes the
#' recipient of piping. It returns a copy of the input function, that is
#' identical to the original except for the order of the arguments.
#'
#' @param fun The function to adapt (for `zfitter()` this should be a fitting
#' function that takes `formula` and `data` parameters). The name should not be
#' quoted, rather, the actual function should be passed (prefixed with package
#' if needed).
#'
#' @param x The name of the argument that should be moved to the front of the
#' argument list. Can be passed with or without quotes, and is processed using
#' non-standard evaluation unless surrounded with curlies, as in `{value}`,
#' see details below.
#'
#' @param x_not_found How to handle the case where the value of `x` is not the
#' name of a parameter in `fun`. If `error`, abort the function. If `ok`,
#' prepend the value to the existing parameter list. This can be useful if
#' looking to pipe data into a parameter that is hidden by a `...`.
#'
#' @details
#' The `x` parameter is processed using non-standard evaluation, which can be
#' disabled using curly brackets. In other words, the following are all
#' equivalent, and return a file renaming function with the `to` parameter as
#' the first one:
#'
#' * `zfunction(file.rename, to)`
#' * `zfunction(file.rename, "to")`
#' * `param_name <- "to"; zfunction(file.rename, {param_name})`
#'
#' @examples
#' # A a grep function with x as first param is often useful
#' zgrep <- zfunction(grep, x)
#' carnames <- rownames(mtcars)
#' grep("ll", carnames, value=TRUE)
#' zgrep(carnames, "ll", value=TRUE)
#'
#' # zfunction() is the best approach to wrapping functions such as
#' # `pls::plsr()` that hide the data parameter behind the `...`.
#' if (requireNamespace("pls")) {
#' zplsr <- zfunction(pls::plsr, data, x_not_found = "ok")
#' zplsr(cars, dist ~ speed)
#' }
#'
#' # Curly {x} handling: These are all equivalent
#' param_name <- "to";
#' f1 <- zfunction(file.rename, to)
#' f2 <- zfunction(file.rename, "to")
#' f3 <- zfunction(file.rename, {param_name})
#'
#' @md
#' @rdname zfunction
#' @export
zfunction <- function(fun, x, x_not_found = c("error", "warning", "ok")) {
# Process and validate args
!missing(x) || stop("x may not be missing")
x <- curly_arg(x) # Process curlies{}
nchar(x) > 0 || stop("argument \"x\" is missing, with no default")
is.function(fun) || stop( paste0("Specified function ('",
deparse(substitute(fun)), "') was not found.") )
x_not_found <- match.arg(x_not_found)
frm <- formals(fun)
ix <- which(names(frm)==x)
# Rearrange the formals
if (length(ix) > 0) {
# x found in the parameter list, move to front
formals(fun) <- frm[c(ix, zeq(1,ix-1), zeq(ix+1,length(frm)))]
} else {
msg <- paste0("'", x, "' not found in the parameter list of '",
deparse(substitute(fun)), "()'")
if (x_not_found == "error") {
stop(msg)
} else if (x_not_found == "warning") {
warning(msg)
}
# x not found in the parameter list (but no error thrown)
# Add x to front of the list
pl <- alist(x_tmp=); names(pl)[1] <- x
formals(fun) <- c(pl, frm)
}
# Return the modified function
fun
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/base_a_zfunction.R |
#' Create pipe-friendly fold around a function
#'
#' @description
#' `zfold()` creates a pipe-friendly version of a function of the standard
#' format by creating a fold (or wrapper) around it with the parameters
#' reordered. Compared to using `zfunction()`, which makes a copy of the
#' original function with rearranged the parameters, this creates a wrapper that
#' in turn will call the original function with all passed parameters. This is
#' good for making pipe-friendly versions of `S3` generics, whereas rearranging
#' parameters directly will break the `S3` dispatch mechanism.
#'
#' @examples
#' # Using zfold() to create a grep() wrapper with the desired arg order
#' zgrep <- zfold(grep, x)
#' carnames <- rownames(mtcars)
#' grep("ll", carnames, value=TRUE)
#' zgrep(carnames, "ll", value=TRUE)
#'
#' @md
#' @rdname zfunction
#' @export
zfold <- function(fun, x, x_not_found = c("error", "warning", "ok")) {
# Process and validate args
!missing(x) || stop("x may not be missing")
x <- curly_arg(x) # Process curlies{}
nchar(x) > 0 || stop("argument \"x\" is missing, with no default")
is.function(fun) || stop( paste0("Specified function ('",
deparse(substitute(fun)), "') was not found.") )
!missing(x) || stop("x may not be missing")
x_not_found <- match.arg(x_not_found)
# Store the name of the function to call, trimming package if present
fun_name <- deparse(substitute(fun))
fun_name <- gsub(".*::", "", fun_name)
# Construct a shim, then reorder the arguments using zfunction()
result <- function() {
# Assign 'fun' in 'e', a new environment that then contains both
# 'fun' and the calling environment, parent.frame(), where other
# variables that 'fun' # needs are available
e <- new.env(parent = parent.frame())
assign(fun_name, fun, envir = e)
# Match the call, and evaluate the function in e
cl <- match.call()
cl[[1]] <- as.name(fun_name)
eval(cl, envir = e)
}
formals(result) <- formals(zfunction(fun, {x}, x_not_found = x_not_found))
# Return the newly created function
result
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/base_b_zfold.R |
#' @description
#' `zfitter()` creates a pipe-friendly version of a fitting function of the
#' standard format –– that is a function with a `formula` parameter followed by
#' a `data` parameter. It also shortens very long data names (longer than 32
#' characters by default), which otherwise are a nuisance when the data comes
#' from the pipe, because the pipeline gets converted to a very long function
#' call.
#'
#' @examples
#' # Using zfitter to wrap around a fitting function
#' # (this is the actual way zlm_robust is defined in this package)
#' if (requireNamespace("estimatr", quietly = TRUE)) {
#' zlm_robust <- zfitter(estimatr::lm_robust)
#' zlm_robust(cars, speed~dist)
#'
#' # The resulting function works well the native pipe ...
#' if ( getRversion() >= "4.1.0" ) {
#' cars |> zlm_robust( speed ~ dist )
#' }
#' }
#'
#' # ... or with dplyr
#' if ( require("dplyr", warn.conflicts=FALSE) ) {
#'
#' # Pipe cars dataset into zlm_robust for fitting
#' cars %>% zlm_robust( speed ~ dist )
#'
#' # Process iris with filter() before piping. Print a summary()
#' # of the fitted model using zprint() before assigning the
#' # model itself (not the summary) to m.
#' m <- iris %>%
#' dplyr::filter(Species=="setosa") %>%
#' zlm_robust(Sepal.Length ~ Sepal.Width + Petal.Width) %>%
#' zprint(summary)
#' }
#'
#' @rdname zfunction
#' @export
zfitter <- function(fun) {
# zfitter() only makes sense if fun has "formula" & "data" parameters.
# For edge cases, zfold() can always be called directly
if ( length(setdiff(c("formula","data"), names(formals(fun)))) > 0 ) {
stop( paste0("Specified fitting function ('",
deparse(substitute(fun)), "') must take formula and data parameters.") )
}
# Call zfold() to create a fold around fun with "data" param at front
# Use eval(bquote()) to preserve the correct name of the function
eval(bquote( zfold(.(substitute(fun)), "data" )))
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/base_c_zfitter.R |
#' Create a safer sequence
#'
#' Internal function to create a sequence in a safe way.
#'
#' @param from Low end of sequence
#' @param to High end of sequence
#' @return A sequence from `from` to `to`, or error if `to<from`
#'
#' @md
#' @noRd
zeq <- function(from, to)
{
stopifnot ( round(from) == from )
stopifnot ( round(to) == to )
stopifnot ( to >= from - 1 )
return (seq_len(1+to-from)+from-1)
}
#' Process curly parameters
#'
#' Curly parameters are processed using NSE, unless they are encapsulated in
#' curlies `{}`, which optionally triggers standard evaluation. This function
#' is only intended to be used inside another function, and it is used in
#' a very similar way to `match.arg()`. The examples are very useful ...
#'
#' @param param The parameter to process as a curly param.
#'
#' @examples
#' # Not run automatically because curly_arg() is private
#' \dontrun{
#' # Usage of curly_arg() compared with match.arg()
#' curly_demo <- function(x, y = c("yes", "no")) {
#' x <- zfit:::curly_arg(x)
#' y <- match.arg(y)
#' x
#' }
#'
#' myparam <- "a string"
#' myvector <- c("string 1", "string 2")
#'
#' curly_demo(a_symbol) # NSE ON
#' curly_demo("a string") # NSE disabled with "" for constant strins
#' curly_demo({"curly-wrap"}) # NSE disabled with {}
#' curly_demo(c("a","b")) # NSE ON, usually not wanted, quoting preferred
#' curly_demo({c("a","b")}) # NSE disabled with {}, allowing vectors
#' curly_demo(myparam) # NSE ON, even if a value exists for myparam
#' curly_demo("myparam") # NSE disabled, result is a string constant
#' curly_demo({myparam}) # NSE disabled, value of myparam propagates
#' curly_demo({myvector}) # NSE disabled, value of myvector propagates
#' }
#'
#' @keywords internal
curly_arg <- function(param) {
# Boilerplate for processing {param}
double_sub_symbol <- eval.parent(bquote( substitute(.(substitute(param)))))
res <- deparse(double_sub_symbol)
if ( (res[1] == "{" && res[length(res)] == "}") ||
grepl("^\".*\"$", res) ) {
res <- param
}
res
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/base_utils.R |
#' zfit: Fit Models in a Pipe
#'
#' @description
#' `r desc::desc_get("Description")`
#'
#' @includeRmd man/include/overview.Rmd
#'
#' @seealso
#' * [zlm] is the wrapper `lm`, probably the most common fitting
#' function. The help file for this function includes several
#' usage examples.
#' * [zglm] is a wrapper for `glm`, to fit generalized
#' linear models.
#' * [zprint] is helpful for printing a `summary` of a model,
#' but assigning the evaluated model to a variable
#'
#' @docType package
#' @name zfit
"_PACKAGE"
| /scratch/gouwar.j/cran-all/cranData/zfit/R/zfit-package.R |
# Small wrapper to prepare the missing package message
msg_pkg_missing <- function(fun, pkg) {
paste0( "'", fun, "' requires the '", pkg, "' package.\n",
" Install with install.packages(\"", pkg, "\") and restart R.")
}
#' Pipe-friendly wrappers for external fitters
#'
#' @description
#' These functions provide pipe-friendly wrappers around model fitters provided
#' by several external packages. The functions require the corresponding
#' packages to be installed, if the required package is missing the functions
#' warns with directions for how to install it.
#'
#' `zlm_robust()` wraps [estimatr::lm_robust()], which fits a linear model with
#' a variety of options for estimating robust standard errors.
#'
#' @examples
#' if (requireNamespace("estimatr") && getRversion() >= "4.1.0")
#' zlm_robust(cars, dist ~ speed) |> summary() |> try()
#'
#' @name zlm_robust
#' @rdname external_fitters
#' @export
if (requireNamespace("estimatr", quietly = TRUE)) {
zlm_robust <- zfitter(estimatr::lm_robust)
} else {
zlm_robust <- function(...) {
stop(msg_pkg_missing("zlm_robust()", "estimatr"))
}
}
#' @description
#' `zpolr()` wraps [MASS::polr()], which fits an ordered logistic response for
#' multi-value ordinal variables, using a proportional odds logistic regression.
#'
#' @examples
#' if (requireNamespace("MASS") && getRversion() >= "4.1.0")
#' zpolr(mtcars, ordered(gear) ~ mpg + hp) |> summary() |> try()
#'
#' @name zpolr
#' @rdname external_fitters
#' @export
if (requireNamespace("MASS", quietly = TRUE)) {
zpolr <- zfitter(MASS::polr)
} else {
zpolr <- function(...) {
stop(msg_pkg_missing("zpolr()", "MASS"))
}
}
#' @description
#' `zplsr()` wraps [pls::plsr()], which performs a partial least squares
#' regression.
#'
#' @examples
#' if (requireNamespace("pls") && getRversion() >= "4.1.0")
#' zplsr(cars, dist ~ speed) |> summary() |> try()
#'
#' @name zplsr
#' @rdname external_fitters
#' @export
if (requireNamespace("pls", quietly = TRUE)) {
zplsr <- zfunction(pls::plsr, x = "data", x_not_found = "ok")
} else {
zplsr <- function(...) {
stop(msg_pkg_missing("zplsr()", "pls"))
}
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/zfit_external.R |
# Fix R CMD check errors
utils::globalVariables("gaussian")
utils::globalVariables("binomial")
#' Run a glm model in a pipe
#'
#' @description
#' These functions are wrappers for the [glm] function. The `zglm` function can
#' be used to estimate any generalized linear model in a pipe. The `zlogit`,
#' `zprobit`, and `zpoisson` functions can be used to estimate specific models.
#' All of these functions rely on the `glm` function for the actual estimation,
#' they simply pass the corresponding values to the `family` parameter of the
#' `glm` function.
#'
#' Usage of these functions is very similar to the [zlm] function (a wrapper
#' for lm), for detailed examples, check out the entry for that function.
#'
#' @param data A `data.frame` containing the model data.
#' @param formula The `formula` to be fitted.
#' @param family See the `glm` function.
#' @param weights See the `glm` function.
#' @param subset See the `glm` function.
#' @param na.action See the `glm` function.
#' @param start See the `glm` function.
#' @param etastart See the `glm` function.
#' @param mustart See the `glm` function.
#' @param offset See the `glm` function.
#' @param control See the `glm` function.
#' @param model See the `glm` function.
#' @param method See the `glm` function.
#' @param x See the `glm` function.
#' @param y See the `glm` function.
#' @param singular.ok See the `glm` function.
#' @param contrasts See the `glm` function.
#' @param ... Other arguments to be passed to the `glm` function.
#'
#' @return A fitted model.
#'
#' @seealso * [zlm] is the wrapper for [lm], probably the most common fitting
#' function. The help file for [zlm] function includes several usage examples.
#'
#' @export
zglm <- zfitter(stats::glm)
#' @description
#' The `zlogit` function calls `zglm`, specifying `family=binomial(link="logit")`.
#'
#' @name zglm
#' @export
zlogit = function(data, formula, ...) {
# Assign data to local var, to preserve form of call (see zlm())
assign(deparse(substitute(data)),data)
eval(bquote( zglm(.(substitute(data)), .(formula), family=binomial(link="logit"), ...) ))
}
#' @description
#' The `zprobit` function calls `zglm`, specifying `family=binomial(link="probit")`.
#'
#' @name zglm
#' @export
zprobit = function(data, formula, ...) {
# Assign data to local var, to preserve form of call (see zlm())
assign(deparse(substitute(data)),data)
eval(bquote( zglm(.(substitute(data)), .(formula), family=binomial(link="probit"), ...) ))
}
#' @description
#' The `zpoisson` function calls `zglm`, specifying `family="poisson"`.
#'
#' @name zglm
#' @export
zpoisson = function(data, formula, ...) {
# Assign data to local var, to preserve form of call (see zlm())
assign(deparse(substitute(data)),data)
eval(bquote( zglm(.(substitute(data)), .(formula), family="poisson", ...) ))
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/zfit_glm.R |
#' Run an lm model in a pipe.
#'
#' This function wraps around the [lm] function in order to make it
#' more friendly to pipe syntax (with the data first).
#'
#' @param data A `data.frame` containing the model data.
#' @param formula The `formula` to be fitted.
#' @param subset See the `lm` function.
#' @param weights See the `lm` function.
#' @param na.action See the `lm` function.
#' @param method See the `lm` function.
#' @param model See the `lm` function.
#' @param x See the `lm` function.
#' @param y See the `lm` function.
#' @param qr See the `lm` function.
#' @param singular.ok See the `lm` function.
#' @param contrasts See the `lm` function.
#' @param offset See the `lm` function.
#' @param ... Other arguments to be passed to the `lm` function.
#' @return A fitted model.
#'
#' @seealso
#' * [zglm] is a wrapper for `glm`, to fit generalized
#' linear models.
#'
#' @examples
#' # Usage is possible without pipes
#' zlm( cars, dist ~ speed )
#'
#' # zfit works well with dplyr and magrittr pipes
#' if ( require("dplyr", warn.conflicts=FALSE) ) {
#'
#' # Pipe cars dataset into zlm for fitting
#' cars %>% zlm(speed ~ dist)
#'
#' # Process iris with filter before piping to zlm
#' iris %>%
#' filter(Species == "setosa") %>%
#' zlm(Sepal.Length ~ Sepal.Width + Petal.Width)
#' }
#'
#' # zfit also works well with the native pipe
#' if ( require("dplyr") && getRversion() >= "4.1.0" ) {
#'
#' # Pipe cars dataset into zlm for fitting
#' cars |> zlm(speed ~ dist)
#'
#' # Process iris with filter() before piping. Print a
#' # summary of the fitted model using zprint() before
#' # assigning the model itself (not the summary) to m.
#' m <- iris |>
#' filter(Species == "setosa") |>
#' zlm(Sepal.Length ~ Sepal.Width + Petal.Width) |>
#' zprint(summary)
#' }
#'
#' @export
zlm <- zfitter(stats::lm)
| /scratch/gouwar.j/cran-all/cranData/zfit/R/zfit_lm.R |
#' Print the result of a function in a pipe but return original object
#'
#' Given `x` and `f`, this function prints `f(x)` before returning the original
#' `x`. It is useful in a pipe, when one wants a to print the derivative of an
#' object in the pipe but then return or assign the original object. A common
#' use case is printing the `summary() of an estimated model but then assigning
#' the original model (rather than the summary object) to a variable for further
#' processing.
#'
#' @param x An object, typically in a pipe.
#' @param f A function to be applied to `x` before printing.
#' @param ... Other arguments to be passed to `f`.
#'
#' @return The original object `x`.
#'
#' @examples
#' if (getRversion() >= "4.1.0" && require("dplyr")) {
#'
#' # Print summary before assigning model to variable
#' m <- lm( speed ~ dist, cars) |>
#' zprint(summary) # prints summary(x)
#' m # m is the original model object
#'
#' # Print grouped data before filtering original
#' cw_subset <- chickwts |>
#' zprint(count, feed, sort=TRUE) |> # prints counts by feed
#' filter(feed=="soybean")
#' cw_subset # cw_subset is ungrouped, but filtered by feed
#' }
#'
#' @export
zprint = function(x, f=NULL, ...) {
if (is.null(f)) {
print(x)
} else {
print(f(x, ...))
}
invisible(x)
}
| /scratch/gouwar.j/cran-all/cranData/zfit/R/zfit_zprint.R |
`zfit` makes it easier to use a piped workflow with functions that don't have the "correct" order of parameters (the first parameter of the function does not match the object passing through the pipe).
The issue is especially prevalent with model fitting functions, such as when passing and processing a `data.frame` (or `tibble`) before passing them to `lm()` or similar functions. The pipe passes the data object into the first parameter of the function, but the conventional estimation functions expect a formula to be the first parameter.
This package addresses the issue with three functions that make it trivial to construct a pipe-friendly version of any function:
* `zfunction()` reorders the arguments of a function. Just pass the name of a function, and the name of the parameter that should receive the piped argument, and it returns a version of the function with that parameter coming first.
* `zfold()` creates a fold (a wrapper) around a function with the reordered arguments. This is sometimes needed instead of a simple reordering, for example for achieving correct S3 dispatch, and for functions that report its name or other information in output.
* `zfitter()` takes any estimation function with the standard format of a `formula` and `data` parameter, and returns a version suitable for us in pipes (with the `data` parameter coming first). Internally, it simply calls the `zfold()` function to create a fold around the fitter function.
The package also includes ready made wrappers around the most commonly used estimation functions. `zlm()`and `zglm()` correspond to `lm()` and `glm()`, and `zlogit()`, `zprobit()`, and `zpoisson()`, use `glm()` to perform logistic or poisson regression within a pipe.
Finally, the package includes the `zprint()` function, which is intended to simplify the printing of derived results, such as `summary()`, within the pipe, without affecting the modeling result itself.
| /scratch/gouwar.j/cran-all/cranData/zfit/man/include/overview.Rmd |
is.dummy <- function( v )
{
( sum( (v!=0) & (v!=1) ) == 0 ) &
( sum( v!=1 ) != 0 )
}
get.scale <- function( X )
{
s.scale <- apply( X, 2, sd )
s.scale[1] <- 1.0
for( i in 2:dim(X)[2] )
if( is.dummy( X[,i] ) )
s.scale[i] = 1.0
return( s.scale )
}
zic <- function( formula, data, a0, b0, c0, d0, e0, f0, n.burnin, n.mcmc, n.thin, tune = 1.0, scale = TRUE )
{
# unsorted data matrices
mdl <- model.frame( formula, data )
y <- model.response( mdl )
X <- model.matrix( formula, mdl )
# sort matrices
idx <- sort( y, index.return = TRUE )$ix
y <- y[idx]
X <- X[idx,]
if( scale )
{
s.scale <- get.scale( X )
X <- scale( X, center = FALSE, scale = s.scale )
}
# call C++
output <- .Call( "zic_sample",
y, X,
a0, b0, -9, -9, -9, -9, -9, e0, f0,
c0, d0, -9, -9, -9, -9, -9,
FALSE, n.burnin, n.mcmc, n.thin, tune, PACKAGE = "zic" )
output$alpha <- mcmc( output$alpha )
output$beta <- mcmc( output$beta )
output$gamma <- mcmc( output$gamma )
output$delta <- mcmc( output$delta )
output$sigma2 <- mcmc( output$sigma2 )
varnames(output$alpha) <- list( "alpha" )
varnames(output$beta) <- colnames(X)[2:dim(X)[2]]
varnames(output$gamma) <- list( "gamma" )
varnames(output$delta) <- colnames(X)[2:dim(X)[2]]
varnames(output$sigma2) <- list( "sigma2" )
if( scale )
{
output$s.scale <- s.scale[2:length(s.scale)]
}
return( output )
}
zic.svs <- function( formula, data, a0, g0.beta, h0.beta, nu0.beta, r0.beta, s0.beta, e0, f0,
c0, g0.delta, h0.delta, nu0.delta, r0.delta, s0.delta,
n.burnin, n.mcmc, n.thin, tune = 1.0, scale = TRUE )
{
# unsorted data matrices
mdl <- model.frame( formula, data )
y <- model.response( mdl )
X <- model.matrix( formula, mdl )
# sort matrices
idx <- sort( y, index.return = TRUE )$ix
y <- y[idx]
X <- X[idx,]
if( scale )
{
s.scale <- get.scale( X )
X <- scale( X, center = FALSE, scale = s.scale )
}
# call C++
output <- .Call( "zic_sample",
y, X,
a0, -9, g0.beta, h0.beta, nu0.beta, r0.beta, s0.beta, e0, f0,
c0, -9, g0.delta, h0.delta, nu0.delta, r0.delta, s0.delta,
TRUE, n.burnin, n.mcmc, n.thin, tune, PACKAGE = "zic" )
output$alpha <- mcmc( output$alpha )
output$beta <- mcmc( output$beta )
output$gamma <- mcmc( output$gamma )
output$delta <- mcmc( output$delta )
output$sigma2 <- mcmc( output$sigma2 )
output$I.beta <- mcmc( output$I.beta )
output$I.delta <- mcmc( output$I.delta )
output$omega.beta <- mcmc( output$omega.beta )
output$omega.delta <- mcmc( output$omega.delta )
varnames(output$alpha) <- list( "alpha" )
varnames(output$beta) <- colnames(X)[2:dim(X)[2]]
varnames(output$gamma) <- list( "gamma" )
varnames(output$delta) <- colnames(X)[2:dim(X)[2]]
varnames(output$sigma2) <- list( "sigma2" )
varnames(output$I.beta) <- colnames(X)[2:dim(X)[2]]
varnames(output$I.delta) <- colnames(X)[2:dim(X)[2]]
varnames(output$omega.beta) <- list( "omega.beta" )
varnames(output$omega.delta) <- list( "omega.delta" )
if( scale )
{
output$s.scale <- s.scale[2:length(s.scale)]
}
return( output )
}
| /scratch/gouwar.j/cran-all/cranData/zic/R/zic.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.