Does anyone call R from Fortran?
R and its packages have almost every statistics algorithm I want, and I would like to access it from Fortran. A simple but crude way is to write unformatted stream data from Fortran, which R reads and processes. For example, the code
program xcall_r
! 12/25/2020 10:12 AM demonstrate Fortran calling R, passing data with binary file
implicit none
integer :: iter
integer, parameter :: n = 1000000,bin_unit = 20, niter = 10
real(kind=kind(1.0d0)) :: x(n)
character (len=*), parameter :: bin_file = "double.bin"
logical, parameter :: call_r = .true.
do iter=1,niter
call random_number(x)
write (*,"(a,f11.7)") "mean = ",sum(x)/n
if (call_r) then
open (unit=bin_unit,file=bin_file,action="write",access="stream",form="unformatted",status="replace")
write (bin_unit) x
close (bin_unit)
call execute_command_line("C:\programs\R\R-4.0.1\bin\x64\rterm.exe --vanilla --slave < xread_bin.r")
end if
end do
end program xcall_r
for R script xread_bin.r
inp = file("double.bin","rb")
x = readBin(inp, "double",n=10000000) # n is max number of values to read -- can read fewer
cat("from R: ",mean(x),"\n\n")
gives output such as
mean = 0.5000192
from R: 0.5000192
mean = 0.5003266
from R: 0.5003266
<snip>
The wall time elapsed is 2.2 s when the program calls R 10 times and 0.1 s when it does not, so calling R has overhead of about 0.2 s (even if R script does nothing). Passing estimated parameters from R back to Fortran instead of just printing them would be more involved. It is possible to call C++ functions from R using the Rcpp package. There is an RFortran library, but it works only with Intel Fortran on Windows.