Title: | Supplemental S-PLUS Functionality in R |
---|---|
Description: | Currently there are many functions in S-PLUS that are missing in R. To facilitate the conversion of S-PLUS packages to R packages, this package provides some missing S-PLUS functionality in R. |
Authors: | William Constantine [aut], Tim Hesterberg [aut], Knut Wittkowski [ctb], Tingting Song [ctb], Bill Dunlap [ctb], Stephen Kaluzny [ctb, cre] |
Maintainer: | Stephen Kaluzny <[email protected]> |
License: | GPL-2 |
Version: | 1.3-5 |
Built: | 2024-11-14 02:42:02 UTC |
Source: | https://github.com/spkaluzny/splus2r |
This is typically used to combine multiple all.equal
tests
into a single test, in a test file called by do.test
.
allTrue(...)
allTrue(...)
... |
Each argument is typically a call to |
This is intended for use in test run by do.test
.
A typical test may contain lines that create one or more
objects, followed by commands to check that those objects have
the expected structure and/or that calculations were correct.
By using allTrue
, the tests can all be combined into the
same expression that created the objects, so that if an error
occurs it is easier to see where it occured.
if all inputs are TRUE
the value is TRUE
.
Otherwise a list indicating which arguments did not return
TRUE
, containing the actual values.
Tim Hesterberg
all.equal
,
do.test
,
expectStop
,
expectWarnings
,
identical
.
# This is the type of expression that may be found in a test file # to be run by do.test -- inside {} are lines that create one or # more objects, followed by multiple tests (inside allTrue) that # check those objects. { y <- rnorm(30) x <- matrix(rnorm(60), ncol=2) fit <- lm(y~x) allTrue(# are important components included? all(is.element(c("coefficients", "residuals", "effects", "rank", "fitted.values", "assign", "df.residual", "call"), names(fit))), { # do coefficients match the algebraic form? # The algebraic form is inaccurate, so allow greater tolerance X <- cbind(1, x) all.equal(unname(fit$coefficients), drop(solve( t(X) %*% X, t(X) %*% y)), tol = 1e-5) }, # are residuals computed correctly? all.equal(fit$residuals, y - X %*% fit$coefficients)) } # The second test uses 'unname' to remove names and 'drop' to change a # matrix to a vector, so the test should pass. # The third test fails because fit$residuals is a vector with names # while the %*% calculation returns a matrix.
# This is the type of expression that may be found in a test file # to be run by do.test -- inside {} are lines that create one or # more objects, followed by multiple tests (inside allTrue) that # check those objects. { y <- rnorm(30) x <- matrix(rnorm(60), ncol=2) fit <- lm(y~x) allTrue(# are important components included? all(is.element(c("coefficients", "residuals", "effects", "rank", "fitted.values", "assign", "df.residual", "call"), names(fit))), { # do coefficients match the algebraic form? # The algebraic form is inaccurate, so allow greater tolerance X <- cbind(1, x) all.equal(unname(fit$coefficients), drop(solve( t(X) %*% X, t(X) %*% y)), tol = 1e-5) }, # are residuals computed correctly? all.equal(fit$residuals, y - X %*% fit$coefficients)) } # The second test uses 'unname' to remove names and 'drop' to change a # matrix to a vector, so the test should pass. # The third test fails because fit$residuals is a vector with names # while the %*% calculation returns a matrix.
Detection of missing values.
anyMissing(x)
anyMissing(x)
x |
any object (though not all are currently supported). |
logical, TRUE is missing values are detected.
anyMissing(1:5) anyMissing(c(1, NA, 2)) anyMissing(list(a=1:3, b=NA)) anyMissing(data.frame(a=1:3, b=c(NA, 5:6)))
anyMissing(1:5) anyMissing(c(1, NA, 2)) anyMissing(list(a=1:3, b=NA)) anyMissing(data.frame(a=1:3, b=c(NA, 5:6)))
Rectangular data objects include matrices, data frames, and atomic vectors.
x |
object to be converted to rectangular data. |
i |
first (row) subscript |
j |
second (column) subscript. |
as.rectangular(x)
returns x
if x
is already rectangular, or as.data.frame(x)
if it is not.
## as.rectangular(list(a=1:10, b=11:20))
## as.rectangular(list(a=1:10, b=11:20))
Essentially just converts data to rectangular form, if possible.
asSeriesData(x)
asSeriesData(x)
x |
input object to coerce. |
rectangular conversion of input argument.
numericSequence
, seriesData
, seriesDataNew
, seriesDataValid
, signalSeries
, as.data.frame.signalSeries
, as.matrix.signalSeries
, cumsum.signalSeries
, deltat.signalSeries
, diff.signalSeries
, plot.signalSeries
.
Reports the size of an integer in bits.
bits.per.integer()
bits.per.integer()
Included for S-PLUS compatibility; R currently uses 32-bit integers, even on 64-bit machines.
Dunlap, W.M., and Taylor, C.F.
bits.per.integer()
bits.per.integer()
Summarizes the columns or rows of a rectangular object.
colIds(x, do.NULL=TRUE, prefix="col") colMaxs(x, na.rm = FALSE, dims = 1, n = NULL) colMedians(x, na.rm=FALSE) colMins(x, na.rm = FALSE, dims = 1, n = NULL) colRanges(x, na.rm = FALSE, dims = 1, n = NULL) colVars(x, na.rm=FALSE, dims = 1, unbiased = TRUE, SumSquares = FALSE, weights = NULL, freq = NULL, n = NULL) rowIds(x, do.NULL=TRUE, prefix="row") rowMaxs(x, na.rm = FALSE, dims = 1, n = NULL) rowMins(x, na.rm = FALSE, dims = 1, n = NULL) rowRanges(x, na.rm = FALSE, dims = 1, n = NULL)
colIds(x, do.NULL=TRUE, prefix="col") colMaxs(x, na.rm = FALSE, dims = 1, n = NULL) colMedians(x, na.rm=FALSE) colMins(x, na.rm = FALSE, dims = 1, n = NULL) colRanges(x, na.rm = FALSE, dims = 1, n = NULL) colVars(x, na.rm=FALSE, dims = 1, unbiased = TRUE, SumSquares = FALSE, weights = NULL, freq = NULL, n = NULL) rowIds(x, do.NULL=TRUE, prefix="row") rowMaxs(x, na.rm = FALSE, dims = 1, n = NULL) rowMins(x, na.rm = FALSE, dims = 1, n = NULL) rowRanges(x, na.rm = FALSE, dims = 1, n = NULL)
x |
rectangular input object such as a matrix or data.frame. |
dims |
if |
do.NULL |
logical for rowIds or colIds. |
n |
number of rows; treat |
na.rm |
logical, NA values are removed if TRUE. |
prefix |
character string preface for column IDs returned by rowIds or colIds. |
unbiased |
logical, unbiased variance estimates returned if |
SumSquares |
logical, sums of squares are returned if |
weights , freq
|
unsupported, here for backwards compatibility. |
corresponding summary by row or by column.
See 'aggregate' package for alternative definitions of colStdevs, colVars, rowStdevs and rowVars functions.
## create a matrix, add dimensions, and obtain ## various summaries x <- matrix(sin(1:20), nrow=4) dimnames(x) <- list(c("a","b","c","d"), paste("col", 1:5)) colIds(x) colMaxs(x) colMedians(x) colMins(x) colRanges(x) rowIds(x) rowMaxs(x) rowMins(x) rowRanges(x)
## create a matrix, add dimensions, and obtain ## various summaries x <- matrix(sin(1:20), nrow=4) dimnames(x) <- list(c("a","b","c","d"), paste("col", 1:5)) colIds(x) colMaxs(x) colMedians(x) colMins(x) colRanges(x) rowIds(x) rowMaxs(x) rowMins(x) rowRanges(x)
Deparse the argument into a single string, with at most maxchars
characters. New lines are turned into blanks, and truncated
results end in "....".
deparseText(expr, maxchars=30)
deparseText(expr, maxchars=30)
expr |
any expression. |
maxchars |
maximum number of characters returned |
deparsed character string.
deparseText(args(lm), maxchars=20)
deparseText(args(lm), maxchars=20)
Expressions are parsed and evaluated from file
.
Each expression should evaluate to a logical TRUE
. Otherwise,
do.test()
prints the expression and its value.
do.test(file, verbose=FALSE, strict=FALSE, local=FALSE, check)
do.test(file, verbose=FALSE, strict=FALSE, local=FALSE, check)
file |
a file or connection containing code to test. |
verbose |
logical flag. If |
strict |
logical flag. If |
local |
logical flag controlling where the evaluation
takes place: by default ( |
check |
an unevaluated expression. If |
A test file typically contains a sequence of expressions to test
different aspects of a function or set of functions, including
testing that each input argument is handled appropriately,
error handling,
the output has the expected structure,
correct output under a number of combinations of inputs,
and error handling (warning and stop invoked when appropriate and
with appropriate messages). Each expression may contain multiple
lines grouped using {}
,
where early lines may do computations and the last line
checks for expected results, usually using all.equal
.
Some expressions may be included that aren't intended to test anything
by finishing them with TRUE
, e.g. to read data:
{read.table("data.txt"); TRUE}
or to remove objects at the end of a test file:
{rm(a, b, x, y); TRUE}
.
We recommend including comments inside expressions to indicate the purpose of each test; then if errors occur the comments are printed too.
To compare just numbers, not names or matrix dimensions, functions
unname
and drop
are useful.
To exclude
certain components or attributes from the comparison the function
all.equal.excluding
is useful. This is defined in the examples
below.
Each test should run silently if everything is working correctly;
there should be nothing printed. expectWarnings
can
be used to intercept warning
statements.
NULL
all.equal
,
allTrue
,
drop
,
expectStop
,
expectWarnings
,
identical
,
Quote
,
unname
## Not run: # Create a toy test file, and run it cat('{all.equal(24/8, 3)}', '{all.equal(5, 6)}', # this one will fail 'expectWarnings( { # Test subscript replacement ', ' x <- data.frame(a=1:3,b=2:4)', ' x[,3] <- x', ' all.equal(ncol(x), 3)', '}, expected = "provided 2 variables to replace 1 var")', 'expectStop(lm(5), expected = "invalid formula")', '{ rm(x) ; TRUE }', # cleanup at end of test sep="\n", file = "testfile.t") do.test("testfile.t") ## ------- Test file: testfile.t --------- ## {all.equal(5, 6)} ## [1] "Mean relative difference: 0.2" # # The test that fails is printed, with the results of the test. # In R 2.6.1 the subscript replacement test above also fails # (bug reported 14 Jan 2008), resulting in the additional printout: ## expectWarnings( { ## x <- data.frame(a=1:3,b=2:4) ## x[,3] <- x ## all.equal(ncol(x), 3) ## }, expected = "provided 2 variables to replace 1 var") ## $`Test result` ## [1] "Mean relative difference: 0.25" ## End(Not run) # This function is useful in some tests: all.equal.excluding <- function(x, y, ..., excluding=NULL, attrs=NULL){ # Like all.equal, but exclude components in `excluding', # and excluding attributes named in `attrs'. # # `excluding' and `attrs' should be character, names of components # and attributes. # # For example: # all.equal.excluding(obj1, obj2, excluding = c("call", "x")) for(i in intersect(names(x), excluding)) x[[i]] <- NULL for(i in intersect(names(y), excluding)) y[[i]] <- NULL for(i in intersect(names(attributes(x)), attrs)) attr(x,i) <- NULL for(i in intersect(names(attributes(y)), attrs)) attr(y,i) <- NULL all.equal(x,y, ...) } # Test if two objects are the same except for "call" and "x": data <- data.frame(x = 1:20, y = exp(1:20/20)) fit1 <- lm(y ~ x, data = data, x=TRUE) fit2 <- update(fit1, x=) all.equal.excluding(fit1, fit2, excluding = c("call", "x"))
## Not run: # Create a toy test file, and run it cat('{all.equal(24/8, 3)}', '{all.equal(5, 6)}', # this one will fail 'expectWarnings( { # Test subscript replacement ', ' x <- data.frame(a=1:3,b=2:4)', ' x[,3] <- x', ' all.equal(ncol(x), 3)', '}, expected = "provided 2 variables to replace 1 var")', 'expectStop(lm(5), expected = "invalid formula")', '{ rm(x) ; TRUE }', # cleanup at end of test sep="\n", file = "testfile.t") do.test("testfile.t") ## ------- Test file: testfile.t --------- ## {all.equal(5, 6)} ## [1] "Mean relative difference: 0.2" # # The test that fails is printed, with the results of the test. # In R 2.6.1 the subscript replacement test above also fails # (bug reported 14 Jan 2008), resulting in the additional printout: ## expectWarnings( { ## x <- data.frame(a=1:3,b=2:4) ## x[,3] <- x ## all.equal(ncol(x), 3) ## }, expected = "provided 2 variables to replace 1 var") ## $`Test result` ## [1] "Mean relative difference: 0.25" ## End(Not run) # This function is useful in some tests: all.equal.excluding <- function(x, y, ..., excluding=NULL, attrs=NULL){ # Like all.equal, but exclude components in `excluding', # and excluding attributes named in `attrs'. # # `excluding' and `attrs' should be character, names of components # and attributes. # # For example: # all.equal.excluding(obj1, obj2, excluding = c("call", "x")) for(i in intersect(names(x), excluding)) x[[i]] <- NULL for(i in intersect(names(y), excluding)) y[[i]] <- NULL for(i in intersect(names(attributes(x)), attrs)) attr(x,i) <- NULL for(i in intersect(names(attributes(y)), attrs)) attr(y,i) <- NULL all.equal(x,y, ...) } # Test if two objects are the same except for "call" and "x": data <- data.frame(x = 1:20, y = exp(1:20/20)) fit1 <- lm(y ~ x, data = data, x=TRUE) fit2 <- update(fit1, x=) all.equal.excluding(fit1, fit2, excluding = c("call", "x"))
These functions are for use in automated testing using do.test
,
to test whether function give specified
stop
and warning
messages.
expectStop(expr, expected = NULL) expectWarnings(expr, expected)
expectStop(expr, expected = NULL) expectWarnings(expr, expected)
expr |
An expression, that should result in a call to |
expected |
|
expectStop
is useful for checking error checking; that a function
stops when it should, and gives the right message.
For example, this may be in a file called by do.test:
{ expectStop(var(1:5, 1:4), "incompatible") }
The function returns TRUE
if
a stop() occurs, and
the error message is expected.
Otherwise it returns appropriate messages.
expectStop
intercepts the error.
Execution continues, and assignments made earlier are committed.
Similarly, expectWarnings
is useful to check that a function
gives appropriate warnings.
For example, this may be in a file called by do.test:
expectWarnings( { object1 <- (code generating warning messages); object2 <- (code generating possibly other warning messages); all.equal(object1, object2) }, c("expected warning 1", "expected warning 2"))
The function returns TRUE
if
expr evaluates to TRUE
; and
each warning message produced by evaluating expr contains as a substring an element of expected, and each element of expected is a substring of at least one of the produced warning messages.
Otherwise it returns a list with components describing the test failures. Normal printing of warning messages is suppressed.
It is possible to test for warnings and a stop in a single expression, by nesting calls to the two functions.
If all tests pass, then TRUE
.
Otherwise expectStop
returns character strings describing the
failure, while expectWarnings
returns a list with one or
more of the following components:
'Test result' |
the value (if not |
'Unexpected warnings' |
character vector
of actual warning messages that were not listed in |
'Warnings expected but not found' |
character vector
of messages in |
Tim Hesterberg
# Expressions like the following would typically be included in a file # that is called by do.test expectStop(lm(5), expected = "invalid formula") expectStop(cov2cor( matrix(2:1) ), expected = "'V' is not a square numeric matrix") expectWarnings( # Test subscript replacement; should discard extra # column and give a warning { x <- data.frame(a=1:3,b=2:4) x[,3] <- x all.equal(ncol(x), 3) }, expected = "provided 2 variables to replace 1 var") # Test for a warning and stop together: { f <- function(x){ warning("a warning") stop("a stop") } expectStop( expectWarnings( f(3), expected = "a warning"), expected = "a stop") } # The definition of f and the call to expectStop are included here # within {} because that is how they would typically be grouped in # a file that is called by do.test. Also note that f has been saved # (the assignment of f is committed, rather than aborted).
# Expressions like the following would typically be included in a file # that is called by do.test expectStop(lm(5), expected = "invalid formula") expectStop(cov2cor( matrix(2:1) ), expected = "'V' is not a square numeric matrix") expectWarnings( # Test subscript replacement; should discard extra # column and give a warning { x <- data.frame(a=1:3,b=2:4) x[,3] <- x all.equal(ncol(x), 3) }, expected = "provided 2 variables to replace 1 var") # Test for a warning and stop together: { f <- function(x){ warning("a warning") stop("a stop") } expectStop( expectWarnings( f(3), expected = "a warning"), expected = "a stop") } # The definition of f and the call to expectStop are included here # within {} because that is how they would typically be grouped in # a file that is called by do.test. Also note that f has been saved # (the assignment of f is committed, rather than aborted).
This is equivalent to {if(test) x else y}
. The main
advantage of using this function is better formatting, and a more
natural syntax when the result is being assigned; see examples below.
With 5 arguments, this is equivalent to {if(test1) x else if(test2) u
else v}
(where arguments are given by name, not position).
ifelse1(test, x, y, ...)
ifelse1(test, x, y, ...)
test |
logical value; if TRUE return x. |
x |
any object; this is returned if test is TRUE. |
y |
any object; this is returned if test is FALSE. |
... |
there should be 3, 5, 7, etc. arguments to this function; arguments 1, 3, 5, etc. should be logical values; the other arguments (even numbered, and last) are objects that may be returned. |
test
should be a scalar logical, and only one of x
or
y
is evaluated, depending on whether test = TRUE
or
test = FALSE
, and x
and y
may be any objects.
In contrast, for
ifelse
, test is normally a vector, both x
and y
are evaluated, even if
not used, and x
and y
are vectors the same length as
test
.
with three arguments, one of x
or y
.
With k arguments, one of arguments 2, 4, ..., k-1, k.
ifelse1(TRUE, "cat", "dog") ifelse1(FALSE, "one", FALSE, "two", "three")
ifelse1(TRUE, "cat", "dog") ifelse1(FALSE, "one", FALSE, "two", "three")
is.inf
returns a vector of the same length as the input object,
indicating which elements are infinite (not missing).
is.inf(x)
is.inf(x)
x |
object to be tested |
This calls is.infinite
.
This returns a vector of the same length as x
; the j
th
element is TRUE
if x[j]
is infinite
(i.e., equal to one of Inf
or -Inf
).
This will be FALSE
if x
is not numeric or complex.
Complex numbers are infinite if either the real and imaginary part is.
is.inf(Inf) # [1] TRUE is.inf(NA) # [1] FALSE is.inf(1) # [1] FALSE
is.inf(Inf) # [1] TRUE is.inf(NA) # [1] FALSE is.inf(1) # [1] FALSE
Check to see whether the input is either NA or a vector of length 0.
is.missing(x)
is.missing(x)
x |
object to check. |
TRUE if the input is a vector of length 0; is.na(x)
otherwise.
is.missing(numeric(0)) is.missing(NA) is.missing(c(1,2,3,NA,5))
is.missing(numeric(0)) is.missing(NA) is.missing(c(1,2,3,NA,5))
Returns a logical vector describing if a numeric elements is a number.
is.number(x)
is.number(x)
x |
numeric vector |
is.number
is TRUE
if the value is numeric or complex
and is not missing (NA
or NaN
).
is.number(32) # [1] TRUE is.number(matrix(1:20, nrow=2)) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] # [1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE # [2,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE is.number(list(matrix(1:20, nrow=2), 1:4)) # [1] TRUE TRUE is.number('s') # [1] TRUE
is.number(32) # [1] TRUE is.number(matrix(1:20, nrow=2)) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] # [1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE # [2,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE is.number(list(matrix(1:20, nrow=2), 1:4)) # [1] TRUE TRUE is.number('s') # [1] TRUE
is.orderable(x)
returns !is.na()
.
is.orderable(x)
is.orderable(x)
x |
object to be tested. |
x
should not be a list; in that case the behavior currently
differs between S-PLUS and R.
is.orderable
returns a logical vector of the same length
as x
.
x <- c(1, 4, NA, 0, 5) is.orderable(x) # [1] TRUE TRUE FALSE TRUE TRUE
x <- c(1, 4, NA, 0, 5) is.orderable(x) # [1] TRUE TRUE FALSE TRUE TRUE
Returns TRUE if the input object is rectangular.
is.rectangular(x)
is.rectangular(x)
x |
any object. |
logical, returns TRUE if input object is rectangular.
is.rectangular(matrix(1:12, nrow=3)) is.rectangular(list(1:3,2:4)) is.rectangular(as.rectangular(list(1:3,2:4)))
is.rectangular(matrix(1:12, nrow=3)) is.rectangular(list(1:3,2:4)) is.rectangular(as.rectangular(list(1:3,2:4)))
The is.vector
function returns a FALSE
value in some cases where intuitively one might
expect a TRUE
value to be returned. For example,
is.vector(z)
returns FALSE
for each of the
following:
z <- 1:3;names(z) <- 1:3
z <- matrix(1:3, nrow=1)
z <- matrix(1:3, ncol=1)
These results are not necessarily incorrect, they are
just one interpretion of the definition of a vector.
Contrarily, the isNumericAtomicVector(z)
function returns
TRUE
for each of the above examples. Thus,
isNumericAtomicVector
expands the basic definition of a
vector to allow matrices containing a single row
or column and named vectors. Also, unlike is.vector
,
isNumericAtomicVector
returns FALSE
for objects of class list
.
isNumericAtomicVector(x)
isNumericAtomicVector(x)
x |
an object of arbitrary class. |
a vector of character strings containing the result. The length
of this vector is equal to length(x)
.
## cases where isNumericAtomicVector returns ## TRUE z <- 1:3;names(z) <- letters[1:3] isNumericAtomicVector(z) isNumericAtomicVector(matrix(1:3, nrow=1)) isNumericAtomicVector(matrix(1:3, ncol=1)) isNumericAtomicVector(1:5) isNumericAtomicVector(letters) ## cases where isNumericAtomicVector returns ## FALSE isNumericAtomicVector(list(1:3)) isNumericAtomicVector(data.frame(1:3,2:4)) isNumericAtomicVector(matrix(1:12, nrow=4))
## cases where isNumericAtomicVector returns ## TRUE z <- 1:3;names(z) <- letters[1:3] isNumericAtomicVector(z) isNumericAtomicVector(matrix(1:3, nrow=1)) isNumericAtomicVector(matrix(1:3, ncol=1)) isNumericAtomicVector(1:5) isNumericAtomicVector(letters) ## cases where isNumericAtomicVector returns ## FALSE isNumericAtomicVector(list(1:3)) isNumericAtomicVector(data.frame(1:3,2:4)) isNumericAtomicVector(matrix(1:12, nrow=4))
Convert text to lower or upper case.
lowerCase(x) upperCase(x)
lowerCase(x) upperCase(x)
x |
a character string. |
a character string coerced to the specified case.
x <- "A dog and a cat" lowerCase(x) upperCase(x)
x <- "A dog and a cat" lowerCase(x) upperCase(x)
MC makes closures for defining functions in a function.
MC(f, env=NULL)
MC(f, env=NULL)
f |
function |
env |
a list containing functions to be used in f |
MC declares functions to be used in f. When f is defined inside of a function, say fun, it cannot call other functions defined in fun. MC can enclose the functions needed by f and make it possible for f to call other functions defined in fun.
Knut M. Wittkowski [email protected]
f1 <- function(x, y) x+y f2 <- MC(function(x, y) x*y, list(f1=f1))
f1 <- function(x, y) x+y f2 <- MC(function(x, y) x*y, list(f1=f1))
count the number of ... arguments passed.
nDotArgs(...)
nDotArgs(...)
... |
... arguments or real arguments in the call to the function which calls |
the number of ... arguments in the call to the
function which calls nDotArgs
.
myfun <- function(..., a=4) nDotArgs(...) myfun() ## returns 0 myfun(1:3,"bear") ## returns 2 myfun(a=5, 1:3, "bear") ## returns 2 (excludes a)
myfun <- function(..., a=4) nDotArgs(...) myfun() ## returns 0 myfun(1:3,"bear") ## returns 2 myfun(a=5, 1:3, "bear") ## returns 2 (excludes a)
Returns number of rows or number of columns of rectangular input object.
numCols(x) numRows(x)
numCols(x) numRows(x)
x |
rectangular object. |
the number of rows or columns of the input object.
as.data.frame
,matrix
,Subscript
,nrow
,dimnames
.
x <- matrix(1:12, nrow=3) numCols(x) numRows(x)
x <- matrix(1:12, nrow=3) numCols(x) numRows(x)
Constructor function for numericSequence objects. At least three of the four arguments must be supplied, unless the function is called with no arguments.
numericSequence(from, to, by, length.)
numericSequence(from, to, by, length.)
from |
start of the sequence. |
to |
end of the sequence. |
by |
increment for the sequence. |
length. |
length of the sequence, a non-negative integer. |
a numericSequence object with properties given by the arguments, or the default numericSequence if no arguments are supplied.
supported S4 methods include: Math
, Math2
, Ops
, Summary
, [
, [[
, duplicated
, is.na
,
length
, match
, mean
, median
, quantile
, show
, sort
,
summary
, unique
, which.na
. There are also [
and [[
S4 style replacment methods available.
s4 style conversion methods ala as(x, foo)
where foo
is one of the following conversion classes:
"character"
, "integer"
, "numeric"
.
seriesData
, asSeriesData
, seriesDataNew
, seriesDataValid
, signalSeries
, as.data.frame.signalSeries
, as.matrix.signalSeries
, cumsum.signalSeries
, deltat.signalSeries
, diff.signalSeries
, plot.signalSeries
.
Methods for class signalSeries
in package splus2R
Supported (generic) methods include:
Target classes: character, integer, numeric.
Math functions
Math2 functions
Ops functions
Single- and double-bracket access and replacement functions
Find duplciated entries in sequence
Test for NA entries in sequence
Length of sequence
Matching functions for sequence
Mean of sequence
Median of sequence
Quantile of sequence
Reverse sequence
Show the sequence
Sort the sequence
Find unique sequence entries
Summarize the sequence
Find unique elements of a sequence
Find NA entries in the sequence
the old-style version of function unclass
; it sets oldClass
to NULL
, rather than class
.
oldUnclass(x)
oldUnclass(x)
x |
any object. |
unclassed version of input object.
oldUnclass(matrix(1:10))
oldUnclass(matrix(1:10))
Finds the local maxima in a vector, or time series, or in each column of a matrix.
peaks(x, span=3, strict=TRUE, endbehavior=0)
peaks(x, span=3, strict=TRUE, endbehavior=0)
x |
vector or matrix. |
span |
a peak is defined as an element in a sequence which is greater than all other elements within a window of width span centered at that element. The default value is 3, meaning that a peak is bigger than both of its neighbors. Default: 3. |
strict |
logical flag: if TRUE, an element must be strictly greater than all other values in its window to be considered a peak. Default: TRUE. |
endbehavior |
a value of 0, 1 or 2 that determines how peaks are computed within
a |
an object like x
of logical values.
Values that are TRUE correspond to local peaks in the data.
The value of endbehavior
acts as follows:
0 is as if the series had runs of halfwidth
values of Inf
attached to either end,
1 is as if there were runs of halfwidth
values of -Inf
attached,
and 2 is as if there were runs ofhalfwidth
values of NA
attached.
x <- as.vector(sunspots) z <- peaks(x, span=51) plot(x, type="l") abline(v=which(z), col="red", lty="dashed")
x <- as.vector(sunspots) z <- peaks(x, span=51) plot(x, type="l") abline(v=which(z), col="red", lty="dashed")
Access the positions of series objects.
positions(object)
positions(object)
object |
an object of class |
the positions associated with the input time series: an object of class numericSequence
.
x <- signalSeries(1:10, from=pi, by=0.1) positions(x)
x <- signalSeries(1:10, from=pi, by=0.1) positions(x)
Random generation for the multivariate normal (also called Gaussian) distribution.
rmvnorm(n, mean=rep(0,d), cov=diag(d), sd, rho, d=2)
rmvnorm(n, mean=rep(0,d), cov=diag(d), sd, rho, d=2)
n |
sample size – number of random vectors of length d to return (as rows in a matrix). |
cov |
covariance or correlation matrix with d rows and columns. |
d |
dimension of the multivariate normal. |
mean |
vector of length d, or matrix with n rows and d columns. |
rho |
scalar, vector, or bdVector of length n, containing correlations for bivariate data. This is ignored if cov is supplied. |
sd |
vector of length d, or matrix with n rows and d columns, containing standard deviations. If supplied, the rows and columns of cov are multiplied by sd. In particular, if cov is a correlation matrix and sd is a vector of standard deviations, the result is a covariance matrix. If sd is a matrix then one row is used for each observation. |
random sample ( rmvnorm) for the multivariate normal distribution.
## 5 rows and 2 independent columns rmvnorm(5) ## 5 rows and 3 independent columns rmvnorm(5, mean=c(9,3,1)) ## 2 columns, std. dev. 1, correlation .9 rmvnorm(5, rho=.9) ## specify variable means and covariance matrix rmvnorm(5, mean=c(9,3), cov=matrix(c(4,1,1,2), 2))
## 5 rows and 2 independent columns rmvnorm(5) ## 5 rows and 3 independent columns rmvnorm(5, mean=c(9,3,1)) ## 2 columns, std. dev. 1, correlation .9 rmvnorm(5, rho=.9) ## specify variable means and covariance matrix rmvnorm(5, mean=c(9,3), cov=matrix(c(4,1,1,2), 2))
Access the data slot of series objects.
seriesData(object)
seriesData(object)
object |
object with which to find data. |
the data slot of object.
single level data replacement method.
Usage: x[1:4] <- 1:4)
numericSequence
, asSeriesData
, seriesDataNew
, seriesDataValid
, signalSeries
, as.data.frame.signalSeries
, as.matrix.signalSeries
, cumsum.signalSeries
, deltat.signalSeries
, diff.signalSeries
, plot.signalSeries
.
Creates template for new seriesData object., basically a NULL matrix.
seriesDataNew()
seriesDataNew()
nULL matrix.
numericSequence
, seriesData
, asSeriesData
, seriesDataValid
, signalSeries
, as.data.frame.signalSeries
, as.matrix.signalSeries
, cumsum.signalSeries
, deltat.signalSeries
, diff.signalSeries
, plot.signalSeries
.
Checks to see if input object is rectangular.
seriesDataValid(object)
seriesDataValid(object)
object |
the object to check. |
logical value, TRUE is a valid seriesData object.
numericSequence
, seriesData
, asSeriesData
, seriesDataNew
, signalSeries
, as.data.frame.signalSeries
, as.matrix.signalSeries
, cumsum.signalSeries
, deltat.signalSeries
, diff.signalSeries
, plot.signalSeries
.
Describe the structure of an object, recursively.
showStructure(x, maxlen = 20, describeAttributes = TRUE, short = NULL, prefix = "", attri = FALSE, ...)
showStructure(x, maxlen = 20, describeAttributes = TRUE, short = NULL, prefix = "", attri = FALSE, ...)
x |
any object |
maxlen |
integer; if |
describeAttributes |
logical; if |
short |
|
prefix |
for internal use in recursive calls. This is used for indenting in recursive calls. |
attri |
for internal use in recursive calls. This is |
... |
Additional argument that may be passed to methods; not currently used. |
This supports recursive objects, using recursive calls. Each
level of recursion is indented two additional spaces. List components
are shown with $
, slots with @
, and attributes with &
.
This prints a description; it doesn't return anything useful.
Tim Hesterberg
a <- c(m=1, n=2) b <- diag(1:3) cc <- cbind(a=1:5, b=2:6, c=letters[1:5]) d <- data.frame(cc) attr(d, "dup.row.names") <- TRUE e <- ts(1:10, frequency = 4, start = c(1959, 2)) f <- list(a,b=b) setClass("track", representation(x="numeric", y="numeric")) g <- new("track", x=1:5, y=1:5) showStructure(a) showStructure(b) showStructure(cc) showStructure(d) showStructure(e) showStructure(f) showStructure(g) # prints with @ rather than $ showStructure(list(a=a, b=b)) showStructure(list(cc=cc, d, list(a,e)))
a <- c(m=1, n=2) b <- diag(1:3) cc <- cbind(a=1:5, b=2:6, c=letters[1:5]) d <- data.frame(cc) attr(d, "dup.row.names") <- TRUE e <- ts(1:10, frequency = 4, start = c(1959, 2)) f <- list(a,b=b) setClass("track", representation(x="numeric", y="numeric")) g <- new("track", x=1:5, y=1:5) showStructure(a) showStructure(b) showStructure(cc) showStructure(d) showStructure(e) showStructure(f) showStructure(g) # prints with @ rather than $ showStructure(list(a=a, b=b)) showStructure(list(cc=cc, d, list(a,e)))
Construct a signalSeries object from positions and data, or return an empty signalSeries object.
signalSeries(data, positions., units, units.position, from=1, by=1)
signalSeries(data, positions., units, units.position, from=1, by=1)
by |
amount to skip for positions. |
data |
variable data, which will be converted to a rectangular object with the as.rectangular function. |
from |
starting value of positions. |
positions. |
numeric or numeric sequence object to use as the time/position values. |
units |
units for variable data. |
units.position |
units for positions. |
If no arguments are supplied, the default (empty) signalSeries object is returned. Otherwise, a signalSeries object is created with the given positions and data, and units if they are supplied. As an alternative to supplying the positions directly, they can be supplied by giving from and by, in which case the positions are generated as a numeric sequence with the right length to match the data.
a signalSeries
object with the given data and positions.
s4 style conversion to another class ala as(x, foo) where foo is
any of the following: "character"
, "complex"
, "data.frame"
, "integer"
,
"logical"
, "matrix"
, "numeric"
, "vector"
.
convert to a data.frame
.
convert to a matrix.
cumulative summation over series.
samlig intervals of series.
differencing operation applied to the series. Usage: diff(x, ...) where the ...
are additional arguments
sent directly to the diff
function.
plots the series.
Methods for class signalSeries
in package splus2R
Supported (generic) methods include:
Target classes: complex, character, matrix, numeric, logical, integer, vector, and data.frame. S3 style methods include as.numeric and as.vector.
Arithmetic functions
Comparison functions
Logical functions
Math functions
Math2 functions
Ops functions
Dimension of series (NULL is returned)
Length of series
Mean of series
Minimum of series
Number of columns of series (1 is returned)
Plot the series
Display the series
Sum the series.
Sumamrize the series object
Calculates the standard deviation of a series.
stdev(x, ...)
stdev(x, ...)
x |
input series. |
... |
optional arguments sent directly to the |
the standard deviation of the input series.
var
.
stdev(c(pi, 1, 3))
stdev(c(pi, 1, 3))
subscript2d is for subscripting matrices and data frames.
subscript2d(x,i,j) subscript2dMatrix(x,i,j) subscript2dDataFrame(x,i,j)
subscript2d(x,i,j) subscript2dMatrix(x,i,j) subscript2dDataFrame(x,i,j)
x |
a matrix or data frame |
i |
first (row) subscript. |
j |
second (column) subscript. |
subscript2d(x,i,j)
is like x[i,j,drop=F]
,
except that it allows x[,1]
(for example) for atomic vectors as well,
and it always returns an object of the same class as x
(that is, it does not support a drop argument).
x <- 1:10 subscript2d(x,3,1) subscript2d(data.frame(x),3,1) subscript2d(matrix(x),3,1)
x <- 1:10 subscript2d(x,3,1) subscript2d(data.frame(x),3,1) subscript2d(matrix(x),3,1)
Computes the p-norm of a vector
vecnorm(x, p=2)
vecnorm(x, p=2)
x |
the vector whose norm is sought (either numeric or complex). |
p |
a number or character string indicating the type of norm desired. Possible values include real number greater or
equal to 1, |
requested p-norm of input vector.
## compare 2-norm calculations x <- rnorm(100) sqrt(sum(x*x)) vecnorm(x) ## compare 2-norm of series which sums to Inf. The ## vecnorm returns a finite value in this case. x <- rep(sqrt(.Machine$double.xmax), 4) sqrt(sum(x*x)) vecnorm(x) ## 1-norm comparison sum(abs(x)) vecnorm(x, p=1) ## L-infinity norm comparison max(abs(x)) vecnorm(x, p=Inf)
## compare 2-norm calculations x <- rnorm(100) sqrt(sum(x*x)) vecnorm(x) ## compare 2-norm of series which sums to Inf. The ## vecnorm returns a finite value in this case. x <- rep(sqrt(.Machine$double.xmax), 4) sqrt(sum(x*x)) vecnorm(x) ## 1-norm comparison sum(abs(x)) vecnorm(x, p=1) ## L-infinity norm comparison max(abs(x)) vecnorm(x, p=Inf)
Returns an integer vector describing which values in the input vector, if any, are missing.
which.na(x)
which.na(x)
x |
an R object, which should be of mode |
an integer vector describing which values in the input vector, if any, are missing.
## A non-zero number divided by zero creates ## infinity, zero over zero creates a NaN weird.values <- c(1/0, -20.9/0, 0/0, NA) ## Produces: 3 4. In this example, the which.na ## expression and the subscript expression ## involving is.na should return the same value which.na(weird.values) seq(along=weird.values)[is.na(weird.values)]
## A non-zero number divided by zero creates ## infinity, zero over zero creates a NaN weird.values <- c(1/0, -20.9/0, 0/0, NA) ## Produces: 3 4. In this example, the which.na ## expression and the subscript expression ## involving is.na should return the same value which.na(weird.values) seq(along=weird.values)[is.na(weird.values)]