问题描述
假设我在 Rcpp 中有一个 List
,这里称为 x
包含矩阵.我可以使用 x[0]
或其他东西提取其中一个元素.但是,如何提取该矩阵的特定元素?我的第一个想法是 x[0](0,0)
但这似乎不起作用.我尝试使用 *
标志但也不起作用.
Suppose I have a List
in Rcpp, here called x
containing matrices. I can extract one of the elements using x[0]
or something. However, how do I extract a specific element of that matrix? My first thought was x[0](0,0)
but that does not seem to work. I tried using *
signs but also doesn't work.
这是一些打印矩阵的示例代码(显示矩阵可以轻松提取):
Here is some example code that prints the matrix (shows matrix can easily be extracted):
library("Rcpp")
cppFunction(
includes = '
NumericMatrix RandMat(int nrow, int ncol)
{
int N = nrow * ncol;
NumericMatrix Res(nrow,ncol);
NumericVector Rands = runif(N);
for (int i = 0; i < N; i++)
{
Res[i] = Rands[i];
}
return(Res);
}',
code = '
void foo()
{
List x;
x[0] = RandMat(3,3);
Rf_PrintValue(wrap( x[0] )); // Prints first matrix in list.
}
')
foo()
如何更改 Rf_PrintValue(wrap( x[0] ));
行以打印第一行和第一列中的元素?在我想使用它的代码中,我需要提取这个元素来进行计算.
How could I change the line Rf_PrintValue(wrap( x[0] ));
here to print the the element in the first row and column? In the code I want to use it for I need to extract this element to do computations.
推荐答案
快速解决方案:
C++ 中的复合表达式有时会咬人;模板魔法妨碍了.因此,只需将
List
对象分配给任何元素,例如NumericMatrix
.
Compound expression in C++ can bite at times; the template magic gets in the way. So just assign from the
List
object to a whatever the element is, eg aNumericMatrix
.
然后从 NumericMatrix
中选择您认为合适的.我们有行、列、元素、...访问.
Then pick from the NumericMatrix
as you see fit. We have row, col, element, ... access.
使用 Rcpp::Rcout << 可以更轻松地打印anElement
但请注意,我们目前无法打印整个矩阵或向量——但 int
或 double
类型很好.
Printing can be easier using Rcpp::Rcout << anElement
but note that we currently cannot print entire matrices or vectors -- but the int
or double
types are fine.
这是一个示例实现.
#include <Rcpp.h>
// [[Rcpp::export]]
double sacha(Rcpp::List L) {
double sum = 0;
for (int i=0; i<L.size(); i++) {
Rcpp::NumericMatrix M = L[i];
double topleft = M(0,0);
sum += topleft;
Rcpp::Rcout << "Element is " << topleft << std::endl;
}
return sum;
}
/*** R
set.seed(42)
L <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))
sacha(L) # fix typo
*/
及其结果:
R> Rcpp::sourceCpp('/tmp/sacha.cpp')
R> set.seed(42)
R> L <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))
R> sacha(L)
Element is 1.37096
Element is 1
Element is 1
[1] 3.37096
R>
这篇关于Rcpp 中列表的索引元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!