# [Rd] AS_NUMERIC and as.numeric - Could someone explain?

Daniel Hoppe daniel.hoppe at univie.ac.at
Wed Jun 30 17:40:21 CEST 2004

```Dear List,

I stepped into a strange effect which I can't explain to myself
(probably due to lack of knowledge on R internals).

I have four vectors a,b,c and z of size 10000 each. With these vectors I
call

.Call("hyp2f1forrey", a, b, b, z, PACKAGE = "hyp2f1")

to access

SEXP hyp2f1forrey(SEXP a, SEXP b, SEXP c, SEXP x)
{
int i,n;
double *xa, *xb, *xc, *xx, *xresr, *xresi;
SEXP resr, resi;

n = LENGTH(a);

PROTECT(a = AS_NUMERIC(a));
PROTECT(b = AS_NUMERIC(b));
PROTECT(c = AS_NUMERIC(c));
PROTECT(x = AS_NUMERIC(x));
PROTECT(resr = NEW_NUMERIC(n));
PROTECT(resi = NEW_NUMERIC(n));

xa = NUMERIC_POINTER(a);
xb = NUMERIC_POINTER(b);
xc = NUMERIC_POINTER(c);
xx = NUMERIC_POINTER(x);
xresr = NUMERIC_POINTER(resr);
xresi = NUMERIC_POINTER(resi);

for (i = 0; i < n; i++)
F77_CALL(hyp)(&xx[i], &xa[i], &xb[i], &xc[i],  &xresr[i],
&xresi[i]);
UNPROTECT(6);
return(resr);
}

I read the documentation in the way that I could either do the call from
above or

.Call("hyp2f1forrey", as.numeric(a), as.numeric(b), as.numeric(b),
as.numeric(z), PACKAGE = "hyp2f1")

and remove the

PROTECT(a = AS_NUMERIC(a));
PROTECT(b = AS_NUMERIC(b));
PROTECT(c = AS_NUMERIC(c));
PROTECT(x = AS_NUMERIC(x));

in the C-Code. What happens now is that in my resulting vector of length
10000 some values are incorrect depending on the exact way of calling
the C-Function.

.Call("hyp2f1forrey", a, b, b, z, PACKAGE = "hyp2f1")  -->
incorrect result
.Call("hyp2f1forrey", a, b, b), z), PACKAGE =
"hyp2f1") --> works
.Call("hyp2f1forrey", as.numeric(a), as.numeric(b), as.numeric(c),
as.numeric(z), PACKAGE = "hyp2f1") -- works
.Call("hyp2f1forrey", a[1:10000], b[1:10000], b[1:10000]),
z[1:10000]), PACKAGE = "hyp2f1") --> works too!

Could someone explain to me where the difference in these calls comes
from?