在Rcpp中生成多元高斯分布

时间:2019-09-02 17:10:19

标签: r rcpp

我在此处使用此链接获取一些Rcpp代码,以根据多元高斯分布生成样本:https://gallery.rcpp.org/articles/simulate-multivariate-normal/

Rcpp代码:

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

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat mvrnormArma(int n, arma::vec mu, arma::mat sigma) {
   int ncols = sigma.n_cols;
   arma::mat Y = arma::randn(n, ncols);
   return arma::repmat(mu, 1, n).t() + Y * arma::chol(sigma);
}

R代码:

mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))

直到最近,它都可以正常工作,并且出现以下错误:

error: Mat::init(): requested size is not compatible with column vector layout

还有其他人有这个问题吗?

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

今天上传到CRAN的版本适合我。您声明哪个版本有误?

R> library(RcppArmadillo)
R> packageVersion("RcppArmadillo")
[1] ‘0.9.700.2.0’
R> Rcpp::sourceCpp("~/git/stackoverflow/57760655/question.cpp")

R> #mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))
R> set.seed(123)  # make it reproducible
R> mvrnormArma(n = 10, mu = c(0, 0), sigma = matrix(c(1,0,0,1), 2, 2))
            [,1]      [,2]
 [1,] -0.6853851  1.811730
 [2,]  0.9302219  0.741069
 [3,] -0.2260918 -0.119390
 [4,]  0.9513753  0.315338
 [5,]  0.0699539  0.670879
 [6,]  0.9767215  0.332053
 [7,]  2.1650415  0.966927
 [8,] -1.8262054  1.294966
 [9,]  0.5804146  1.062635
[10,] -0.0592898  2.270198
R>

我照原样使用了C ++代码,只是将Sigma调整为小写的sigma。