At last, simple addition in R is now fast and easy!!!

They said it could never be done, but they've never heard of Fortran.

In order to add two numbers in R before you had to type:

> 7 + 3

It was tedious to type and several hours could pass as you waited for
your return value.

So, imagine the excitement around your lab or office when you type in:

>.Fortran("add",as.numeric(7),as.numeric(3),as.numeric(0))

and get your result back faster then a greased goat!

Well now you can!

Here's how:

First create a file called add.f with the following code:

---------------------clip--------------------------------

c Add two numbers

subroutine add(a,b,c)
double precision a,b,c
c = a + b
end

------------------end clip------------------------------

Don't disturb the spacing, Fortran is fussy about that.

Now compile you're code:

g77 -c add.f

Now make a shared lib for R (unix/linux):

R CMD SHLIB add.o

This will create a file called 'add.so'

Now go into R:

>dyn.load("add.so") # you might need an explicit path here

And now you too have the power of fast, easy, simple addition!!

>.Fortran("add",as.numeric(7),as.numeric(3),as.numeric(0))

If you want to get real fancy you can put your .Fortran call into a 
function:

myadd = function(a,b){
out = .Fortran("add",as.numeric(a),as.numeric(b),c=as.numeric(0))
return(out$c)
}

> x = myadd(3,7)
[1] 10

And you've done it! Be vanquished naysayers, simple addition will
trouble us no more!

(I thought a very simple tutorial on integrating Fortran code into R might 
be of use.) 

Joel Bremson
jbremson@wald.ucdavis.edu
Statistics Graduate Student
UC Davis

	[[alternative HTML version deleted]]


