gpt4 book ai didi

c++ - 在 rcpp 中将列表转换为矩阵

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:51 26 4
gpt4 key购买 nike

我想转换一个列表,例如像这样:

[[1]]
[1] 3 4 99 1 222

[[2]]
[1] 1 2 3 4 5

到 Rcpp 中的矩阵 (2,5)。最快的方法是什么?

函数 wrap() 在这种情况下不起作用。

我首先尝试将列表转换为 vector ,然后再转换为矩阵。在函数中使用 wrap():

#include <Rcpp.h>
using namespace Rcpp ;


// [[Rcpp::export]]
NumericVector mat(List a){
NumericVector wynik;
wynik = Rcpp::wrap(a);
return wynik;
}

/***R
mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
*/

我收到一个错误:

>   mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
Error in eval(substitute(expr), envir, enclos) :
not compatible with requested type

最佳答案

与其将 cbindt 仅用于一次迭代,不如初始化一个矩阵,然后用必要的维度检查逐行填充会更好。

代码

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericMatrix make_mat(Rcpp::List input_list){

unsigned int n = input_list.length();

if(n == 0) {
Rcpp::stop("Must supply a list with more than 1 element.");
}

Rcpp::NumericVector testvals = input_list[0];
unsigned int elems = testvals.length();

Rcpp::NumericMatrix result_mat = Rcpp::no_init(n, elems);

// fill by row
for(unsigned int i = 0; i < n; i++) {
Rcpp::NumericVector row_val = input_list[i];

if(elems != row_val.length()) {
Rcpp::stop("Length of row does not match matrix requirements");
}

result_mat(i, Rcpp::_) = row_val;

}

return result_mat;
}

结果

make_mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 3 4 99 1 222
# [2,] 1 2 3 4 5

关于c++ - 在 rcpp 中将列表转换为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41084010/

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