通过Rcpp中的索引求和

时间:2018-10-01 12:10:25

标签: c++ r rcpp

样本数据

library(dplyr)
library(data.table)
library(Rcpp)

df <- data.frame(year = rep(2003:2004, each = 4), 
             mg = rep(rep(c("a", "b"), each = 2), times = 2),
             plant_date = c(20, 30, 20, 30, 33, 40, 33, 40),
             stage1 = c(40, 50, 42, 52, 43, 55, 48, 57),
             stage2 = c(55, 65, 57, 66, 58, 68, 59, 65),
             stage3 = c(61, 75, 63, 76, 66, 77, 68, 79))

set.seed(123)
dat <- data.frame(year = rep(2003:2004, each = 365), doy = rep(1:365, times = 2), 
              rainfall = sample(0:20, 730, replace = T))

final.dat <- dat %>% dplyr::left_join(df)

我想做的是每年,结合plant.datemg,以及plant.datestage1,{{ 1}}至stage1stage2stage2。我是这样做的:

stage3

我想使用final.dat %>% dplyr::group_by(year, plant_date, mg) %>% dplyr::summarise( sum_rain_stage1 = sum(rainfall[doy >= plant_date & doy <= stage1]), sum_rain_stage2 = sum(rainfall[doy >= plant_date & doy <= stage2]), sum_rain_stage3 = sum(rainfall[doy >= plant_date & doy <= stage3]), mean_rain_stage1 = mean(rainfall[doy >= plant_date & doy <= stage1]), mean_rain_stage2 = mean(rainfall[doy >= plant_date & doy <= stage2]), mean_rain_stage3 = mean(rainfall[doy >= plant_date & doy <= stage3])) 实现类似目的。但是由于缺乏熟悉,我只能按如下方式开发此框架:

Rcpp

定义函数(如下)并提供源代码:

final.dat <- data.table(final.dat)   
setkey(x, year, plant_date, mg, doy)

并按如下所示运行函数:

Rcpp::sourceCpp("rainfall_sum.cpp")) 

我的(不完整)功能是:

 final.dat[, c("sum_rain_stage1","sum_rain_stage2","sum_rain_stage3" , "mean_rain_stage1", , "mean_rain_stage2", "mean_rain_stage3") := rainfall_sum(doy, rainfall, plant_date, stage1, stage2 , stage3), keyby = .(year, plant_date, mg)]

1 个答案:

答案 0 :(得分:-1)

要回答这个问题,这里是汇总元素的函数,请保留练习以计算c ++中的均值。

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double sumRcpp(NumericVector x){
  int n = x.size(); // Size of vector
  double sum = 0; // Sum value
  // For loop, note cpp index shift to 0
  for(int i = 0; i < n; i++){
    // Shorthand for sum = sum + x[i]
    sum += x[i];
  }
  return sum; // Obtain and return the Sum
}

// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically 
// run after the compilation.
//

/*** R
sumRcpp(c(42,43))
*/