| Title: | Utility Functions for 'spatstat' |
|---|---|
| Description: | Contains utility functions for the 'spatstat' family of packages which may also be useful for other purposes. |
| Authors: | Adrian Baddeley [aut, cre] (ORCID: <https://orcid.org/0000-0001-9499-8382>), Rolf Turner [aut] (ORCID: <https://orcid.org/0000-0001-5521-5218>), Ege Rubak [aut] (ORCID: <https://orcid.org/0000-0002-6675-533X>) |
| Maintainer: | Adrian Baddeley <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 3.2-3 |
| Built: | 2026-05-10 06:04:44 UTC |
| Source: | https://github.com/spatstat/spatstat.utils |
The spatstat.utils package contains low-level utilities, written for the spatstat package, which may be useful in other packages as well.
The functions in spatstat.utils were originally written as internal, undocumented, utility functions in the spatstat package.
Many of these functions could be useful to other programmers, so we have made them available in a separate package spatstat.utils and provided documentation.
The functionality contained in spatstat.utils includes:
Find prime numbers (primesbelow),
factorise a composite number into its prime factors
(primefactors),
determine whether a number is prime (is.prime)
or whether two numbers are relatively prime
(relatively.prime),
and find the least common multiple
or greatest common divisor of two numbers
(least.common.multiple,
greatest.common.divisor).
Faster versions of some basic R tools and idioms are provided.
These are only faster in particular cases, but if you know that
your data have a particular form, the acceleration can be substantial.
See ifelseAB, fave.order,
revcumsum, tapplysum.
Use the correct word in English to refer to
an ordinal number (ordinal,
ordinalsuffix)
and the correct indefinite article
(articlebeforenumber).
The function splat is a replacement for
cat(paste(...)) which ensures that output stays
inside the declared text margin (getOption("width"))
and can also perform automatic indentation.
There are useful functions to add or remove parentheses
(paren, unparen), capitalise words
(capitalise) and
to make comma-separated lists (commasep).
Simple functions handle an interval (range) of numerical
values: check.range,
intersect.ranges,
inside.range,
check.in.range,
prange.
Tools for handling a formula in the R language include
lhs.of.formula,
rhs.of.formula,
variablesinformula,
termsinformula,
offsetsinformula,
can.be.formula and
identical.formulae.
There are tools for creating and manipulating symbolic expressions
for polynomials, as they might appear in a formula
(sympoly,
expand.polynom).
There are many tools for validating an argument and
generating a comprehensible error or warning message
if the argument is not valid:
check.1.integer,
check.nvector,
check.named.vector.
There are many tools for calling a function while passing
only some of the arguments in a supplied list of arguments:
do.call.matched, do.call.without,
resolve.defaults.
optimizeWithTrace is a simple wrapper for
the one-dimensional optimization routine
optimize. It stores the values of the
function argument each time it is called, stores the resulting
function values, and returns them along with the optimal value.
There are workarounds for known bugs or undesirable features in
other software.
spatstatLocator is a replacement for
locator which works around a bug in the
RStudio graphics interface.
cat.factor concatenates several factors,
merging the levels, to produce a new factor.
This library and its documentation are usable under the terms of the “GNU General Public License”, a copy of which is distributed with R.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
Determines the indefinite article (an or a) which should precede a given number, if the number is read out in English.
articlebeforenumber(k, teenhundreds=FALSE)articlebeforenumber(k, teenhundreds=FALSE)
k |
A single number. |
teenhundreds |
Logical value specifying that (for example) 1800 should be read as “eighteen hundred” instead of “one thousand eight hundred”. See Details. |
This function applies the rule that,
if the English language word or phrase for the number k
begins with a vowel, then it should be preceded by an,
and otherwise by a.
If teenhundreds=FALSE (the default),
the numbers 1100 and 1800 will be read as
‘one thousand one hundred’ and ‘one thousand eight hundred’,
and the indefinite article will be a.
However if teenhundreds=TRUE, the numbers 1100 and 1800
be read as ‘eleven hundred’ and ‘eighteen hundred’
and the indefinite article will be an.
One of the character strings "an" or "a".
Adrian Baddeley [email protected].
f <- function(k) cat(paste(articlebeforenumber(k), paste0(k, "-fold"), "increase\n")) f(8) f(18) f(28)f <- function(k) cat(paste(articlebeforenumber(k), paste0(k, "-fold"), "increase\n")) f(8) f(18) f(28)
Given a character string or vector of character strings containing words, change the start of each word to a capital letter.
capitalise(s, strict = FALSE)capitalise(s, strict = FALSE)
s |
Character string or vector of character strings. |
strict |
Logical. If |
Each entry of s is split into separate words separated by
the space character. Then the first letter of each word is coerced
to a capital letter using toupper, and if
strict=TRUE, subsequent letters are coerced to lower case
using tolower. Then the words are replaced in
their original positions in s.
A character string or character vector of the same length as s.
Originally documented in base R. Code copied by Adrian Baddeley [email protected].
a <- c("worKers", "of tHe", "worLd unIte") capitalise(a) capitalise(a, TRUE)a <- c("worKers", "of tHe", "worLd unIte") capitalise(a) capitalise(a, TRUE)
Combine (concatenate) several factor objects, to produce a factor.
cat.factor(...)cat.factor(...)
... |
Any number of arguments. Each argument should be a factor, or will be converted to a factor. |
The arguments ... are concatenated as they would be
using c() or cat(),
except that factor levels are retained
and merged correctly. See the Examples.
A factor, whose length is the sum of the lengths of all arguments. The levels of the resulting factor are the union of the levels of the arguments.
Rolf Turner [email protected].
c.
f <- factor(letters[1:3]) g <- factor(letters[3:5]) f g cat(f,g) c(f,g) cat.factor(f, g)f <- factor(letters[1:3]) g <- factor(letters[3:5]) f g cat(f,g) c(f,g) cat.factor(f, g)
These utility functions check whether a given argument is a single value of the required type.
check.1.real(x, context = "", fatal = TRUE, warn=TRUE) check.1.integer(x, context = "", fatal = TRUE, warn=TRUE) check.1.string(x, context = "", fatal = TRUE, warn=TRUE)check.1.real(x, context = "", fatal = TRUE, warn=TRUE) check.1.integer(x, context = "", fatal = TRUE, warn=TRUE) check.1.string(x, context = "", fatal = TRUE, warn=TRUE)
x |
The argument to be checked. |
context |
Optional string describing the context in which the argument is checked. |
fatal |
Logical value indicating whether a fatal error should occur when
|
warn |
Logical value indicating whether to issue a warning message
if |
These functions check whether the argument x is a single
atomic value of type numeric, integer or
character.
If x does have the required length and type, the result
of the function is the logical value TRUE.
Otherwise, if fatal=TRUE (the default) an error occurs,
while if fatal=FALSE a warning is issued (if warn=TRUE)
and the function returns the value FALSE.
A logical value (or an error may occur).
Adrian Baddeley [email protected].
x <- pi check.1.real(x) check.1.integer(pi, fatal=FALSE, context="In your dreams,") check.1.string(x, fatal=FALSE) check.1.integer(x, fatal=FALSE, warn=FALSE)x <- pi check.1.real(x) check.1.integer(pi, fatal=FALSE, context="In your dreams,") check.1.string(x, fatal=FALSE) check.1.integer(x, fatal=FALSE, warn=FALSE)
This is a programmer's utility function to check whether the argument is a vector or factor of the correct length.
check.anyvector(v, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, warn = FALSE, vname, oneok = FALSE)check.anyvector(v, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, warn = FALSE, vname, oneok = FALSE)
v |
The argument to be checked. |
npoints |
The required length of |
fatal |
Logical value indicating whether to stop with an error message
if |
things |
Character string describing what the entries of |
naok |
Logical value indicating whether |
warn |
Logical value indicating whether to issue a warning
if |
vname |
Character string giving the name of |
oneok |
Logical value indicating whether |
This function checks whether v is a vector or factor with
length equal to npoints (or length equal to 1 if
oneok=TRUE), not containing any NA values (unless
naok=TRUE).
If these requirements are all satisfied, the result is the logical
value TRUE.
If not, then if fatal=TRUE (the default), an error occurs;
if fatal=FALSE, the result is the logical value FALSE
with an attribute describing the requirement that was not satisfied.
A logical value indicating whether all the requirements were
satisfied. If FALSE, then this value has an attribute
"whinge", a character string describing the requirements that
were not satisfied.
Adrian Baddeley [email protected].
check.nvector,
check.nmatrix,
check.1.real, check.named.vector.
z <- factor(letters[1:10]) y <- z[1] check.anyvector(z, 5, fatal=FALSE) check.anyvector(y, 5, oneok=TRUE) check.anyvector(42, 5, fatal=FALSE)z <- factor(letters[1:10]) y <- z[1] check.anyvector(z, 5, fatal=FALSE) check.anyvector(y, 5, oneok=TRUE) check.anyvector(42, 5, fatal=FALSE)
These functions check whether the object x has
components with the required names, and does not have
any unexpected components.
check.named.vector(x, nam, context = "", namopt = character(0), onError = c("fatal", "null"), xtitle=NULL) check.named.list(x, nam, context = "", namopt = character(0), onError = c("fatal", "null"), xtitle=NULL) check.named.thing(x, nam, namopt = character(0), xtitle = NULL, valid = TRUE, type = "object", context = "", fatal = TRUE)check.named.vector(x, nam, context = "", namopt = character(0), onError = c("fatal", "null"), xtitle=NULL) check.named.list(x, nam, context = "", namopt = character(0), onError = c("fatal", "null"), xtitle=NULL) check.named.thing(x, nam, namopt = character(0), xtitle = NULL, valid = TRUE, type = "object", context = "", fatal = TRUE)
x |
The object to be checked. |
nam |
Vector of character strings giving the names of all the components which must be present. |
namopt |
Vector of character strings giving the names of components which may optionally be present. |
context |
Character string describing the context in which |
xtitle |
Optional character string to be used when referring to |
valid |
Logical value indicating whether |
type |
Character string describing the required class of objects. |
onError |
Character string indicating what to do if |
fatal |
Logical value indicating what to do if |
check.named.thing checks whether x has all the
required components, in the sense that names(x)
includes all the names in nam,
and that every entry in names(x) belongs to either nam or
namopt. If all these checks are true, the result is a
zero-length character vector. Otherwise, if fatal=TRUE (the
default), an error occurs; otherwise the result is a character
vector describing the checks which failed.
check.named.vector checks whether x is a numeric vector
and check.named.list checks whether x is a list.
They then call check.named.thing to check whether all the
required components are present. If all these checks are true, the result is
a reordered version of x in which all the compulsory entries
appear first. Otherwise, if onError="fatal" (the default)
an error occurs; otherwise the result is NULL.
check.named.vector returns a numeric vector or NULL.
check.named.list returns a list or NULL.
check.named.thing returns a character vector.
Adrian Baddeley [email protected].
z <- list(a=1, b=2, e=42) check.named.list(z, c("a", "b"), namopt=c("c", "d", "e")) check.named.thing(z, c("a", "b"), namopt=c("c", "d", "e")) zz <- unlist(z) check.named.vector(zz, c("a", "b"), namopt=c("c", "d", "e")) check.named.thing(z, c("b", "c"), namopt=c("d", "e"), fatal=FALSE)z <- list(a=1, b=2, e=42) check.named.list(z, c("a", "b"), namopt=c("c", "d", "e")) check.named.thing(z, c("a", "b"), namopt=c("c", "d", "e")) zz <- unlist(z) check.named.vector(zz, c("a", "b"), namopt=c("c", "d", "e")) check.named.thing(z, c("b", "c"), namopt=c("d", "e"), fatal=FALSE)
This is a programmer's utility function to check whether the argument is a numeric vector of the correct length.
check.nmatrix(m, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, squarematrix = TRUE, matchto = "nrow", warn = FALSE, mname)check.nmatrix(m, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, squarematrix = TRUE, matchto = "nrow", warn = FALSE, mname)
m |
The argument to be checked. |
npoints |
The required number of rows and/or columns for the matrix |
fatal |
Logical value indicating whether to stop with an error message
if |
things |
Character string describing what the rows/columns of |
naok |
Logical value indicating whether |
squarematrix |
Logical value indicating whether |
matchto |
Character string (either |
warn |
Logical value indicating whether to issue a warning
if |
mname |
Optional character string giving the name of |
This programmer's utility function checks whether m is a numeric matrix
of the correct dimensions, and checks for NA values.
If matchto="nrow" (the default) then
the number of rows of m must be equal to npoints.
If matchto="ncol" then the number of columns of m
must be equal to npoints. If squarematrix=TRUE (the
default) then the numbers of rows and columns must be equal.
If naok = FALSE (the default) then the entries of m
must not include NA.
If these requirements are all satisfied, the result is the logical
value TRUE.
If not, then if fatal=TRUE (the default), an error occurs;
if fatal=FALSE, the result is the logical value FALSE
with an attribute describing the requirement that was not satisfied.
A logical value indicating whether all the requirements were satisfied.
Adrian Baddeley [email protected].
z <- matrix(1:16, 4, 4) check.nmatrix(z, 4)z <- matrix(1:16, 4, 4) check.nmatrix(z, 4)
This is a programmer's utility function to check whether the argument is a numeric vector of the correct length.
check.nvector(v, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, warn = FALSE, vname, oneok = FALSE)check.nvector(v, npoints = NULL, fatal = TRUE, things = "data points", naok = FALSE, warn = FALSE, vname, oneok = FALSE)
v |
The argument to be checked. |
npoints |
The required length of |
fatal |
Logical value indicating whether to stop with an error message
if |
things |
Character string describing what the entries of |
naok |
Logical value indicating whether |
warn |
Logical value indicating whether to issue a warning
if |
vname |
Character string giving the name of |
oneok |
Logical value indicating whether |
This function checks whether v is a numeric vector with
length equal to npoints (or length equal to 1 if
oneok=TRUE), not containing any NA values (unless
naok=TRUE).
If these requirements are all satisfied, the result is the logical
value TRUE.
If not, then if fatal=TRUE (the default), an error occurs;
if fatal=FALSE, the result is the logical value FALSE
with an attribute describing the requirement that was not satisfied.
A logical value indicating whether all the requirements were
satisfied. If FALSE, then this value has an attribute
"whinge", a character string describing the requirements that
were not satisfied.
Adrian Baddeley [email protected].
check.anyvector,
check.nmatrix,
check.1.real, check.named.vector.
z <- 1:10 check.nvector(z, 5, fatal=FALSE) y <- 42 check.nvector(y, 5, fatal=FALSE, oneok=TRUE)z <- 1:10 check.nvector(z, 5, fatal=FALSE) y <- 42 check.nvector(y, 5, fatal=FALSE, oneok=TRUE)
These simple functions handle an interval or range of numerical
values. check.range(r) checks whether r specifies a
range of values, that is, whether r is a vector of length 2
with r[1] <= r[2]. intersect.ranges(r, s) finds the intersection
of two ranges r and s. inside.range(x, r) returns
a logical vector containing TRUE if the corresponding entry of
x falls inside the range r, and FALSE if it does
not. check.in.range(x, r) checks whether a single number
x falls inside the specified range r.
Finally prange(r) produces a character string that represents
the range r.
check.range(r, fatal = TRUE) check.in.range(x, r, fatal = TRUE) inside.range(x, r) intersect.ranges(r, s, fatal = TRUE) prange(r)check.range(r, fatal = TRUE) check.in.range(x, r, fatal = TRUE) inside.range(x, r) intersect.ranges(r, s, fatal = TRUE) prange(r)
r |
A numeric vector of length 2 specifying the endpoints of a range of values. |
x |
Numeric vector of data. |
s |
A numeric vector of length 2 specifying the endpoints of a range of values. |
fatal |
Logical value indicating whether to stop with an error message if the data do not pass the check. |
check.range checks whether r specifies a
range of values, that is, whether r is a vector of length 2
with r[1] <= r[2]. If so, the result is TRUE. If not,
then if fatal=TRUE, an error occurs, while if
fatal=FALSE the result is FALSE.
intersect.ranges(r, s) finds the intersection
of two ranges r and s. If the intersection is non-empty,
the result is a numeric vector of length 2. If the intersection is empty,
then if fatal=TRUE, an error occurs, while if
fatal=FALSE the result is NULL.
inside.range(x, r) returns
a logical vector containing TRUE if the corresponding entry of
x falls inside the range r, and FALSE if it does
not.
check.in.range(x, r) checks whether a single number
x falls inside the specified range r.
If so, the result is TRUE. If not, then if fatal=TRUE,
an error occurs, while if
fatal=FALSE the result is FALSE.
Finally prange(r) produces a character string that represents
the range r.
The result of check.range, check.in.range
and inside.range, is
a logical value or logical vector. The result of
intersect.ranges is a numerical vector of length 2, or NULL.
The result of prange is a character string.
Adrian Baddeley [email protected]
rr <- c(0, 2) ss <- c(1, 3) x <- seq(0.5, 3.5, by=1) check.range(rr) check.range(42, fatal=FALSE) inside.range(x, rr) intersect.ranges(rr, ss) prange(rr)rr <- c(0, 2) ss <- c(1, 3) x <- seq(0.5, 3.5, by=1) check.range(rr) check.range(42, fatal=FALSE) inside.range(x, rr) intersect.ranges(rr, ss) prange(rr)
Convert the elements of a vector into character strings and paste them together, separated by commas.
commasep(x, join = " and ", flatten = TRUE)commasep(x, join = " and ", flatten = TRUE)
x |
Vector of items in the list. |
join |
The string to be used to separate the last two items in the list. |
flatten |
Logical value indicating whether to return a single character string
( |
A character string (if flatten=TRUE, the default)
or a list of character strings.
Adrian Baddeley [email protected].
commasep(letters[1:4]) y <- commasep(sQuote(letters[1:4])) cat(y, fill=TRUE)commasep(letters[1:4]) y <- commasep(sQuote(letters[1:4])) cat(y, fill=TRUE)
Calculate the lagged difference of a long vector.
difflong(x, drop = TRUE)difflong(x, drop = TRUE)
x |
Numeric or integer vector. |
drop |
Logical value. See Details. |
A ‘long vector’ is a vector with more than
elements (the largest possible 32-bit integer).
Long vectors are supported in R on 64-bit computer systems.
This feature was introduced in R version 3.0.0.
Although long vectors are permitted, not all functions in R have been extended to handle long vectors.
The base R function diff currently does not handle
a long vector, and may cause the entire R
session to be terminated.
The function difflong is a temporary replacement
for diff in the simplest case:
difflong(x) is a replacement for diff(x).
If drop=TRUE (the default),
the result of difflong(x) is equivalent to diff(x),
a vector with length equal to length(x) - 1.
If drop=FALSE the result of difflong(x, FALSE) has the
same length as x; the first entry is zero, and the subsequent
entries are equivalent to diff(x).
A vector of the same type as x.
Adrian Baddeley [email protected].
x <- sample(1:5) diff(x) difflong(x)x <- sample(1:5) diff(x) difflong(x)
Call a specified function, using only those arguments which are known to be acceptable to the function.
do.call.matched(fun, arglist, funargs, extrargs = NULL, matchfirst = FALSE, sieve = FALSE, skipargs = NULL, envir=parent.frame())do.call.matched(fun, arglist, funargs, extrargs = NULL, matchfirst = FALSE, sieve = FALSE, skipargs = NULL, envir=parent.frame())
fun |
A function, or a character string giving the name of a function, to be called. |
arglist |
A named list of arguments. |
funargs |
Character vector giving the names of arguments that are recognised
by |
extrargs |
Optional. Character vector giving the names of additional arguments
that can be handled by |
skipargs |
Optional. Character vector giving the names of arguments which should
not be passed to |
matchfirst |
Logical value indicating whether the first entry
of |
sieve |
Logical value indicating whether to return the un-used arguments as well as the result of the function call. See Details. |
envir |
An environment within which to evaluate the call,
if any entries of |
This function is a wrapper for do.call
which avoids passing arguments that are unrecognised by fun.
In the simplest case do.call.matched(fun, arglist)
is like do.call(fun, arglist), except that
entries of arglist which do not match any formal
argument of fun are removed.
Extra argument names can be permitted using extrargs,
and argument names can be forbidden using skipargs.
If sieve=FALSE (the default), the result is the
return value from fun.
If sieve=TRUE, the result is a list with entries
result (the return value from fun) and
otherargs (a list of the arguments that were not passed
to fun).
Adrian Baddeley [email protected]
resolve.defaults,
do.call.without.
f <- function(x=0,y=0, ...) { paste(x, y, ..., sep=", ") } f() do.call.matched(f, list(y=2)) do.call.matched(f, list(y=2, z=5), extrargs="z") do.call.matched(f, list(y=2, z=5), extrargs="z", skipargs="y")f <- function(x=0,y=0, ...) { paste(x, y, ..., sep=", ") } f() do.call.matched(f, list(y=2)) do.call.matched(f, list(y=2, z=5), extrargs="z") do.call.matched(f, list(y=2, z=5), extrargs="z", skipargs="y")
Call a specified function, omitting some arguments which are inappropriate to the function.
do.call.without(fun, ..., avoid, envir=parent.frame())do.call.without(fun, ..., avoid, envir=parent.frame())
fun |
The function to be called. A function name, a character string giving the name of the function, or an expression that yields a function. |
... |
Any number of arguments. |
avoid |
Vector of character strings, giving the names of arguments that should
not be passed to |
envir |
An environment within which to evaluate the call,
if any entries of |
This is a simple mechanism for preventing some arguments from being
passed in a function call. The arguments ... are collected in
a list. A argument is omitted if its name exactly matches
one of the strings in avoid.
The return value of fun.
Adrian Baddeley [email protected].
do.call.matched for a more complicated and flexible call.
do.call.without(paste, 1, 2, z=3, w=4, avoid="z")do.call.without(paste, 1, 2, z=3, w=4, avoid="z")
Determines whether the entries in a numeric vector are evenly spaced and increasing.
evenly.spaced(x, tol = 1e-07)evenly.spaced(x, tol = 1e-07)
x |
Numeric vector. |
tol |
Relative tolerance. |
The result is TRUE if x is an increasing sequence
in which the successive differences diff(x)
are all equal to one another (within the specified relative tolerance),
and FALSE otherwise.
A single logical value.
Adrian Baddeley [email protected].
evenly.spaced(seq(0, 1, length=4))evenly.spaced(seq(0, 1, length=4))
Computes the numerical breakpoints used by cut.default.
exactCutBreaks(x, breaks)exactCutBreaks(x, breaks)
x |
Numeric vector which would be converted to a factor. |
breaks |
Either a numeric vector of breakpoints,
or a single integer giving the number of intervals into which
|
This function contains a copy of the code in
cut.default which determines the
numerical breakpoints used to convert x to a factor.
It returns the breakpoints only.
The arguments x and breaks have the same interpretation
as in cut.default. Only the range of x
is used in the computation, so x could be replaced by range(x).
This function would normally be used when breaks is a single
integer specifying the number of intervals for the cut operation.
It returns the exact numerical values of the breakpoints which are
determined, but not returned, by cut.default).
Numeric vector.
Adrian Baddeley [email protected].
exactCutBreaks(c(0,1), 4)exactCutBreaks(c(0,1), 4)
Create a formula representing a polynomial, or expand polynomials in an existing formula.
expand.polynom(f) sympoly(x, y, n)expand.polynom(f) sympoly(x, y, n)
f |
A formula. |
x, y
|
Variable names. |
n |
Integer specifying the degree of the polynomial.
(If |
These functions expand a polynomial into its homogeneous terms and return a model formula.
sympoly(x, n) creates a formula whose right-hand side represents the
polynomial of degree n in the variable x. Each
homogeneous term x^k is a separate term in the formula.
sympoly(x, y, n) creates a formula representing the
polynomial of degree n in the two variables x and
y.
If f is a formula containing a term of the form
polynom(...) then expand.polynom(f) replaces this term
by its expansion as a sum of homogeneous terms, as defined in
the help for polynom.
A formula.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
sympoly(A, 4) sympoly(A, B, 3) expand.polynom(U ~ A + polynom(B, 2))sympoly(A, 4) sympoly(A, B, 3) expand.polynom(U ~ A + polynom(B, 2))
A faster alternative to findInterval
for intervals which are equally-spaced.
fastFindInterval(x, b, labels = FALSE, reltol = 0.001, dig.lab = 3L, left.open=TRUE)fastFindInterval(x, b, labels = FALSE, reltol = 0.001, dig.lab = 3L, left.open=TRUE)
x |
Data. Numeric vector of values that are to be classified. |
b |
Breakpoints. Numeric vector of increasing values that are the endpoints of the intervals. |
labels |
Logical value specifying whether to return a factor, whose levels are the string labels of the intervals. |
reltol |
Relative tolerance. A positive number. |
dig.lab |
Integer. Maximum number of digits to use in the labels
for the intervals, when |
left.open |
Logical value specifying whether intervals are left-open and
right-closed ( |
This is an alternative to
findInterval(x, b, rightmost.closed=TRUE)
which seems to be faster when b is equally spaced
and the length of x is large.
If labels=FALSE (the default), the result is an integer vector
giving, for each value x[i], the index j of the interval that
contains x[i]:
If left.open=TRUE (the default), the intervals are left-open
and right-closed, except for the first interval. This means that
x[i] belongs to the jth interval if
b[j] < x[i] <= b[j+1] for j > 1
and b[1] <= x[i] <= b[2] for j=1.
If left.open=FALSE, the intervals are left-closed
and right-open, except for the last interval. This means that
x[i] belongs to the jth interval if
b[j] <= x[i] < b[j+1] for j < m
and b[m] <= x[i] <= b[m+1] for j=m
where m = length(b)-1 is the number of intervals.
If labels=TRUE, the result is a factor, and the levels are
synthetic labels for the intervals, similar to those produced by
findInterval.
Note that the default value of left.open
is TRUE for fastFindInterval
but FALSE for findInterval.
Integer vector, or factor.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
x <- runif(10) b <- seq(0, 1, by=0.2) fastFindInterval(x, b, labels=TRUE)x <- runif(10) b <- seq(0, 1, by=0.2) fastFindInterval(x, b, labels=TRUE)
Generate a geometric sequence between two endpoints. The sequence is equally spaced on a logarithmic scale.
geomseq(from, to, length.out)geomseq(from, to, length.out)
from |
Starting value. A positive number. |
to |
Ending value. A positive number. |
length.out |
Number of elements in the sequence. A positive integer. |
This is a wrapper for seq.default which generates
a geometric sequence between the two endpoints.
Numeric vector.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
geomseq(1, 32, length.out=6)geomseq(1, 32, length.out=6)
Calculates the harmonic mean of a numeric vector, robustly handling special cases.
harmonicmean(x, na.rm = TRUE) harmonicsum(x, na.rm = TRUE)harmonicmean(x, na.rm = TRUE) harmonicsum(x, na.rm = TRUE)
x |
Numeric vector. |
na.rm |
Logical value specifying whether to remove |
The harmonic mean of a set of numbers is the reciprocal of the mean of the reciprocals of the numbers.
The function harmonicmean calculates the harmonic mean
of x. The algorithm robustly handles special cases
where some of the values in x are very small or are
exactly equal to zero.
The function harmonicsum calculates the reciprocal of the
sum of the reciprocals of the x values.
A single numeric value.
Adrian Baddeley [email protected].
harmonicmean(1:3)harmonicmean(1:3)
These low-level functions provide faster alternatives to
some uses of ifelse.
ifelseAB(test, a, b) ifelseAX(test, a, x) ifelseXB(test, x, b) ifelseXY(test, x, y) ifelseNegPos(test, x) ifelse0NA(test) ifelse1NA(test)ifelseAB(test, a, b) ifelseAX(test, a, x) ifelseXB(test, x, b) ifelseXY(test, x, y) ifelseNegPos(test, x) ifelse0NA(test) ifelse1NA(test)
test |
A logical vector. |
a |
A single atomic value. |
b |
A single atomic value. |
x |
A vector of values, of the same length as |
y |
A vector of values, of the same length as |
These low-level functions provide faster alternatives to
some uses of ifelse. They were developed by
trial-and-error comparison of computation times of different expressions.
ifelse0NA(test) is equivalent to ifelse(test, 0, NA).
ifelse1NA(test) is equivalent to ifelse(test, 1, NA).
ifelseAB(test, a, b) is equivalent to ifelse(test, a, b)
where a and b must be single values.
ifelseAX(test, a, x) is equivalent to ifelse(test, a, x)
where a must be a single value, and x a vector of the
same length as test.
ifelseXB(test, x, b) is equivalent to ifelse(test, x, b)
where b must be a single value, and x a vector of the
same length as test.
ifelseXY(test, x, y) is equivalent to ifelse(test, x, y)
where x and y must be vectors of the
same length as test.
ifelseNegPos(test, x) is equivalent to ifelse(test, x, -x)
where x must be a vector of the same length as test.
A vector of the same length as test containing values of the
same type as a,b,x,y.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
x <- runif(4e5) u <- (x < 0.5) system.time(ifelse(u, 2, x)) system.time(ifelseAX(u, 2, x))x <- runif(4e5) u <- (x < 0.5) system.time(ifelse(u, 2, x)) system.time(ifelseAX(u, 2, x))
Determine whether the given integer is a square number, a cube number, or a power of an integer.
is.square(n) is.cube(n) is.power(n)is.square(n) is.cube(n) is.power(n)
n |
A single integer. |
is.square(n) returns TRUE if n
is a square number, that is, n = m^2 for some integer m,
and returns FALSE otherwise.
is.cube(n) returns TRUE if n
is the cube of an integer, n = m^3 for some integer m,
and returns FALSE otherwise.
is.power(n) returns TRUE if n
is an integer power of an integer, n = m^k for some integers
m and k, and returns FALSE otherwise.
These functions use the prime factorisation of n
and may be more reliable than testing where sqrt(n) is an
integer, etc.
Negative values of n are permitted.
A single logical value.
Adrian Baddeley [email protected].
is.square(9) is.cube(9) is.cube(27) is.cube(-27) is.power(27) is.power(3^5)is.square(9) is.cube(9) is.cube(27) is.cube(-27) is.power(27) is.power(3^5)
Compute the area or boundary length of a polygon, determine whether a point falls inside a polygon, compute the area of overlap between two polygons, and related tasks.
verify.xypolygon(p, fatal = TRUE) is.hole.xypolygon(polly) Area.xypolygon(polly) bdrylength.xypolygon(polly) reverse.xypolygon(p, adjust=FALSE) overlap.xypolygon(P, Q) simplify.xypolygon(p, dmin) inside.xypolygon(pts, polly, test01, method)verify.xypolygon(p, fatal = TRUE) is.hole.xypolygon(polly) Area.xypolygon(polly) bdrylength.xypolygon(polly) reverse.xypolygon(p, adjust=FALSE) overlap.xypolygon(P, Q) simplify.xypolygon(p, dmin) inside.xypolygon(pts, polly, test01, method)
p, polly, P, Q
|
Data representing a polygon. See Details. |
dmin |
Single numeric value giving the minimum permissible length of an edge in the simplified polygon. |
fatal |
Logical value indicating whether failure is a fatal error. |
pts |
Coordinates of points to be tested.
A named list with entries |
adjust |
Logical value indicating whether internal data should be adjusted. See Details. |
test01, method
|
For developer use only. |
In the spatstat family of packages, a polygon in the Euclidean plane is represented as a named list with the following entries:
x,y
Numeric vectors giving the coordinates of the vertices. The vertices should be traversed in anti-clockwise order (unless the polygon is a hole, when they should be traversed in clockwise order) and the last vertex should not repeat the first vertex.
Optional. A logical value indicating whether the polygon is a hole.
Optional. Single numeric value giving the area of the polygon (negative if it is a hole).
The function verify.xypolygon checks whether its argument
satisfies this format. If so, it returns TRUE; if not,
it returns FALSE or (if fatal=TRUE) generates a fatal error.
The other functions listed here perform basic calculations for polygons using elementary Cartesian analytic geometry in R.
is.hole.xypolygon determines whether a polygon is a hole or not.
Area.xypolygon computes the area of the polygon using the
discrete Green's formula.
bdrylength.xypolygon calculates the total length of edges
of the polygon.
reverse.xypolygon reverses the order of the
coordinate vectors x and y. If adjust=TRUE,
the other entries hole and area will be adjusted as well.
overlap.xypolygon computes the area of overlap between two
polygons using the discrete Green's formula. It is slow compared
to the code in the polyclip package.
simplify.xypolygon removes vertices of the polygon until
every edge is longer than dmin.
inside.xypolygon(pts, polly) determines whether each point
in pts lies inside the polygon polly and returns a
logical vector.
verify.xypolygon and
is.hole.xypolygon return a single logical value.
inside.xypolygon returns a logical vector.
Area.xypolygon, bdrylength.xypolygon
and overlap.xypolygon
return a single numeric value.
reverse.xypolygon and simplify.xypolygon
return another polygon object.
Adrian Baddeley [email protected].
p <- list(x=c(0,1,4,2), y=c(0,0,2,3)) is.hole.xypolygon(p) Area.xypolygon(p) bdrylength.xypolygon(p) overlap.xypolygon(p, list(x=p$x+1, y=p$y+1)) reverse.xypolygon(p) plot(c(0,5),c(0,3),type="n",xlab="x", ylab="y") polygon(p) polygon(simplify.xypolygon(p, 1.1), lty=3) plot(c(0,5),c(0,3),type="n",xlab="x", ylab="y") polygon(p) xx <- runif(10, max=5) yy <- runif(10, max=3) points(xx, yy) ok <- as.logical(inside.xypolygon(list(x=xx, y=yy), p)) points(xx[ok], yy[ok], pch=16)p <- list(x=c(0,1,4,2), y=c(0,0,2,3)) is.hole.xypolygon(p) Area.xypolygon(p) bdrylength.xypolygon(p) overlap.xypolygon(p, list(x=p$x+1, y=p$y+1)) reverse.xypolygon(p) plot(c(0,5),c(0,3),type="n",xlab="x", ylab="y") polygon(p) polygon(simplify.xypolygon(p, 1.1), lty=3) plot(c(0,5),c(0,3),type="n",xlab="x", ylab="y") polygon(p) xx <- runif(10, max=5) yy <- runif(10, max=3) points(xx, yy) ok <- as.logical(inside.xypolygon(list(x=xx, y=yy), p)) points(xx[ok], yy[ok], pch=16)
Find the minimum or maximum of a function over an interval of real numbers, keeping track of the function arguments and function values that were evaluated.
optimizeWithTrace(f, interval, ..., lower = min(interval), upper = max(interval))optimizeWithTrace(f, interval, ..., lower = min(interval), upper = max(interval))
f |
The function to be minimized or maximized. |
interval |
Numeric vector of length 2 containing the end-points of the interval to be searched. |
lower, upper
|
The lower and upper endpoints of the interval to be searched. |
... |
Other arguments passed to |
This is a simple wrapper for the optimization routine
optimize. The function f will be
optimized by computing its value at several locations in the interval,
as described in the help for optimize.
This wrapper function stores the locations and
resulting function values, and returns them along with the
result of the optimization.
A list with components
minimum (or maximum), the location in the
search interval which yielded the optimum value;
objective, the value of the function at this
location;
x, the sequence of locations in the interval that
were considered (in the order considered);
y, the function values corresponding to x.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
f <- function (x, a) (x - a)^2 result <- optimizeWithTrace(f, c(0, 1), tol = 0.0001, a = 1/3) result curve(f(x, 1/3)) with(result, points(x, y, pch=16))f <- function (x, a) (x - a)^2 result <- optimizeWithTrace(f, c(0, 1), tol = 0.0001, a = 1/3) result curve(f(x, 1/3)) with(result, points(x, y, pch=16))
Compute the k-th smallest value in a dataset,
or find which entry in a dataset is the k-th smallest.
orderstats(x, k, decreasing = FALSE) orderwhich(x, k, decreasing = FALSE)orderstats(x, k, decreasing = FALSE) orderwhich(x, k, decreasing = FALSE)
x |
Data whose order statistics will be computed. A numeric vector. |
k |
Rank. An integer, or vector of integers. |
decreasing |
Logical value specifing whether a rank of 1
is assigned to the highest value ( |
These are low-level functions for efficiently computing order statistics:
orderstats(x, k) returns the k-th smallest value in x,
and orderwhich(x, k) returns the position of the
k-th smallest value in x.
Given a dataset of values ,
the order statistic of rank is the -th smallest
value in the dataset. The order statistic of rank 1 is the smallest
value, and the order statistic of rank is the largest value.
The order statistic of rank is denoted .
The full sequence of order statistics
can simply be obtained by sorting the original values into increasing order.
The command orderstats(x, k) is equivalent to
sort(x)[k]; it calculates the
k-th smallest value in x.
The command orderwhich(x, k) is equivalent to
order(x)[k]. It identifies the position of the
k-th smallest value in x, that is, it returns the
index j such that x[j] is the k-th smallest value
in x.
The functions orderstats and orderwhich are more
efficient than using sort and order
when it is only desired to calculate a few of the
order statistics (for example, only the smallest and second-smallest
values in the dataset).
orderstats returns a vector of the same kind as x,
with the same length as k.
orderwhich returns an integer vector
with the same length as k.
Adrian Baddeley [email protected].
x <- runif(10) orderstats(x, 2) sort(x)[2] orderwhich(x, 2:3) order(x)[2:3]x <- runif(10) orderstats(x, 2) sort(x)[2] orderwhich(x, 2:3) order(x)[2:3]
Returns the appropriate abbreviation in English for an ordinal number
(for example ordinal(5) is "5th").
ordinal(k) ordinalsuffix(k)ordinal(k) ordinalsuffix(k)
k |
An integer or vector of integers. |
ordinal(k) returns a character string representing the
kth ordinal number. ordinalsuffix(k) determines the
appropriate suffix.
The suffix can be either "st" (abbreviating
first), "nd" (abbreviating second),
"rd" (abbreviating third) or
"th" (for all other ordinal numbers fourth,
fifth, etc).
A character string or character vector of the same length as k.
Adrian Baddeley [email protected].
ordinal(1:7) cat(paste("Happy", ordinal(21), "Birthday"), fill=TRUE)ordinal(1:7) cat(paste("Happy", ordinal(21), "Birthday"), fill=TRUE)
Specify a value together with a default to be used when the first value is null.
a %orifnull% ba %orifnull% b
a |
Any kind of object or expression to be evaluated. |
b |
Default value to be used when |
The operator %orifnull% is designed to improve the
readability of code.
a %orifnull% b is equivalent to if(!is.null(a)) a else b.
That is, a %orifnull% b is equal to
a provided a is not null, and otherwise
the result is equal to b.
Expressions are evaluated only when necessary.
If a is a language expression, it is first evaluated. Then if
is.null(a) is FALSE, the result is a. Otherwise,
b is evaluated, and the result is b.
Note that b is not evaluated unless a is NULL.
The operator %orifnull% has higher precedence than the arithmetic
operators +, -, *, / but lower precedence than ^.
The operator is associative, and can be used repeatedly in an expression, so that a default value may have its own default. See the Examples.
The result is a if a is not NULL,
and otherwise the result is b.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected]
x <- 7 y <- 42 z <- w <- NULL x %orifnull% y z %orifnull% y z %orifnull% x %orifnull% y z %orifnull% w %orifnull% yx <- 7 y <- 42 z <- w <- NULL x %orifnull% y z %orifnull% y z %orifnull% x %orifnull% y z %orifnull% w %orifnull% y
Add or remove enclosing parentheses around a string.
paren(x, type = "(") unparen(x)paren(x, type = "(") unparen(x)
x |
A character string, or vector of character strings. |
type |
Type of parentheses: either |
paren(x) adds enclosing parentheses to the beginning and end of
the string x.
unparen(x) removes enclosing parentheses if they are present.
A character string, or vector of character strings of the same length
as x.
Adrian Baddeley [email protected].
paren("Hello world") paren(42, "[") paren(letters[1:10]) unparen(c("(yes)", "[no]", "{42}"))paren("Hello world") paren(42, "[") paren(letters[1:10]) unparen(c("(yes)", "[no]", "{42}"))
This is a programmer's utility which converts a fraction to a percentage and encodes the percentage as a character string.
percentage(x, digits = 3)percentage(x, digits = 3)
x |
Either a single number, or a logical vector. |
digits |
Number of digits accuracy. |
If x is a single number, it should be a fraction between 0 and 1.
It will be converted to a percentage and then converted to a character
string followed by the percentage symbol.
If x is a logical vector, the fraction of values which are
TRUE will be computed, and used to determine the percentage.
A character string.
Adrian Baddeley [email protected]
percentage(1/3) percentage(runif(20) > 0.2)percentage(1/3) percentage(runif(20) > 0.2)
These functions find prime numbers, factorise a composite number into its prime factors, determine whether a number is prime, and find the least common multiple or greatest common divisor of two numbers.
primefactors(n, method=c("C", "interpreted")) divisors(n) is.prime(n) relatively.prime(n, m) least.common.multiple(n,m) greatest.common.divisor(n,m) primesbelow(nmax)primefactors(n, method=c("C", "interpreted")) divisors(n) is.prime(n) relatively.prime(n, m) least.common.multiple(n,m) greatest.common.divisor(n,m) primesbelow(nmax)
n, m
|
Integers to be factorized. |
nmax |
Integer. Upper limit on prime numbers to be found. |
method |
Character string indicating the choice of algorithm. (Developer use only.) |
is.prime(n) returns TRUE if n is a prime number,
and FALSE otherwise.
primefactors(n) factorises the integer n
into its prime number factors, and returns an integer vector
containing these factors. Some factors may be repeated.
divisors(n) finds all the integers which divide
the integer n, and returns them as a sorted vector of integers
(beginning with 1 and ending with n).
relatively.prime(n, m) returns TRUE if the integers
n and m are relatively prime, that is, if they have no
common factors.
least.common.multiple and greatest.common.divisor
return the least common multiple or greatest common divisor of two
integers n and m.
primesbelow(nmax) returns an integer vector containing all the
prime numbers less than or equal to nmax.
is.prime and relatively.prime return a logical value.
least.common.multiple and greatest.common.divisor
return a single integer.
primefactors and primesbelow
return an integer vector.
Adrian Baddeley [email protected].
is.prime(17) is.prime(399137) relatively.prime(2, 3) primefactors(24) ## Note repeated factors primefactors(713291035) divisors(24) greatest.common.divisor(60, 100) least.common.multiple(10, 15) primesbelow(20)is.prime(17) is.prime(399137) relatively.prime(2, 3) primefactors(24) ## Note repeated factors primefactors(713291035) divisors(24) greatest.common.divisor(60, 100) least.common.multiple(10, 15) primesbelow(20)
Add the coordinates of a spatial location to a queue.
The queue can be accessed by the spatstatLocator function
in a non-interactive session.
queueSpatstatLocator(x, y)queueSpatstatLocator(x, y)
x, y
|
Numeric values, or vectors of the same length,
containing spatial coordinates. Any data acceptable to
|
The spatstatLocator function is a replacement
for the locator function
that can be used to test software which depends on user input.
When queueSpatstatLocator(x,y) is called, the coordinate
data x,y are saved in a queue. The first-listed coordinate
pair x[1], y[1] is at the front of the queue. Subsequently, when
spatstatLocator is called, the coordinates are
taken from the front of the queue and returned as if they had been
clicked by the user.
This only works in a non-interactive
session, that is, when interactive() returns FALSE.
Integer (invisible). The length of the queue, after inclusion of the new points.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
queueSpatstatLocator(0.5, 0.7) queueSpatstatLocator(c(0.3, 0.4), c(0.2, 0.9)) if(!interactive()) { spatstatLocator(2) spatstatLocator(1) }queueSpatstatLocator(0.5, 0.7) queueSpatstatLocator(c(0.3, 0.4), c(0.2, 0.9)) if(!interactive()) { spatstatLocator(2) spatstatLocator(1) }
Given any data x, these functions return
the missing value NA, the empty vector, or the
equivalent of the number 0,
with the same type as x.
RelevantZero(x) RelevantNA(x) RelevantEmpty(x) isRelevantZero(x)RelevantZero(x) RelevantNA(x) RelevantEmpty(x) isRelevantZero(x)
x |
Data of any type. |
In the R system, missing values may have different types. For example, if an entry is missing from a numeric vector, it is a missing numeric value, not a missing logical value, and R distinguishes between these two types of missing values.
The function RelevantNA returns a missing value of the same
type as the input x (as defined by typeof).
Thus, RelevantNA(3.2) returns a missing numeric value
and RelevantNA(TRUE) returns a missing logical value.
RelevantEmpty(x) returns a vector of length zero which has the
same type as x. Thus, RelevantEmpty(TRUE) is equivalent
to logical(0).
RelevantZero(x) returns a single value, of the same type as
x, that is equivalent to the number zero. For example,
RelevantZero(TRUE) returns FALSE.
The function isRelevantZero tests whether x is a single
zero value, by testing whether x is identical to
RelevantZero(x).
RelevantZero and RelevantNA return a single value
of the same type as x.
RelevantEmpty returns a zero-length vector of the same type
as x.
isRelevantZero returns a single logical value.
Adrian Baddeley [email protected].
RelevantZero(42) RelevantZero(TRUE) RelevantZero("hello world") RelevantNA(1:3) typeof(RelevantNA(1:3)) typeof(RelevantNA("hello world"))RelevantZero(42) RelevantZero(TRUE) RelevantZero("hello world") RelevantNA(1:3) typeof(RelevantNA(1:3)) typeof(RelevantNA("hello world"))
Determine the values of variables by applying several different default rules in a given order.
resolve.defaults(..., .MatchNull = TRUE, .StripNull = FALSE) resolve.1.default(.A, ...)resolve.defaults(..., .MatchNull = TRUE, .StripNull = FALSE) resolve.1.default(.A, ...)
... |
Several lists of |
.MatchNull |
Logical value. If |
.StripNull |
Logical value indicating whether
entries of the form |
.A |
Either a character string giving the name of the variable
to be extracted, or a list consisting of one |
These functions determine the values of variables by applying a series of default rules, in the order specified.
Each of the arguments ... should be a list of
name=value pairs giving a value
for a variable name. Each list could represent a
set of arguments given by the user, or a
rule assigning default values to some variables.
Lists that appear earlier in the sequence of arguments ...
take precedence.
The arguments ... will be concatenated into a single list.
The earliest occurrence of each name is then used to
determine the final value of the variable name.
The function resolve.defaults returns a list of
name=value pairs for all variables encountered.
It is commonly used to decide the values of
arguments to be passed to another function
using do.call.
The function resolve.1.default returns the value
of the specified variable as determined by resolve.defaults.
It is commonly used inside a function to determine the value
of an argument.
The result of resolve.defaults is
a list of name=value pairs.
The result of resolve.1.default can be any kind of value.
Adrian Baddeley [email protected]
user <- list(day="Friday") ruleA <- list(month="Jan", gravity=NULL) ruleB <- list(day="Tuesday", month="May", gravity=42) resolve.defaults(user, ruleA, ruleB) resolve.defaults(user, ruleA, ruleB, .StripNull=TRUE) resolve.defaults(user, ruleA, ruleB, .MatchNull=FALSE) resolve.1.default("month", user, ruleA, ruleB)user <- list(day="Friday") ruleA <- list(month="Jan", gravity=NULL) ruleB <- list(day="Tuesday", month="May", gravity=42) resolve.defaults(user, ruleA, ruleB) resolve.defaults(user, ruleA, ruleB, .StripNull=TRUE) resolve.defaults(user, ruleA, ruleB, .MatchNull=FALSE) resolve.1.default("month", user, ruleA, ruleB)
Returns a vector of cumulative sums of the input values,
running in reverse order. That is, the ith entry in the output
is the sum of entries i to n in the input,
where n is the length of the input.
revcumsum(x)revcumsum(x)
x |
A numeric, logical or complex vector. |
This low-level utility function is a faster alternative to
rev(cumsum(rev(x)))
under certain conditions.
It computes the reverse cumulative sum of the entries of x.
If y <- revcumsum(x), then y[i] = sum(x[i:n]) where
n = length(x).
This function should not be used if x could contain NA
values: this would lead to an error.
A vector of the same length and type as x
(except that if x is logical then the result is an integer vector).
Adrian Baddeley [email protected].
revcumsum(1:5) rev(cumsum(rev(1:5))) x <- runif(1e6) system.time(rev(cumsum(rev(x)))) system.time(revcumsum(x))revcumsum(1:5) rev(cumsum(rev(1:5))) x <- runif(1e6) system.time(rev(cumsum(rev(x)))) system.time(revcumsum(x))
Given a numeric value, try to express it as a simple rational number.
simplenumber(x, unit = "", multiply = "*", tol = .Machine$double.eps)simplenumber(x, unit = "", multiply = "*", tol = .Machine$double.eps)
x |
A single numeric value. |
unit |
Optional. Character string giving the name of the unit
in which |
multiply |
Optional. Character string representing multiplication. |
tol |
Numerical tolerance. |
The code tries to express x as an integer x=n, or as
the reciprocal of an integer x=1/n, or
as a simple rational number x = m/n, where m,n are
small integers.
A character string representing the simple number,
or NULL if not successful.
Adrian Baddeley [email protected].
simplenumber(0.3) simplenumber(0.333333333333333333333333) x <- pi * 2/3 simplenumber(x/pi, "pi")simplenumber(0.3) simplenumber(0.333333333333333333333333) x <- pi * 2/3 simplenumber(x/pi, "pi")
Deprecated functions of the spatstat.utils package.
equispaced(z, reltol=0.001)equispaced(z, reltol=0.001)
z |
Numeric vector. |
reltol |
Numeric value for relative tolerance. |
equispaced has been replaced by evenly.spaced.
This is an alternative to the locator
function. It contains a workaround for a bug that occurs in
RStudio.
spatstatLocator(n, type = c("p", "l", "o", "n"), ..., snap.step=NULL, snap.origin=c(0,0))spatstatLocator(n, type = c("p", "l", "o", "n"), ..., snap.step=NULL, snap.origin=c(0,0))
n |
Optional. Maximum number of points to locate. |
type |
Character specifying how to plot the locations.
If |
... |
Additional graphics parameters used to plot the locations. |
snap.step |
Optional. Spatial coordinates will be rounded to the nearest
multiple of |
snap.origin |
Optional. Numeric vector of length 2. Coordinates of the origin that will be used when rounding coordinates. |
This is a replacement/workaround for the locator
function in some versions of RStudio which do not seem to
recognise the option type="p".
See locator for a description of the
behaviour.
If snap.step is given, then the coordinates of the selected
locations will be rounded to the nearest multiple of snap.step.
A list containing components x and y which are vectors
giving the coordinates of the identified points in the
user coordinate system, i.e., the one specified by par("usr").
Programmers may like to know that
code which depends on spatstatLocator
can be tested in a non-interactive session,
if the coordinates are previously queued using
queueSpatstatLocator.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
if(interactive()) locator(1, type="p")if(interactive()) locator(1, type="p")
Prints a given character string or strings
inside the text margin specified by options("width").
Indents the text if required.
splat(..., indent = 0)splat(..., indent = 0)
... |
Character strings, or other arguments acceptable to
|
indent |
Optional. Indentation of the text. Either an integer specifying the number of character positions by which the text should be indented, or a character string whose length determines the indentation. |
splat stands for ‘split cat’.
The command splat(...) is like cat(paste(...))
except that the output will be split into lines that can be
printed within the current text margin
specified by getOption("width").
The arguments ... are first combined into a character vector
using paste. Then they are split into words
separated by white space. A newline will be inserted whenever the next
word does not fit in the available text area.
(Words will not be broken, so the text margin could be exceeded
if any word is longer than getOption("width")).
If any argument is a vector, each
element of the vector is treated as a separate line.
Existing newline characters in ... are also respected.
Null.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
op <- options(width=20) splat("There is more than one way to skin a cat.") splat("There is more than one", "way to skin a cat.", indent=5) options(width=10) splat("The value of pi is", pi) splat("The value of pi is", signif(pi)) options(op)op <- options(width=20) splat("There is more than one way to skin a cat.") splat("There is more than one", "way to skin a cat.", indent=5) options(width=10) splat("The value of pi is", pi) splat("The value of pi is", signif(pi)) options(op)
Computes a function that tapers smoothly from 0 to 1.
taperoff(x, zeropoint = 0, onepoint = 1, type = c("smooth", "cosine", "Gaussian"))taperoff(x, zeropoint = 0, onepoint = 1, type = c("smooth", "cosine", "Gaussian"))
x |
Function argument. A number or a numeric vector. |
zeropoint |
Value of |
onepoint |
Value of |
type |
Character string (partially matched) specifying which taper function to use. |
A taper is a mathematical function that exhibits a gradual transition between the values 0 and 1.
By default, the function value is equal to 0
if , is equal to 1 if ,
and lies between 0 and 1 when .
If type="cosine", the function is the cosine taper
.
If type="smooth" the function is the smooth partition of unity
where .
If type="Gaussian" the function is the cumulative distribution
function of the Gaussian (normal) distribution with mean
and standard deviation .
If zeropoint and onepoint are specified, then
the function value is equal to 0 when
x=zeropoint, equal to 1 when x=onepoint, and lies
between 0 and 1 when x lies between zeropoint and
onepoint.
A numeric vector of the same length as x.
Adrian Baddeley
curve(taperoff(x, type="smooth")) curve(taperoff(x, type="cosine"), add=TRUE, col="green") curve(taperoff(x, type="Gaussian"), add=TRUE, col="blue")curve(taperoff(x, type="smooth")) curve(taperoff(x, type="cosine"), add=TRUE, col="green") curve(taperoff(x, type="Gaussian"), add=TRUE, col="blue")
A faster equivalent of tapply(FUN=sum).
tapplysum(x, flist, do.names = FALSE, na.rm = TRUE)tapplysum(x, flist, do.names = FALSE, na.rm = TRUE)
x |
Vector of numeric or complex values. |
flist |
A list of |
do.names |
Logical value indicating whether to attach names to the result. |
na.rm |
Logical value indicating whether to remove |
This function is designed to be a faster alternative to
the idiom y <- tapply(x, flist, sum); y[is.na(y)] <- 0.
The result y is a vector, matrix or array of
dimension equal to the number of factors in flist. Each
position in y represents one of the possible combinations
of the factor levels. The resulting value in this position
is the sum of all entries of x
where the factors in flist take this particular combination of
values. The sum is zero if this combination does not occur.
Currently this is implemented for the cases where flist
has length 1, 2 or 3 (resulting in a vector, matrix or 3D array,
respectively).
For other cases we fall back on tapply.
A numeric vector, matrix or array.
Adrian Baddeley [email protected] and Tilman Davies.
x <- 1:12 a <- factor(rep(LETTERS[1:2], each=6)) b <- factor(rep(letters[1:4], times=3)) ff <- list(a, b) tapply(x, ff, sum) tapplysum(x, ff, do.names=TRUE) tapplysum(x + 2i, ff, do.names=TRUE)x <- 1:12 a <- factor(rep(LETTERS[1:2], each=6)) b <- factor(rep(letters[1:4], times=3)) ff <- list(a, b) tapply(x, ff, sum) tapplysum(x, ff, do.names=TRUE) tapplysum(x + 2i, ff, do.names=TRUE)
Operations for manipulating formulae.
termsinformula(x) variablesinformula(x) offsetsinformula(x) lhs.of.formula(x) rhs.of.formula(x, tilde=TRUE) lhs.of.formula(x) <- value rhs.of.formula(x) <- value can.be.formula(x) identical.formulae(x,y)termsinformula(x) variablesinformula(x) offsetsinformula(x) lhs.of.formula(x) rhs.of.formula(x, tilde=TRUE) lhs.of.formula(x) <- value rhs.of.formula(x) <- value can.be.formula(x) identical.formulae(x,y)
x, y
|
Formulae, or character strings representing formulae. |
tilde |
Logical value indicating whether to retain the tilde. |
value |
Symbol or expression in the R language. See Examples. |
variablesinformula(x)
returns a character vector of the names
of all variables which appear in the formula x.
termsinformula(x) returns a character vector of all
terms in the formula x (after expansion of interaction terms).
offsetsinformula(x) returns a character vector of all
offset terms in the formula.
rhs.of.formula(x) returns the right-hand side of the formula
as another formula (that is, it removes the left-hand side) provided
tilde=TRUE (the default). If tilde=FALSE, then the
right-hand side is returned as a language object.
lhs.of.formula(x) returns the left-hand side of the formula
as a symbol or language object, or NULL if the formula has no
left-hand side.
lhs.of.formula(x) <- value
and rhs.of.formula(x) <- value
change the formula x by replacing the left or right hand side
of the formula by value.
can.be.formula(x) returns TRUE if x is a formula
or a character string that can be parsed as a formula, and returns
FALSE otherwise.
identical.formulae(x,y) returns TRUE if x and
y are identical formulae (ignoring their environments).
variablesinformula,
termsinformula and
offsetsinformula return a character vector.
rhs.of.formula returns a formula.
lhs.of.formula returns a symbol or language object, or NULL.
can.be.formula and identical.formulae return
a logical value.
Adrian Baddeley [email protected], Rolf Turner [email protected] and Ege Rubak [email protected].
f <- (y ~ x + z*w + offset(h)) lhs.of.formula(f) rhs.of.formula(f) variablesinformula(f) termsinformula(f) offsetsinformula(f) g <- f environment(g) <- new.env() identical(f,g) identical.formulae(f,g) lhs.of.formula(f) <- quote(mork) # or as.name("mork") f rhs.of.formula(f) <- quote(x+y+z) # or parse(text="x+y+z")[[1]] ff <- (y ~ x + z*w + offset(h)) lhs.of.formula(f) rhs.of.formula(f) variablesinformula(f) termsinformula(f) offsetsinformula(f) g <- f environment(g) <- new.env() identical(f,g) identical.formulae(f,g) lhs.of.formula(f) <- quote(mork) # or as.name("mork") f rhs.of.formula(f) <- quote(x+y+z) # or parse(text="x+y+z")[[1]] f
Perform the specified logical operation
on the character vector x, recognising the
special strings "TRUE" and "FALSE"
and treating other strings as logical variables.
verbalogic(x, op = "and")verbalogic(x, op = "and")
x |
Character vector. |
op |
Logical operation: one of the character strings
|
This function performs simple logical operations on character strings that represent human-readable statements.
The character vector x may contain any strings:
the special strings "TRUE" and "FALSE" are
treated as the logical values TRUE and FALSE,
while all other strings are treated as if they were
logical variables.
If op="and", the result is a single string,
logically equivalent to x[1] && x[2] && ... && x[n].
First, any entries of x equal to "TRUE" are removed.
The result is "FALSE" if any of the entries of x
is "FALSE"; otherwise it is equivalent to
paste(x, collapse=" and ").
If op="or", the result is a single string, logically equivalent to
x[1] || x[2] || ... || x[n].
First, any entries of x equal to "FALSE" are removed.
The result is "TRUE" if any of the entries of x
is "TRUE"; otherwise it is equivalent to
paste(x, collapse=" or ").
If op="not", the result is a character vector y
such that y[i] is the logical negation of x[i].
The code does not understand English grammar and cannot expand logical expressions.
A character string.
Adrian Baddeley [email protected].
x <- c("The sky is blue", "my name is not Einstein", "FALSE") verbalogic(x, "and") verbalogic(x, "or") verbalogic(x, "not")x <- c("The sky is blue", "my name is not Einstein", "FALSE") verbalogic(x, "and") verbalogic(x, "or") verbalogic(x, "not")
Determines the index of the minimum or maximum of a vector. If there are multiple entries which achieve the minimum or maximum, one of the indices is selected at random.
which.min.fair(x) which.max.fair(x)which.min.fair(x) which.max.fair(x)
x |
numeric, logical, integer or double vector. |
These functions are alternatives to
the standard R functions which.min
and which.max.
The standard functions which.min
and which.max find the index of the
first entry in the vector x which achieves the minimum
or maximum value. This can cause a bias in some simulation
experiments.
The functions which.min.fair and which.max.fair
identify all entries of the vector x which achieve the
minimum or maximum respectively, and
select one of them at random.
A single integer (or integer(0) if all entries of x are
NA or NaN).
Adrian Baddeley [email protected]
z <- c(20, 40, 20, 10, 40, 20, 10, 20, 40) replicate(5, which.max(z)) replicate(5, which.max.fair(z)) replicate(5, which.min.fair(z))z <- c(20, 40, 20, 10, 40, 20, 10, 20, 40) replicate(5, which.max(z)) replicate(5, which.max.fair(z)) replicate(5, which.min.fair(z))