# [R] outer

Sean Carmody sean at categoricalsolutions.com.au
Thu May 10 09:21:45 CEST 2001

```I've just begun playing around with defining functions in R and
I'm not really sure what's going on in the following situation.

I've defined the following function:

gcd <- function(x,y) {
x <- as.integer(x); y <- as.integer(y)
q <- as.integer(x / y)
r <- x - q * y
if (r==0) y else gcd(y,r)
}

As expected, it gives the following results:

> gcd(3,2)
[1] 1

> gcd(2,4)
[1] 2

etc. However, the function behaves strangely with outer:

> outer(1:5,1:5,gcd)
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    1    2    3    4    5
[5,]    1    2    3    4    5

If i change the second line of the definition of gcd to

y <- as.integer(x); x <- as.integer(y)

then the effect of gcd should not change, and the following
results still hold:

> gcd(3,2)
[1] 1

> gcd(2,4)
[1] 2

however, now outer gives a different result:

> outer(1:5,1:5,gcd)
[,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

Somehow something strange seems to be happening to the
internal variable r when outer is used, but I'm not sure what
or why. Any thoughts would be appreciated.

Sean.

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```