r - 这在 Rcpp 中是否正确?

标签 r rcpp

我想比较每一列,并在计算后返回所有结果。我尝试编写代码,但结果并不合理。因为如果矩阵中有 5 列,结果的数量将是 5*4/2=10 而不是 5。我认为问题是代码中的 m。我不知道这是否正确。谢谢。

library(Rcpp)
sourceCpp(code='
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h> 

double KS(arma::colvec x, arma::colvec y) {
  int n = x.n_rows;
  arma::colvec w = join_cols(x, y);
  arma::uvec z = arma::sort_index(w);
  w.fill(-1); w.elem( find(z <= n-1) ).ones();
  return max(abs(cumsum(w)))/n;
}
// [[Rcpp::export]]
Rcpp::NumericVector K_S(arma::mat mt) {
  int n = mt.n_cols;
  int m = 1;
  Rcpp::NumericVector results(n);
  for (int i = 0; i < n-1; i++) {
    for (int j = i+1; j < n; j++){
      arma::colvec x=mt.col(i);
      arma::colvec y=mt.col(j);
      results[m] = KS(x, y);
      m ++;
    }
  }
  return results;
}
')

set.seed(1)
mt <- matrix(rnorm(400*5), ncol=5)
result <- K_S(t(mt))
> result
[1] 0.0000 0.1050 0.0675 0.0475 0.0650

最佳答案

您有几个小错误。在修复它时,我刚刚填充了一个类似的 n 乘 n 矩阵的中间版本——这使得索引错误变得显而易见。返回一个 arma::rowvec 也有助于解决可能的越界索引错误(默认情况下会出错)但最后你(在这种情况下!!)实际上可以只增长一个 std: :vector 代替。

代码

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>

double KS(arma::colvec x, arma::colvec y) {
  int n = x.n_rows;
  arma::colvec w = join_cols(x, y);
  arma::uvec z = arma::sort_index(w);
  w.fill(-1); w.elem( find(z <= n-1) ).ones();
  return max(abs(cumsum(w)))/n;
}
// [[Rcpp::export]]
std::vector<double> K_S(arma::mat mt) {
  int n = mt.n_cols;
  std::vector<double> res;
  for (int i = 0; i < n; i++) {
    for (int j = i+1; j < n; j++){
      arma::colvec x=mt.col(i);
      arma::colvec y=mt.col(j);
      res.push_back(KS(x, y));
    }
  }
  return res;
}

/*** R
set.seed(1)
mt <- matrix(rnorm(400*5), ncol=5)
result <- K_S(mt)
result
*/

输出

> Rcpp::sourceCpp("~/git/stackoverflow/73916783/answer.cpp")
> set.seed(1)
> mt <- matrix(rnorm(400*5), ncol=5)
> result <- K_S(mt)
> result
 [1] 0.1050 0.0675 0.0475 0.0650 0.0500 0.0775 0.0575 0.0500 0.0475 0.0600
> 

关于r - 这在 Rcpp 中是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73916783/

相关文章:

r - 在 R 中的数据表中获取 rowSums

rcpp - 使用 Rcpp 和 C++20 的 R 包

r - 在单个 R data.table 中按组有效地锁定

r - 如何在 RcppParallel 中选择 RMatrix 的行或列

c++ - 替换数组中重复的元素

r - 在 ggplot 中创建半离散颜色条

r - 在自适应平滑中提取 P 样条的节点、基、系数和预测

r - 使用 R data.table 的表驱动评估

rcpp - 了解 `Makevars` 以链接到 R 包中的外部 C 库

r - 通过RMySQL连接到sequel pro数据库远程服务器