1
#include <Rcpp.h>
2
#include <iostream>
3
#include <ctime>
4
#include <algorithm>
5
#include <unordered_map>
6
#include <string>
7
using namespace Rcpp ;
8

9

10
// select the last value of the time period.
11
// [[Rcpp::export]]
12 1
DataFrame reallocateTime_(DataFrame d, const float t_discharge, const float frequency){
13
    // input data
14 1
    NumericVector tin = d["time"];
15 1
    CharacterVector valin = d["item2d"];
16
    // vectors for storing output data
17 1
    std::vector<float> tnew;
18 1
    std::vector<std::string> vnew;
19

20 1
    CharacterVector metain;
21 1
    std::vector<std::string> mnew;
22 1
    std::unordered_map<float, std::string> df_meta;
23

24 1
    int HAS_META = 0;
25
    // initialise meta data column
26 1
    if (d.containsElementNamed("meta")) {
27 1
        CharacterVector metain = d["meta"];
28 1
        for (int i = 0; i < tin.size(); ++i) 
29 1
            df_meta.insert(std::pair<float, std::string>(tin[i], as<std::string>(metain[i])));
30 1
        HAS_META = 1;
31
    }
32

33
    //create a map with tin and tvalin acting as a table.
34 1
    std::unordered_map<float, std::string> df_in;
35 1
    for (int i = 0; i < tin.size(); ++i) {
36 1
            df_in.insert(std::pair<float, std::string>(tin[i], as<std::string>(valin[i])));
37
    }
38 1
    float tt = 0;
39 1
    while(tt <= t_discharge) {
40 1
        vnew.push_back("NA");
41 1
        tnew.push_back(tt);
42 1
        if (HAS_META) mnew.push_back("NA");
43 1
        tt += frequency;
44
    }
45

46 1
    tnew.push_back(1e37);
47 1
    std::sort(tin.begin(), tin.end());
48

49 1
    auto tnew_iter = tnew.begin();
50
    int ind;
51

52 1
    for ( auto t = tin.begin(); t != tin.end(); ++t ) {  
53 1
        while ( tnew_iter != tnew.end() ) {
54 1
            ind = tnew_iter - tnew.begin();
55 1
            if (*t >= 0){
56 1
                if ( *t >= tnew[ind] && *t < tnew[ind + 1] ) {
57 1
                    vnew[ind] = df_in[*t];
58 1
                    if (HAS_META) mnew[ind] = df_meta[*t];
59 1
                    break;
60
                }
61
                else 
62 1
                    tnew_iter++;
63
            }
64 1
            else break; 
65
        }
66
    }
67

68 1
    tnew.pop_back();
69 1
    if (HAS_META)
70 1
        return DataFrame::create(_["time"]=tnew, _["val"]=vnew, _["meta"]=mnew);
71

72 1
    return DataFrame::create(_["time"]=tnew, _["val"]=vnew);
73
}
74

75

Read our documentation on viewing source code .

Loading