简体   繁体   English

从Rcpp内调用igraph

[英]Calling igraph from within Rcpp

As a part of utilizing network data drawn at random before further processing, I am trying to call a couple of functions from the igraph package at the beginning of each iteration. 作为利用在进一步处理之前随机抽取的网络数据的一部分,我试图在每次迭代的开始从igraph包中调用几个函数。 The code I use is as follows: 我使用的代码如下:

#define ARMA_64BIT_WORD
#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
using namespace Rcpp;

using arma::sp_mat;

// [[Rcpp::export]]
sp_mat adj_mat(int n, double p) {

  Environment igraph("package:igraph");
  Function game_er = igraph["erdos.renyi.game"];
  Function get_adjacency = igraph["get.adjacency"];

  List g = game_er(Named("n", n), Named("p", p));

  NumericMatrix A_m = get_adjacency(Named("g", g));

  sp_mat A = as<sp_mat>(A_m);

  return A;
}


/*** R
set.seed(20130810)
library(igraph)

adj_mat(100, 0.5)
*/

So, while the C++ compiles without warnings, the following error is thrown: 因此,尽管C ++编译时没有警告,但会引发以下错误:

> sourceCpp("Hooking-R-in-cpp.cpp")

> set.seed(20130810)

> library(igraph)

> adj_mat(100, 0.5)
Error in adj_mat(100, 0.5) : 
  Not compatible with requested type: [type=S4; target=double].

From the error it looks like I am passing a S4 class to a double? 从错误看起来我正在将S4类传递给double? Where is the error? 错误在哪里?

You were imposing types in the middle of your C++ functions that did not correspond to the representation, so you got run-time errors trying to instantiate them. 您在C ++函数的中间强加了与表示形式不符的类型,因此在尝试实例化它们时遇到了运行时错误。

The version below works. 以下版本适用。 I don't know igraph well enough to suggest what else you use to store the first return; 我对igraph不太了解,无法建议您用来存储首次回报的其他内容; for the S4 you can use the dgCMatrix matrix but S4 is an ok superset. 对于S4您可以使用dgCMatrix矩阵,但是S4是可以的超集。

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
using namespace Rcpp;

using arma::sp_mat;

// [[Rcpp::export]]
sp_mat adj_mat(int n, double p) {

  Environment igraph("package:igraph");
  Function game_er = igraph["erdos.renyi.game"];
  Function get_adjacency = igraph["get.adjacency"];

  SEXP g = game_er(Named("n", n), Named("p", p));

  S4 A_m = get_adjacency(Named("g", g));

  sp_mat A = as<sp_mat>(A_m);

  return A;
}

/*** R
set.seed(20130810)
library(igraph)

adj_mat(100, 0.5)
*/

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

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