main.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define CSTACK_DEFNS 1
  4. #include <R.h>
  5. #include <Rinternals.h>
  6. #include <Rinterface.h>
  7. #include <Rdefines.h>
  8. #include <Rembedded.h>
  9. #include <R_ext/Parse.h>
  10. int initR() {
  11. char *argv[] = {"REmbeddedMy", "--gui=none", "--silent"};
  12. int argc = sizeof(argv)/sizeof(argv[0]);
  13. return Rf_initEmbeddedR(argc, argv);
  14. }
  15. SEXP execCmd(const char *cmd) {
  16. SEXP cmdSexp, cmdExpr, ans = R_NilValue;
  17. ParseStatus status;
  18. int i;
  19. PROTECT(cmdSexp = allocVector(STRSXP, 1));
  20. SET_STRING_ELT(cmdSexp, 0, mkChar(cmd));
  21. cmdExpr = PROTECT(R_ParseVector(cmdSexp, -1, &status, R_NilValue));
  22. if (status != PARSE_OK) {
  23. UNPROTECT(2);
  24. error("invalid command: %s", cmd);
  25. }
  26. /* Loop is needed here as EXPSEXP will be of length > 1 */
  27. for(i = 0; i < length(cmdExpr); i++)
  28. ans = eval(VECTOR_ELT(cmdExpr, i), R_GlobalEnv);
  29. UNPROTECT(2);
  30. return ans;
  31. }
  32. int execScript(int line_count, char *lines[]) {
  33. int i;
  34. for (i = 0; i < line_count; i++) {
  35. execCmd(lines[i]);
  36. }
  37. return 0;
  38. }
  39. void lmExample() {
  40. execCmd("library(fume)");
  41. execCmd("print(mkTrend(c(1,2,3,4,5,6,7,8), 0.95))");
  42. execCmd("print(lm(x ~ I(1:8))$resid)");
  43. //execCmd("print(mkTrend(x, 0.95))");
  44. }
  45. int main(int argc, char **argv) {
  46. int r = initR();
  47. printf("Hello R: %d\n", r);
  48. SEXP e, val;
  49. int errorOccurred, i;
  50. int result = -1;
  51. SEXP ans, x, y;
  52. PROTECT(x = allocVector(REALSXP, 8));
  53. for (i = 0; i < 8; i++)
  54. REAL(x)[i] = i + 1;
  55. SEXP xSym = install("x");
  56. SEXP ySym = install("y");
  57. defineVar(xSym, x, R_GlobalEnv);
  58. PROTECT(xSym);
  59. printf("x: %d, y: %d\n", findVar(xSym, R_GlobalEnv) == R_UnboundValue, findVar(ySym, R_GlobalEnv) == R_UnboundValue);
  60. //char *scridddpt[] = {
  61. //"c<-file(\"R.log\", \"w\")",
  62. //"sink(file=c, type=\"message\")",
  63. //"1+3",
  64. //};
  65. //execScript(4, script);
  66. UNPROTECT(2);
  67. }