Rcpp和RcppArmadillo都有謂詞來測試NA
,NaN
(R擴展)和Inf
。
這裏是一個短RcppArmadillo例如:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(int n, double threshold=NA_REAL) {
arma::mat M = arma::zeros<arma::mat>(n,n);
if (arma::is_finite(threshold)) M = M + threshold;
return M;
}
/*** R
foo(2)
foo(2, 3.1415)
***/
我們初始化爲零的對於參數的矩陣,並且測試。如果它是有限的(即不是NA
或Inf
或NaN
),那麼我們添加該值。如果你想,你也可以單獨測試可能性。
這產生所需的結果:沒有第二個參數,默認值NA
適用,我們得到一個零矩陣。
R> Rcpp::sourceCpp("/tmp/giorgio.cpp")
R> foo(2)
[,1] [,2]
[1,] 0 0
[2,] 0 0
R> foo(2, 3.1415)
[,1] [,2]
[1,] 3.1415 3.1415
[2,] 3.1415 3.1415
R>
當你說失蹤時,你的意思是「不適用」還是你的意思是你沒有給它任何價值? – stanekam 2014-10-07 17:22:12