将NumericVector分配给数据帧的一列

将NumericVector分配给数据帧的一列,r,rcpp,R,Rcpp,假设我有一个用RCpp编写的工作函数cfVecCpp,它接受一个NumericVector,并返回一个长度相同的NumericVector(并且运行正常)。当我尝试在数据帧的元素上以循环的形式运行此操作时,我会出错 这是我的密码: #include <Rcpp.h> #include <algorithm> using namespace Rcpp; using namespace std; //[[Rcpp::export]] NumericVector cfVecC

假设我有一个用
RCpp
编写的工作函数
cfVecCpp
,它接受一个
NumericVector
,并返回一个长度相同的
NumericVector
(并且运行正常)。当我尝试在
数据帧的元素上以循环的形式运行此操作时,我会出错

这是我的密码:

#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;
}
我得到一个错误:

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()
功能。请参阅以了解如何构造数据帧

这是你问题的答案

#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;
}

由于某种原因,我无法编译您的函数
#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;
}
> 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