Skip to content

Commit c5ad3c2

Browse files
committed
'make_table' helper for creating table from SEXP
1 parent 19b5d68 commit c5ad3c2

File tree

4 files changed

+64
-1
lines changed

4 files changed

+64
-1
lines changed

inst/include/RcppNT2/convert/as.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,4 @@
22
#define RCPP_NT2_CONVERT_AS_H
33

44

5-
65
#endif /* RCPP_NT2_CONVERT_AS_H */

inst/include/RcppNT2/core/core.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#ifndef RCPP_NT2_CORE_CORE_H
22
#define RCPP_NT2_CORE_CORE_H
33

4+
#include <RcppNT2/core/create.h>
5+
46
namespace RcppNT2 {
57

68
template <typename T>

inst/include/RcppNT2/core/create.h

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#ifndef RCPP_NT2_CORE_CREATE_H
2+
#define RCPP_NT2_CORE_CREATE_H
3+
4+
#define R_NO_REMAP
5+
#include <R.h>
6+
#include <Rinternals.h>
7+
8+
namespace RcppNT2 {
9+
10+
template <typename T, int RTYPE>
11+
nt2::table<T> make_table_vector_impl(SEXP data)
12+
{
13+
int n = Rf_length(data);
14+
15+
T* ptr = reinterpret_cast<T*>(STRING_PTR(data));
16+
return nt2::table<T>(nt2::of_size(n, 1), ptr, ptr + n);
17+
}
18+
19+
template <typename T, int RTYPE>
20+
nt2::table<T> make_table_matrix_impl(SEXP data)
21+
{
22+
int nr = Rf_nrows(data);
23+
int nc = Rf_ncols(data);
24+
int n = Rf_length(data);
25+
26+
T* ptr = reinterpret_cast<T*>(STRING_PTR(data));
27+
return nt2::table<T>(nt2::of_size(nr, nc), ptr, ptr + n);
28+
}
29+
30+
template <typename T, int RTYPE>
31+
nt2::table<T> make_table_impl(SEXP data)
32+
{
33+
if (Rf_isMatrix(data))
34+
return make_table_matrix_impl<T, RTYPE>(data);
35+
else
36+
return make_table_vector_impl<T, RTYPE>(data);
37+
}
38+
39+
template <typename T>
40+
nt2::table<T> make_table(SEXP data)
41+
{
42+
switch (TYPEOF(data))
43+
{
44+
case REALSXP: return make_table_impl<double, REALSXP>(data);
45+
// case INTSXP: return make_table_impl<int, INTSXP>(data); // TODO: fails to compile?
46+
default:
47+
Rf_warning("can't create an 'nt2::table' from type '%s'", Rf_type2char(TYPEOF(data)));
48+
return nt2::table<T>();
49+
}
50+
}
51+
52+
} // namespace RcppNT2
53+
54+
#endif /* RCPP_NT2_CORE_CREATE_H */
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#ifndef RCPP_NT2_TRAITS_TRAITS_h
2+
#define RCPP_NT2_TRAITS_TRAITS_h
3+
4+
template <int RTYPE> struct storage_type {};
5+
template <> struct storage_type<REALSXP> { typedef double type; };
6+
template <> struct storage_type<INTSXP> { typedef int type; };
7+
8+
#endif /* RCPP_NT2_TRAITS_TRAITS_h */

0 commit comments

Comments
 (0)