【发布时间】:2015-11-12 07:49:40
【问题描述】:
是否可以编写一个 C++ 函数,获取一个 R 数据帧作为输入,然后修改数据帧(在我们的例子中取一个子集)并返回新的数据帧(在这个问题中,返回一个子数据帧)? 我下面的代码可能会让我的问题更清楚:
代码:
# Suppose I have the data frame below created in R:
myDF = data.frame(id = rep(c(1,2), each = 5), alph = letters[1:10], mess = rnorm(10))
# Suppose I want to write a C++ function that gets id as inout and returns
# a sub-dataframe corresponding to that id (**If it's possible to return
# DataFrame in C++**)
# Auxiliary function --> helps get a sub vector:
arma::vec myVecSubset(arma::vec vecMain, arma::vec IDVec, int ID){
arma::uvec AuxVec = find(IDVec == ID);
arma::vec rslt = arma::vec(AuxVec.size());
for (int i = 0; i < AuxVec.size(); i++){
rslt[i] = vecMain[AuxVec[i]];
}
return rslt;
}
# Here is my C++ function:
Rcpp::DataFrame myVecSubset(Rcpp::DataFrame myDF, int ID){
arma::vec id = Rcpp::as<arma::vec>(myDF["id"]);
arma::vec alph = Rcpp::as<arma::vec>(myDF["alpha"]);
arma::vec mess = Rcpp::as<arma::vec>(myDF["mess"]);
// here I take a sub-vector:
arma::vec id_sub = myVecSubset(id, id, int ID);
arma::vec alph_sub = myVecSubset(alph, id, int ID);
arma::vec mess_sub = myVecSubset(mess, id, int ID);
// here is the CHALLENGE: How to combine these vectors into a new data frame???
???
}
总结起来,其实主要有两个问题: 1) 有没有更好的方法在 C++ 中获取上面的子数据帧? (希望我能简单地说 myDF[myDF$id == ID,]!!!)
2) 无论如何我可以将 id_sub、alpha_sub 和 mess_sub 组合成一个 R 数据帧并返回它?
非常感谢您的帮助。
【问题讨论】: