The
八度音程包调用GNU 倍频程API函数;
如果你还不知道GNU 倍频程, it is very如同Matlab并致力于完全兼容。
这几乎和直接 Matlab 一样快......
library(RcppOctave)
set.seed(1)
n = array(rnorm(100*50*100*20), dim = c(100,50,100,20))
system.time( s <- octave_style_quantile(n, .66, 4) )
## user system elapsed
## 0.526 0.048 0.574
# *R* `quantile` argument `type=5` is the method that matches matlab.
system.time( r <- apply(n, 1:3, quantile, .66, names = FALSE, type=5) )
## user system elapsed
## 23.308 0.029 23.327
dim(r)
## [1] 100 50 100
identical(r,s)
## [1] TRUE
Octave 的相当直接的翻译分位数.m
to R.
octave_style_quantile <- function (x, p=NULL, dim=NULL) {
if ( is.null(p) ) p <- c(0.00, 0.25, 0.50, 0.75, 1.00)
if ( is.null(dim) ) {
## Find the first non-singleton dimension.
dim <- which(dim(x) > 1)[1];
}
stopifnot( is.numeric(x)||is.logical(x),
is.numeric(p),
dim <= length(dim(x)) )
## Set the permutation vector.
perm <- seq_along(dim(x))
perm[1] <- dim
perm[dim] <- 1
## Permute dim to the 1st index.
x <- aperm(x, perm);
## Save the size of the permuted x N-d array.
sx = dim(x);
## Reshape to a 2-d array.
dim(x) <- c( sx[1], prod(sx[-1]) );
## Calculate the quantiles.
q = .CallOctave("quantile",x,p)
## Return the shape to the original N-d array.
dim(q) <- c( length(p), sx[-1] )
## Permute the 1st index back to dim.
q = aperm(q, perm);
if( any(dim(q)==1) ) dim(q) <- dim(q)[-which(dim(q)==1)]
q
}