forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrixToDataFrame.cpp
54 lines (46 loc) · 1.28 KB
/
matrixToDataFrame.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List matrixToDataFrame(RObject x) {
SEXPTYPE type = TYPEOF(x);
if (!x.hasAttribute("dim"))
stop("`x` is not a matrix");
IntegerVector dim = x.attr("dim");
if (dim.size() != 2)
stop("`x` is not a matrix");
int nrow = dim[0], ncol = dim[1];
List out = List(ncol);
for (int j = 0; j < ncol; ++j) {
out[j] = Rf_allocVector(type, nrow);
SEXP col = out[j];
Rf_copyMostAttrib(x, col);
int offset = j * nrow;
for (int i = 0; i < nrow; ++i) {
switch(type) {
case LGLSXP:
case INTSXP:
INTEGER(col)[i] = INTEGER(x)[offset + i];
break;
case REALSXP:
REAL(col)[i] = REAL(x)[offset + i];
break;
case CPLXSXP:
COMPLEX(col)[i] = COMPLEX(x)[offset + i];
break;
case STRSXP:
SET_STRING_ELT(col, i, STRING_ELT(x, offset + i));
break;
case VECSXP:
SET_VECTOR_ELT(col, i, VECTOR_ELT(x, offset + i));
break;
}
}
}
if (x.hasAttribute("dimnames")) {
List dimnames = x.attr("dimnames");
out.attr("names") = dimnames[1];
}
out.attr("class") = CharacterVector::create("tbl_df", "tbl", "data.frame");
out.attr("row.names") = IntegerVector::create(NA_INTEGER, -nrow);
return out;
}