更新时间:2023-08-19 17:22:28
你不能通过引用来做.但是,如果您返回数据框,它会起作用:
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