I would like to place the double (precision floating point) values returned from the fisher.test function into 2 vectors, from within R C++.
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:
// 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).
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];
but the IDE tells me this is assigning from an incompatible type.
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?
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
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