gpt4 book ai didi

r - 将 lambda 向量传递给 Rcpp 的 rpois

转载 作者:行者123 更新时间:2023-12-04 18:41:59 24 4
gpt4 key购买 nike

在 R 中,rpois可以传递一个描述多个泊松分布的 lambda 向量,例如

rpois(5, (1:5)*1000)

# [1] 1043 1974 3002 3930 4992

上图中,输出向量的每个元素均来自不同的泊松分布,均值分别为 1000、2000、3000、4000 和 5000。

如果我有一个 arma::mat (使用这些是因为我在其他地方使用立方体)包含泊松分布的 lambda,将这些(一次一行)传递给 rpois 的最佳方法是什么?在 Rcpp 内?

这是一个玩具示例,以及随后的错误消息的摘录:
library(inline)
library(RcppArmadillo)
code <- "
using namespace Rcpp;
using namespace arma;
arma_rng::set_seed(42); // Dirk's seed of choice

mat lam = randu(5, 5); // ignore the fact these are all 0-1
mat out(5, 5);

for (int i = 0; i < 5; i++) {
out.row(i) = rpois(5, lam.row(i));
}

return(wrap(out));
"

f <- cxxfunction(body=code, plugin="RcppArmadillo")

# cannot convert 'arma::subview_row<double>' to 'double' for argument '2'
# to 'Rcpp::NumericVector Rcpp::rpois(int, double)'

我必须承认我对 C++ 中的类型转换的理解很差。我正在尝试做的事情是可能的(我的猜测是否定的,因为似乎 rpois 期待双倍),还是我需要迭代矩阵的每个单元格,每次生成一个偏差?

最佳答案

从 C/C++ 中,您可以访问至少 2 个泊松偏差生成例程(在此 online manual 中搜索 rpois)。

他们的声明如下:

double R::rpois(double mu);
NumericVector Rcpp::rpois(int n, double mu);

它们都不允许在 mu 中传递 > 1 个值(又名 lambda)。第一个函数是R的原始例程,用于实现 rpois正如我们从 R stats 中知道的那样包(一个向量化的 w.r.t. 所有参数)。给定一个 mu ,它返回单个(伪)随机偏差。

第二个就是所谓的 Rcpp糖功能。它允许计算 n一次偏离并将它们作为 NumericVector 返回(再次使用 R::rpois )。

换句话说,您应该使用两个嵌套的 for通过调用 R::rpois 循环填充矩阵.不要害怕这样的方法,这就是 C++。 :)

关于r - 将 lambda 向量传递给 Rcpp 的 rpois,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24216904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com