将NumericVector分配给DataFrame的列

悠天

假设我cfVecCpp编写了一个工作函数RCpp函数接受aNumericVector并返回NumericVector相同长度的a(并且行为正确)。我尝试将其作为元素的循环运行时遇到错误DataFrame

这是我的代码:

#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;
using namespace std;

//[[Rcpp::export]]
NumericVector cfVecCpp(NumericVector x,int maxfill=-1){
 .... // code works fine here
}

//[[Rcpp::export]]
DataFrame cfDFCpp(DataFrame x, int maxfill=-1) {
  int nRows=x.nrows();
  int nCols=x.size();

  DataFrame z;
  for (int i=0;i<nCols;i++) {
    NumericVector tmp=cfVecCpp(x[i],maxfill);
    // tmp.attr("dim")=Dimension(nRows,1);
    z[i]=wrap(tmp); // alternative z[i]=tmp;
  }
  // z.attr("names")=x.attr("names");
  return z;
}

cfDFCpp函数只是尝试遍历的列x,执行一个cfVecCpp操作,然后返回输出。

该代码可以很好地编译。但是,当我尝试在RStudio中运行代码时,如下所示:

y<-cfDFCpp(x) # where x is data frame whose all columns are numeric

我收到一个错误:

Error in cfDFCpp(x) : 
  attempt to set index 0/0 in SET_VECTOR_ELT

我尝试提供属性(请参阅注释掉的代码//行),但是错误不会消失。可能是什么问题?

我甚至试图取代z[i]=wrap(tmp);z[i]=tmp;代码可以正常编译,但是在中运行函数时出现相同的错误RStudio

沙美尔

如果创建了空的数据框z,则无法设置z[i]您需要使用该push_back()功能。请参阅在Rcpp中构造数据框以了解如何构造数据框

这是您问题的答案。

#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;
using namespace std;

//[[Rcpp::export]]
NumericVector cfVecCpp(NumericVector x,int maxfill=-1){
  return(x * 2);
}

//[[Rcpp::export]]
DataFrame cfDFCpp(DataFrame x, int maxfill=-1) {
  int nCols =x.length();
  List zlist(nCols);

  for (int i=0;i<nCols;i++) {
    zlist[i] =cfVecCpp(x[i],maxfill);
  }
  zlist.attr("names") = x.attr("names");
  DataFrame z(zlist); // convert list to DataFrame
  z.attr("row.names") = x.attr("row.names");
  return z;
}

然后,在R中成功运行sourceCpp之后,您可以执行

> data(freeny)

> tail(freeny, 2)
              y lag.quarterly.revenue price.index income.level
1971.5  9.77536               9.74924     4.27839      6.19377
1971.75 9.79424               9.77536     4.27789      6.20030
        market.potential
1971.5           13.1625
1971.75          13.1664
> tail(cfDFCpp(freeny), 2)
               y lag.quarterly.revenue price.index income.level
1971.5  19.55072              19.49848     8.55678     12.38754
1971.75 19.58848              19.55072     8.55578     12.40060
        market.potential
1971.5           26.3250
1971.75          26.3328

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章