r - 在 Rcpp 中生成多元高斯分布

标签 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

其他人也有这个问题吗?

非常感谢任何帮助!

最佳答案

今天上传到 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++代码,只是将西格玛调整为小写西格玛。

关于r - 在 Rcpp 中生成多元高斯分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760655/

相关文章:

r - 包构建上的小插图创建失败,错误为 "Failed to locate the ‘weave’ 输出文件”

c++ - C++ 函数内的条件操作不会损失速度或代码重复 : use macros, 内联函数、模板或其他?

Rcpp 函数崩溃

gcc - 使用 R 内联链接到另一个包

r - 如何以一种好的方式可视化数据框?

r 中其他列的数字复制

r - 编译 Rpackage : error in asNamespace(ns) using Rcpp 的问题

c++ - 将 StringVector 与 Rcpp 连接起来

r - 使用 knitr 从 R 中编写 html

r - 使用 ggplot 在背景图像上绘制数据