Rcpp: Is there an implementation fisher.test() in Rcpp [closed]

て烟熏妆下的殇ゞ 提交于 2019-12-13 23:24:17

问题


Is there an implementation of fisher.test for Rcpp?


回答1:


There is no current implementation of the fisher.test function within Rcpp. A specific component of the test in the R function is written in C due to the computational intensity of it. You are more than welcome to reimplement the test in Rcpp.

A few notes on that though, there is no representation of a factor in a SEXP object. Thus, factor not something Rcpp that supports. As a result, you would have to convert the object into an integer or character type before passing it into C++.

In order to use it for Rcpp, you would have to call the fisher.test R function from C++. That is, you would have to transfer the data back into R.

e.g.

#include <Rcpp.h>

//' @title Accessing R's fisher.test function from Rcpp
// [[Rcpp::export]]
Rcpp::List fisher_test_cpp(const Rcpp::NumericMatrix& x, double conf_level = 0.95){

  // Obtain environment containing function
  Rcpp::Environment base("package:stats"); 

  // Make function callable from C++
  Rcpp::Function fisher_test = base["fisher.test"];    

  // Call the function and receive its list output
  Rcpp::List test_out = fisher_test(Rcpp::_["x"] = x,
                                    Rcpp::_["conf.level"]  = conf_level);

  // Return test object in list structure
  return test_out;
}

/***R

Job = matrix(c(1,2,1,0, 3,3,6,1, 10,10,14,9, 6,7,12,11), 4, 4,
              dimnames = list(income = c("< 15k", "15-25k", "25-40k", "> 40k"),
                              satisfaction = c("VeryD", "LittleD", "ModerateS", "VeryS")))
fisher.test(Job)

fisher_test_cpp(Job)

*/

Note the cpp function returns objects in list form under:

List of 7
 $ p.value    : num 0.783
 $ alternative: chr "two.sided"
 $ method     : chr "Fisher's Exact Test for Count Data"
 $ data.name1 : chr "structure(c(1, 2, 1, 0, 3, 3, 6, 1, 10, 10, 14, 9, 6, 7, 12, "
 $ data.name2 : chr "11), .Dim = c(4L, 4L), .Dimnames = structure(list(income = c(\"< 15k\", "
 $ data.name3 : chr "\"15-25k\", \"25-40k\", \"> 40k\"), satisfaction = c(\"VeryD\", \"LittleD\", "
 $ data.name4 : chr "\"ModerateS\", \"VeryS\")), .Names = c(\"income\", \"satisfaction\")))"
 - attr(*, "class")= chr "htest"

These values can be accessed using:

 double p_value = test_out[0];
 std::string alternative = test_out[1];
 std::string method = test_out[2];

And so on...



来源:https://stackoverflow.com/questions/37737308/rcpp-is-there-an-implementation-fisher-test-in-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!