I am trying to add a new column to data frame using RCpp.
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 file to call AddNewCol() function.
library(Rcpp)
sourceCpp('AddNewCol.cpp')
AddNewCol( df ,"result")
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;
}