Debian Codegraph @

inst/include/sourcetools/r/RFunctions.h

raw
1 #ifndef SOURCETOOLS_R_R_FUNCTIONS_H
2 #define SOURCETOOLS_R_R_FUNCTIONS_H
3
4 #include <string>
5 #include <set>
6
7 #include <sourcetools/r/RUtils.h>
8
9 namespace sourcetools {
10 namespace r {
11
12 inline SEXP eval(const std::string& fn, SEXP envSEXP = NULL)
13 {
14 Protect protect;
15 if (envSEXP == NULL)
16 {
17 SEXP strSEXP = protect(Rf_mkString("sourcetools"));
18 envSEXP = R_FindNamespace(strSEXP);
19 }
20
21 SEXP callSEXP = protect(Rf_lang1(Rf_install(fn.c_str())));
22 SEXP resultSEXP = protect(Rf_eval(callSEXP, envSEXP));
23 return resultSEXP;
24 }
25
26 inline std::set<std::string> objectsOnSearchPath()
27 {
28 std::set<std::string> results;
29 Protect protect;
30
31 SEXP objectsSEXP;
32 protect(objectsSEXP = eval("search_objects"));
33
34 for (R_xlen_t i = 0; i < Rf_length(objectsSEXP); ++i)
35 {
36 SEXP strSEXP = VECTOR_ELT(objectsSEXP, i);
37 for (R_xlen_t j = 0; j < Rf_length(strSEXP); ++j)
38 {
39 SEXP charSEXP = STRING_ELT(strSEXP, j);
40 std::string element(CHAR(charSEXP), Rf_length(charSEXP));
41 results.insert(element);
42 }
43 }
44
45 return results;
46 }
47
48 namespace util {
49
50 inline void setNames(SEXP dataSEXP, const char** names, std::size_t n)
51 {
52 RObjectFactory factory;
53 SEXP namesSEXP = factory.create(STRSXP, n);
54 for (std::size_t i = 0; i < n; ++i)
55 SET_STRING_ELT(namesSEXP, i, Rf_mkChar(names[i]));
56 Rf_setAttrib(dataSEXP, R_NamesSymbol, namesSEXP);
57 }
58
59 inline void listToDataFrame(SEXP listSEXP, int n)
60 {
61 r::Protect protect;
62 SEXP classSEXP = protect(Rf_mkString("data.frame"));
63 Rf_setAttrib(listSEXP, R_ClassSymbol, classSEXP);
64
65 SEXP rownamesSEXP = protect(Rf_allocVector(INTSXP, 2));
66 INTEGER(rownamesSEXP)[0] = NA_INTEGER;
67 INTEGER(rownamesSEXP)[1] = -n;
68 Rf_setAttrib(listSEXP, R_RowNamesSymbol, rownamesSEXP);
69 }
70
71 inline SEXP functionBody(SEXP fnSEXP)
72 {
73 SEXP bodyFunctionSEXP = Rf_findFun(Rf_install("body"), R_BaseNamespace);
74
75 r::Protect protect;
76 SEXP callSEXP = protect(Rf_lang2(bodyFunctionSEXP, fnSEXP));
77 return Rf_eval(callSEXP, R_BaseNamespace);
78 }
79
80 } // namespace util
81
82 } // namespace r
83 } // namespace sourcetools
84
85 #endif /* SOURCETOOLS_R_R_FUNCTIONS_H */