Returns a vector or array or list of values obtained by applying a function to margins of a sparse matrix.
apply.spam(X, MARGIN=NULL, FUN, ...)
the spam
matrix to be used.
a vector giving the subscripts which the function will be
applied over. 1
indicates rows, 2
indicates columns,
NULL
or c(1,2)
indicates rows and columns.
the function to be applied.
optional arguments to FUN
.
Similar as a call to apply
with a regular matrix. The most
important cases are as follows. The
result is a vector (MARGIN
is length 1 and FUN
is
scalar) or a matrix (MARGIN
is length 1 and FUN
returns
fixed length vectors, or MARGIN
is length 2 and FUN
is
scalar) or a list (if FUN
returns vectors of different lengths).
This is a handy wrapper to apply a function to the (nonzero)
elements of a sparse matrix.
For example, it is possible to apply a covariance matrix to a distance
matrix obtained by nearest.dist
, see Examples.
A call to apply
only coerces the sparse matrix to a regular one.
The basic principle is applying the function to @entries
, or to
the extracted columns or rows ([,i,drop=F]
or
[i,,drop=F]
). It is important to note that an empty column
contains at least one zero value and may lead to non intuitive
results.
This function may evolve over the next few releases.
base:apply
for more details on Value.
# NOT RUN {
S <- as.spam(dist(1:5))
S <- apply.spam(S/2, NULL, exp)
# instead of
# S@entries <- exp( S@entries/2)
# Technical detail, a null matrix consists
# of one zero element.
apply.spam(S,c(1,2),pmax)
apply.spam(S,1,range)
# A similar example as for the base apply.
# However, no dimnames else we would get warnings.
x <- as.spam(cbind(x1 = 3, x2 = c(0,0,0, 5:2)))
apply.spam(x, 2, mean, trim = .2)
col.sums <- apply.spam(x, 2, sum)
row.sums <- apply.spam(x, 1, sum)
rbind(cbind(x, row.sums), c(col.sums, sum(col.sums)))
apply.spam(x, 2, is.vector)
# Sort the columns of a matrix
# Notice that the result is a list due to the different
# lengths induced by the nonzero elements
apply.spam(x, 2, sort)
# Function with extra args:
cave <- function(x, c1, c2) c(mean(x[c1]), mean(x[c2]))
apply(x,1, cave, c1=1, c2=c(1,2))
ma <- spam(c(1:4, 0, 0,0, 6), nrow = 2)
ma
apply.spam(ma, 1, table) #--> a list of length 2
apply.spam(ma, 1, stats::quantile)# 5 x n matrix with rownames
# }
Run the code above in your browser using DataLab