I just started to study R, thereby getting stuck on trivial problems. I am trying to understand how values โโare output in R. In C ++, we just use the returned variable, but this is not like R. Let's say I have a function that takes 4 input arguments, passes these arguments to C ++, which executes necessary calculations, now if I want to load this myfun into R and get the output from C ++ funciton, what should I do? Below is the pattern I'm trying to use.
extern "C" { SEXP myfun(SEXP S, SEXP A, SEXP B, SEXP C) { //will call this function from R. SEXP rate, dir, list, list_names; //declare variables PROTECT( rate = allocMatrix(REALSXP, 10, 2) ); //allocate 10x2 matrix of double type? PROTECT( dir = allocVector(INTSXP, 10) ); //allocated vector(10) of int type? double* p_rate = REAL(rate); //why do I need pointers? int* p_dir = INTEGER(dir);
// here I call a C ++ function that evaluates vector<vector<double> > someVal and vector<int> someVal2 .
Now I want to pass these values โโto the speed and directory.
for(int i =0; i < 10; i++){ rate[i][0] = someVal1[i][0]; rate[i][1] = someVal1[i][1]; dir[i] = someVal2[i]; }
but he doesnโt like the compiler. I'm not sure how to use the p_rate and p_dir pointers in this case.
Also, I donโt quite understand why the following code is what it is. The lines, speed, and directory appear to be passing in the list_names names and the speed and speed values. Why can't we just do cout and print the right values?
char *tag[2] = {"rate","dir"}; PROTECT(list_names = allocVector(STRSXP ,2)); SET_STRING_ELT(list_names, 0, mkChar(tag[0])); SET_STRING_ELT(list_names, 1, mkChar(tag[1])); PROTECT(list = allocVector(VECSXP ,2)); SET_VECTOR_ELT(list, 0, rate); SET_VECTOR_ELT(list, 1, dir); setAttrib(list, R_NamesSymbol , list_names); UNPROTECT(8); return (list); }
I do not get the basic idea of โโreturning variables to R, this seems very confusing. I would really appreciate it if someone could point me to the relevant resources that explain these things.
Thanks for your help in advance!