0
我最近開始使用Rcpp包將我的R代碼段寫入C++。給定一個數據矩陣,我有以下Rcpp函數,它可以計算一些觀察值的協方差的內核重加估計值。Rcpp錯誤:不兼容的類型(從%s到%s)
cppFunction('
NumericVector get_cov_1obs(NumericMatrix cdata, int ID, float radius){
int nrow = cdata.nrow(), ncol = cdata.ncol();
float norm_ = 0;
float w;
NumericMatrix out(ncol, ncol);
NumericMatrix outer_prod(ncol, ncol);
for (int i=0; i<ncol;i++){
for (int j=0;j<ncol;j++){
out(i,j) = 0;
outer_prod(i,j) = 0;
}
}
for (int i=0; i<nrow;i++){
w = exp(-(i-ID)*(i-ID)/(2*radius));
norm_ += w;
for (int j=0; j<ncol;j++){
for (int k=0;k<ncol;k++){
outer_prod(j,k) = cdata(i,j) * cdata(i,k);
}
}
for (int j=0; j<ncol;j++){
for (int k=0;k<ncol;k++){
out(j,k) += outer_prod(j,k)*w;
}
}
}
for (int i=0; i<ncol;i++){
for (int j=0;j<ncol;j++){
out(i,j) /= norm_;
}
}
return out;
}')
我想快點估計內核rewieghted協方差matricies對數據集中的所有意見,並將它們存儲爲一個數組。由於RCPP不處理數組我寫了下面的一個R函數:
get_kern_cov_C = function(data, radius){
# data is data for which we wish to estimate covariances
# radius is the radius of the gaussian kernel
# calculate covariances:
kern_cov = array(0, c(ncol(data),ncol(data),nrow(data)))
for (i in 1:nrow(data)){
kern_cov[,,i] = get_cov_1obs(cdata=data, ID = i-1, radius=radius)
}
return(kern_cov)
}
這似乎很好地工作(還有很多,很多快於R)但問題是,每一個現在,然後(似乎是隨機的)我得到以下形式的錯誤:
Error in kern_cov[, , i] = get_cov_1obs(cdata = data, ID = i - 1, radius = radius) :
incompatible types (from X to Y)
其中X或者是內置或NULL和ÿ加倍。
我大致瞭解爲什麼會發生這種情況(我試圖將一個內置/ NULL變量放入一個double),但我不確定是在代碼中的錯誤。我懷疑這可能與內存管理有關,因爲它只會一次又一次地發生。
嗨德克,謝謝你的回覆。我對C很陌生,如何去測試NULL? –