简体   繁体   English

将 R 列表中的数值直接分配给 C++ 中的 NumericVector

[英]Assigning a numeric value within an R List directly to a NumericVector in C++

I would like to place the double (precision floating point) values returned from the fisher.test function into 2 vectors, from within R C++.我想将从 fisher.test function 返回的双精度(精度浮点)值放入 R C++ 内的 2 个向量中。

When assigning to a double as below, things work as expected for the p value, and the lower bound of the confidence interval, but not for the upper bound of the confidence interval:如下所示分配给 double 时,p 值和置信区间的下限会按预期工作,但置信区间的上限不会:

// perform Fisher Exact test
IntegerVector v = { 1, 2, 3, 4 };
v.attr("dim") = Dimension(2, 2);
Function f("fisher.test");
List fe = f(v);
// now assign to variables
List sublist = fe["p.value"];
double pValue = sublist[0];
Rcout << "pValue:" << pValue;
sublist = fe["conf.int"];
NumericVector cis = sublist[0];
double ci_upperBound = cis[1];
Rcout << "ub:" << ci_upperBound ;

However assigning to the NumericVectors as below doesn't work (values are assigned, but not the correct values, as if the pointer is misaligned).但是,如下所示分配给 NumericVectors 不起作用(分配了值,但不是正确的值,就好像指针未对齐一样)。

NumericVector pValues(1);
NumericVector ciLowerBounds(1);
// (then perform Fisher test as per above)
// now assign to variables
List sublist = fe["p.value"];
pValues[0] = sublist[0];
Rcout << "pValue:" << pValues[0];
sublist = fe["conf.int"];
NumericVector cis = sublist[0];
ciUpperBounds[0] = cis[1];

I have tried using pValues[0] = Rcpp::as<double>sublist[0];我试过使用pValues[0] = Rcpp::as<double>sublist[0]; but the IDE tells me this is assigning from an incompatible type.但是 IDE 告诉我这是从不兼容的类型分配的。

Can you please help me assign the p.value and lupper bound of the confidence interval directly to the respective NumericVectors at the appropriate indicies?您能帮我将置信区间的 p.value 和 lupper 界限直接分配给适当指标的相应 NumericVectors 吗?

Your question and example isn't entirely clear to me, but I think part of your issue is the elements of your List fe are already vectors (not lists, as youv'e assumed with your sublist object), so you can extract them direclty你的问题和例子对我来说并不完全清楚,但我认为你的问题的一部分是你的List fe的元素已经是向量(不是列表,正如你对你的sublist对象所假设的那样),所以你可以直接提取它们

library(Rcpp)

cppFunction(
  code = '
    SEXP test( IntegerVector v ) {
      v.attr("dim") = Dimension(2, 2);

      Function f("fisher.test");
      List fe = f(v);

      NumericVector p = fe["p.value"];
      NumericVector ci = fe["conf.int"];

      return List::create(
        _["p"] = p,
        _["ci"] = ci
      );
    }
  '
)

v <- 1:4
test(v)
# $p
# [1] 1
# 
# $ci
# [1]  0.008512238 20.296715040
# attr(,"conf.level")
# [1] 0.95

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM