1
#include <Rcpp.h>
2
// [[Rcpp::plugins(cpp11)]]
3

4
using namespace Rcpp;
5

6

7
  #include <vector>
8

9
// [[Rcpp::export]]
10

11 4
  Rcpp::DataFrame rcpp_Polygons2PolySet(Rcpp::List polys, std::size_t n_preallocate=10000) {
12
    // init
13
    /// declare, define, preallocate main vars
14 4
    int curr_pid=0;
15 4
    int curr_sid=0;
16 4
    int curr_pos=0;
17 4
    std::vector<int> PID;
18 4
    std::vector<int> SID;
19 4
    std::vector<int> POS;
20 4
    std::vector<double> X;
21 4
    std::vector<double> Y;
22 4
    PID.reserve(n_preallocate);
23 4
    SID.reserve(n_preallocate);
24 4
    POS.reserve(n_preallocate);
25 4
    X.reserve(n_preallocate);
26 4
    Y.reserve(n_preallocate);
27
    
28
    // declare temporary vars
29 4
    Rcpp::List tmp_list;
30 4
    NumericMatrix tmp_matrix;
31
  
32
    /// main processing
33 4
    for (int i=0; i!=polys.size(); ++i) {
34
      // set ids
35 4
      ++curr_pid;
36 4
      curr_sid=0;
37
      // extract polygons
38 4
      tmp_list=Rcpp::as<Rcpp::S4>(polys[i]).slot("Polygons");
39 4
      for (int j=0; j!=tmp_list.size(); ++j) {
40
        // extract polygon
41 4
        curr_pos=0;
42 4
        ++curr_sid;
43 4
        tmp_matrix=Rcpp::as<Rcpp::NumericMatrix>(Rcpp::as<Rcpp::S4>(tmp_list[j]).slot("coords"));
44
        // store ids and coordinates
45 4
        for (int k=0; k!=tmp_matrix.nrow(); ++k) {
46 4
          ++curr_pos;
47 4
          PID.push_back(curr_pid);
48 4
          SID.push_back(curr_sid);
49 4
          POS.push_back(curr_pos);
50 4
          X.push_back(tmp_matrix(k,0));
51 4
          Y.push_back(tmp_matrix(k,1));
52
        }
53
        
54
      }
55
    }
56

57
    /// exports
58
    Rcpp::DataFrame df=Rcpp::DataFrame::create(
59 4
      Rcpp::Named("PID")=PID,
60 4
      Rcpp::Named("SID")=SID,
61 4
      Rcpp::Named("POS")=POS,
62 4
      Rcpp::Named("X")=X,
63 4
      Rcpp::Named("Y")=Y
64
    );
65 4
    df.attr("class")=CharacterVector::create("PolySet", "data.frame");
66 4
    return(df);
67
  }
68
 

Read our documentation on viewing source code .

Loading