[R] calling R's library using C

Dirk Eddelbuettel
Fri, 03 Mar 2006 01:39:51 -0000

(whitespace trimmed)

On 2 March 2006 at 13:42, Globe Trotter wrote:
|  Thanks, everyone for all the help! So, here is my calling function in C
|  (called
|  test.c):
|
|  #include<stdio.h>
|  #include<stdlib.h>
|  #include<Rmath.h>
|
|  int main(void) {
|    printf("%f \n",pchisq(2.,7., 1, 0));
|    printf("%f \n",pnchisq(2.,7.,0., 1, 0));
|    return EXIT_SUCCESS;
|  }
|
|  I compile using:
|
|   gcc test.c -I/usr/lib/R/include -L/usr/lib/R/lib -lm -lR
|
|  However, running
|  ./a.out
|
|  gives me:
|
|  1.000000
|  0.040160
|
|  The first is wrong, but the second non-central is correct, and matches the
|  answer from R.
|
|  Incidentally, pgamma (which is what pchisq calls, as per the C program inside
|  R) is also wrong and not surprisingly, gives the same answer as above.
|
|  Any suggestions?

As Brian Ripley already told you, you are so wrong that it is unclear why we
bother helping you for matters clearly stated in manuals you continue to
ignore.

Anyway -- on my Debian system, your file compiles, builds and runs
"fine":

edd at basebud:/tmp> gcc -o globetrotter -I/usr/share/R/include
globetrotter.c -lm -lRmath -L/usr/lib/R/lib -lR
edd at basebud:/tmp> LD_LIBRARY_PATH=/usr/lib/R/lib ./globetrotter
0.040160
0.040160

That said, I put "fine" in quotes as you shouldn't need either -lR
nor the
include directive. Witness:

edd at basebud:/tmp> cp /usr/share/doc/r-mathlib/examples/test.c nmtest.c
edd at basebud:/tmp> gcc -o nmtest  nmtest.c -lm -lRmath
edd at basebud:/tmp> ./nmtest
edd at basebud:/tmp> tail -6 nmtest.c
main()
{
/* something to force the library to be included */
    qnorm(0.7, 0.0, 1.0, 0, 0);
    return 0;
}
edd at basebud:/tmp>

The key is the
	#define MATHLIB_STANDALONE 1
in the R example. Once you add that before the #include for Rmath.h, you're
fine:
edd at basebud:/tmp> gcc -o globetrotter globetrotter.c -lm -lRmath
edd at basebud:/tmp> ./globetrotter
0.040160
0.040160
edd at basebud:/tmp> cat globetrotter.c
#include<stdio.h>
#include<stdlib.h>
#define MATHLIB_STANDALONE 1
#include <Rmath.h>

int main(void) {
  printf("%f \n",pchisq(2.,7., 1, 0));
  printf("%f \n",pnchisq(2.,7.,0., 1, 0));
  return EXIT_SUCCESS;
}

As they say, if all else fails you could consider reading the manual that
discusses this example.

Dirk


--
Hell, there are no rules here - we're trying to accomplish something.
                                                  -- Thomas A. Edison