如何在 RCpp 中向数据框添加新列? [英] How can I add a new column to dataframe in RCpp?

查看:33
本文介绍了如何在 RCpp 中向数据框添加新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 RCpp 向数据框中添加一个新列.

I am trying to add a new column to data frame using RCpp.

在下面的代码中,我打算向数据框 df 添加一个结果"列.但是运行代码后数据集没有结果"列.你能告诉我他们有什么问题吗?

In the following codes, I intend to add a "result" column to dataframe, df. But the dataset does not have "result" column after running the codes. Could you tell me what is wrong with them?

R 文件调用 AddNewCol() 函数.

R file to call AddNewCol() function.

library(Rcpp)
sourceCpp('AddNewCol.cpp')
AddNewCol( df ,"result")

AddNewCol.cpp

AddNewCol.cpp

#include <Rcpp.h>
#include<math.h>
using namespace Rcpp;
// [[Rcpp::export]]
void AddNewCol(DataFrame& df, std::string new_var) {
  int maxRow = df.nrows();
  NumericVector vec_x = df["x"];
  NumericVector vec_y = df["y"];
  NumericVector resultvec = NumericVector(maxRow);

  for( int i = 0 ; i < maxRow; i++ ){
    resultvec[i] = vec_x[i] * pow( vec_y[i] , 2 );  
  }
  df[new_var] = resultvec;
}

推荐答案

你不能通过引用来做.但是,如果您返回数据框,它会起作用:

You cannot do it by reference. But if you return the data frame it works:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
DataFrame AddNewCol(const DataFrame& df, std::string new_var) {
  NumericVector vec_x = df["x"];
  NumericVector vec_y = df["y"];
  df[new_var] = vec_x * Rcpp::pow(vec_y, 2);
  return df;
}

/*** R
set.seed(42)
df <- data.frame(x = runif(10), y = runif(10))
AddNewCol( df ,"result")
*/

请注意,我冒昧地稍微简化了计算.结果:

Note that I have taken the liberty to simplify the computation a bit. Result:

> set.seed(42)

> df <- data.frame(x = runif(10), y = runif(10))

> AddNewCol( df ,"result")
           x         y      result
1  0.9148060 0.4577418 0.191677054
2  0.9370754 0.7191123 0.484582715
3  0.2861395 0.9346722 0.249974991
4  0.8304476 0.2554288 0.054181629
5  0.6417455 0.4622928 0.137150421
6  0.5190959 0.9400145 0.458687354
7  0.7365883 0.9782264 0.704861206
8  0.1346666 0.1174874 0.001858841
9  0.6569923 0.4749971 0.148232064
10 0.7050648 0.5603327 0.221371155

这篇关于如何在 RCpp 中向数据框添加新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆