【发布时间】:2019-08-01 03:42:45
【问题描述】:
如何使用 Rcpp 将 R 对象交给 C++?
嘿,我是 Rcpp 的新手,遇到以下问题(这可能很简单,但我无法弄清楚)。我首先在 R 中创建了一个列表、向量和一个数据框。我想将这些 R 对象传递给 C++ 以修改列表,然后将修改后的列表再次返回给 R 以进行进一步分析。
我在 Rstudio 中做了一个 cpp 文件的例子:
#include <Rcpp.h>
using namespace Rcpp;
/*** R
mylist <- list(mat1 = data.frame(Col1 = c('id1','id2','id3'), Col2 = c(5,6,7), Col3 = as.factor(c('blue','green','black'))),
mat2 = data.frame(Col1 = c('id1','id2','id3'), Col2 = c(5,6,7), Col3 = as.factor(c('blue','green','black'))),
mat3 = data.frame(Col1 = c('id1','id2','id3'), Col2 = c(5,6,7), Col3 = as.factor(c('blue','green','black'))),
mat4 = data.frame(Col1 = c('id1','id2','id3'), Col2 = c(5,6,7), Col3 = as.factor(c('blue','green','black'))))
myvector1 <- c(seq(8,10,1))
myvector2 <- c(seq(101,103,1))
mydataframe <- data.frame(Col1 = c('id3','id4','id5'), Col2 = seq(21,23,1), Col3 = as.factor(c('blue','green','black')))
*/
// [[Rcpp::export]]
// Some code modifying mylist with myvector1, myvector2 and mydataframe and returning the modified list again to R
// Let's say Col2 of mat1 of mylist shall be multiplied with myvector1 and Col 2 of mat2 with myvector2.
// Col2 of mat4 shall be divided by Col2 of mydataframe
// And then the modified mylist should be returned
}
/*** R
# Some analysis with the new modified list generated in the C++ code
summary(mylist$mat2$Col2)
*/
我怎样才能使这样的操作通常有效(实际上我的列表要大得多)?还是使用带有 cxxfunction 函数的 Rscript 更好?感谢您的帮助!
【问题讨论】: