Skip to content
Prev 57460 / 63421 Next

Calling a LAPACK subroutine from R

The Lapack library is loaded automatically by R itself when it needs it  for doing some calculation.
You can force it to do that with a (dummy) solve for example.
Put this at start of your script:

<code>
# dummy code to get LAPACK library loaded
X1 <- diag(2,2)
x1 <- rep(2,2)
# X1;x1
z <- solve(X1,x1)
</code>

followed by the rest of your script.
You will get a warning (I do) that  "passing a character vector  to .Fortran is not portable".
On other systems this may gave fatal errors. This is quick and very dirty. Don't do it.

I believe there is a better and much safer way to achieve what you want.
Here goes.

Create a folder (directory) src in the directory where your script resides.
Create a wrapper for "dpbtrf" file in a file xdpbtrf.f that takes an integer instead of character

<xdpbtrf.f>
c intermediate for dpbtrf

      SUBROUTINE xDPBTRF( kUPLO, N, KD, AB, LDAB, INFO )

c      .. Scalar Arguments ..
      integer         kUPLO
      INTEGER         INFO, KD, LDAB, N

c  .. Array Arguments ..
      DOUBLE PRECISION   AB( LDAB, * )

      character UPLO
c     convert integer argument to character
      if(kUPLO .eq. 1 ) then
          UPLO = 'L'
      else
          UPLO = 'U'
      endif

      call dpbtrf(UPLO,N,KD,AB,LDAB,INFO)
      return
      end
</xdpbtrf.f>


Instead of a character argument UPLO it takes an integer argument kUPLO.
The meaning should be obvious from the code.

Now create a shell script in the folder of your script to generate a dynamic library to be loaded in your script:

<mkso.sh>
# Build a binary dynamic library for accessing Lapack dpbtrf

# syntax checking
 
SONAME=xdpbtrf.so

echo Strict syntax checking
echo ----------------------
gfortran -c -fsyntax-only -fimplicit-none -Wall src/*.f || exit 1

LAPACK=$(R CMD config LAPACK_LIBS)
R CMD SHLIB --output=${SONAME} src/*.f ${LAPACK} || exit 1
</mkso.sh>

To load the dynamic library xdpbtrf.so  change your script into this

<yourscript>
dyn.load("xdpbtrf.so")
n <- 4L
phi <- 0.64
AB <- matrix(0, 2, n)
AB[1, ] <- c(1, rep(1 + phi^2, n-2), 1)
AB[2, -n] <- -phi
round(AB, 3)

AB.ch <- .Fortran("xdpbtrf", kUPLO=1L, N = as.integer(n),
                            KD = 1L, AB = AB, LDAB = 2L, INFO = as.integer(0))$AB
AB.ch

</yourscript>

and you are good to go.

You should always do something  as described above when you need to pass character arguments to Fortran code.

All of this was tested and run on macOS using the CRAN version of R.

Berend Hasselman