从R运行整个C ++管道作为blackbox

时间:2016-04-03 19:03:06

标签: c++ r rcpp

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

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

1 个答案:

答案 0 :(得分:3)

独立于R,使用您的C ++编译器

进行编译
g++ imtd.cpp -o imtd

生成可执行文件,然后创建一个R程序来生成输入文件edgelist.txt,使用R shell命令运行可执行文件并读回输出文件edgelist-out.txt:< / p>

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文件视为黑盒子,只需要知道输入和输出文件的格式。