gpt4 book ai didi

r - 通过引用传递 data.frame 并使用 rcpp 更新它

转载 作者:行者123 更新时间:2023-12-04 01:57:08 24 4
gpt4 key购买 nike

看着rcpp文档和 Rcpp::DataFrame在画廊中,我意识到我不知道如何通过引用修改 DataFrame。谷歌搜索了一下,我在 SO 上找到了这篇文章,在存档中找到了这篇文章。
没有什么明显的,所以我怀疑我错过了一些重要的东西,比如“它已经是这种情况,因为”或“它没有意义,因为”。

我尝试了以下编译但 data.frame传递给 updateDFByRef 的对象在 R 中保持不变

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void updateDFByRef(DataFrame& df) {
int N = df.nrows();
NumericVector newCol(N,1.);
df["newCol"] = newCol;
return;
}

最佳答案

方式DataFrame::operator[]当您执行此操作时,确实实现了副本:

df["newCol"] = newCol;

为了做你想做的,你需要考虑什么是数据框,一个向量列表,具有某些属性。然后您可以通过复制向量(指针,而不是它们的内容)从原始数据中获取数据。

像这样的东西可以做到。这是一个多一点的工作,但不是那么难。
// [[Rcpp::export]]
List updateDFByRef(DataFrame& df, std::string name) {
int nr = df.nrows(), nc= df.size() ;
NumericVector newCol(nr,1.);
List out(nc+1) ;
CharacterVector onames = df.attr("names") ;
CharacterVector names( nc + 1 ) ;
for( int i=0; i<nc; i++) {
out[i] = df[i] ;
names[i] = onames[i] ;
}
out[nc] = newCol ;
names[nc] = name ;
out.attr("class") = df.attr("class") ;
out.attr("row.names") = df.attr("row.names") ;
out.attr("names") = names ;
return out ;
}

这种方法存在一些问题。您的原始数据框和您创建的数据框共享相同的向量,因此可能会发生不好的事情。因此,仅当您知道自己在做什么时才使用它。

关于r - 通过引用传递 data.frame 并使用 rcpp 更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com