# Fortran calling R

**URL:** <https://fortran-lang.discourse.group/t/fortran-calling-r/520>\
**Category:** Uncategorized\
**Created:** [December 25, 2020, 5:10pm UTC](https://fortran-lang.discourse.group/t/fortran-calling-r/520 "2020-12-25T17:10:35Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![ivanpribec](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/ivanpribec/32/3290_2.png) [@ivanpribec](https://fortran-lang.discourse.group/u/ivanpribec)\
**Post date:** [March 1, 2021, 1:25am UTC](https://fortran-lang.discourse.group/t/fortran-calling-r/520/8 "2021-03-01T01:25:46Z")

</div>

@Beliavsky, @edsterjo,

I have created a small example using RInside to call R from Fortran at: [GitHub - ivan-pi/Fortran-RInside: Demonstration of Fortran interface to Rinside](https://github.com/ivan-pi/Fortran-RInside/)

Adapting your example it becomes as simple as:

```auto
program xcall_r
! Demonstrate Fortran calling R, passing data with binary file
use RInside_interface
implicit none
integer :: iter
integer, parameter :: n = 100000, bin_unit = 20, niter = 3
real(kind=kind(1.0d0)) :: x(n)
character (len=*), parameter :: bin_file = "double.bin"
logical, parameter :: call_r = .true.

call setupRinC()

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 xread_bin()
  end if
end do

call teardownRinC()

contains

  subroutine xread_bin()
    type(SEXP) :: res
    type(SEXP) :: inp, x
    res = evalInR('inp = file("double.bin","rb")')

    res = evalInR('x = readBin(inp, "double",n=100000)') ! n is max number of values to read -- can read fewer
    res = evalInR('cat("from R: ",mean(x),"\n\n")')
    res = evalInR('close(inp)')
  end subroutine

end program xcall_r

```

and produces the output:

```nohighlight
mean = 0.4990118
from R: 0.4990118 

mean = 0.4982012
from R: 0.4982012 

mean = 0.4998608
from R: 0.4998608 

```

For some reason if the array is too large (1000000 values) I get errors such as:

```nohighlight
Error: C stack usage 8009524 is too close to the limit
Error: C stack usage 8009572 is too close to the limit
Error: C stack usage 8009460 is too close to the limit
Fatal error: unable to initialize the JIT

```

which seems to be related to the stack size settings of the R binary.

---

_[View the full topic](https://fortran-lang.discourse.group/t/fortran-calling-r/520)._
