从R将整个C++管道作为黑盒运行

Running entire C++ pipeline as blackbox from R

本文关键字:黑盒 运行 管道 C++      更新时间:2023-10-16

我有一个.cpp文件(我认为是一个类),我认为它是一个黑盒:它只需要一个特定格式的.txt文件作为输入,并写入另一个.txt文件作为输出。

如何在R中使用此代码?Rcpp包似乎是可行的,但从浏览网页来看,我看到的所有答案/帖子都涉及从R调用单个C++函数(例如,使用// [[Rcpp::export]])。但就我而言,我对某个特定的功能不感兴趣。我只想把整个C++脚本作为一个黑盒来运行。。。

独立于R,使用C++编译器进行编译

g++ imtd.cpp -o imtd

生成一个可执行文件,然后创建一个R程序来生成输入文件edgelist.txt,使用R shell命令运行可执行文件并在中读取输出文件edgelist-out.txt

shell("imtd edgelist")
# read edgelist-out.txt into R
# - the first field of the first line contains the number of triangles
# - lines containing a comma have 3 fields separated by one or more punctuation characters
# - there are some class counts at the end which we recompute rather than read
L <- readLines("edgelist-out.txt")
no.of.triangles <- read.table(text = L, nrow = 1)[[1]] 
# extract lines with a comma, replace punctuation with space & create 3 column data frame
DF <- read.table(text = gsub("[[:punct:]]", " ", grep(",", L, value = TRUE)))
# rather than read in the class counts compute them from DF
tab <- table(DF$V3) # table of class counts

你不需要Rcpp。如上所述,可以将imtd.cpp文件视为只知道输入和输出文件格式的黑盒。