0

How do I execute a R command in C, without using R extensions, something like:

int main() {

   system("R g<- graph(c(0,1,0,4,0,9,1,7,1,9,2,9,2,3,2,5,3,6,3,9,4,5,4,8,5,8,6,7,6,8,7,8),n=10,dir=FALSE)
    plot(g)")

    return(0)
}
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
user1310873
  • 389
  • 1
  • 6
  • 17
  • 5
    Have you tried that? Did it fail? Did you describe the failure to us? – abelenky Apr 16 '12 at 15:00
  • of course it fails, it just do an example that i want to execute from C – user1310873 Apr 16 '12 at 15:03
  • I just want to plot a graph the same way in R but in C/C++ – user1310873 Apr 16 '12 at 15:14
  • 1
    Then you may misunderstand what C and C++ are. Neither language has intrinsic graphics or plotting functionality. You'll have to specify a platform (Win32, Linux, etc), and pick a graphing library. – abelenky Apr 16 '12 at 15:17
  • Yes, but to answer your question: http://yusung.blogspot.se/2008/08/link-c-with-r.html if you want to use exactly R and C. But you may be better off to use some other graphing library, not R at all. – Prof. Falken Apr 16 '12 at 15:23
  • But I need the opposite way, I want to use R into C. Ok with extensions R how plot with R_ext/GetX11Image.h, this is mention in "Writing R Extensions" manual – user1310873 Apr 16 '12 at 15:47
  • Have you looked at [Rinside](http://cran.r-project.org/web/packages/RInside/index.html)? – Joshua Ulrich Apr 16 '12 at 16:00

2 Answers2

4

You can run R using the system() call as you have, but you can't stick R functions on the command line like that.

What you can do is to write the R code to a file and call it with system("R CMD BATCH foo.R") - minimally:

main(){system("R CMD BATCH test.R");}

Now, by default the output graphics from R CMD BATCH go to a PDF file, so you need to open a graphics window and make the script pause if you want to see it.

Of course your test.R file could be written by your C code before it runs it, and you could keep it in a temporary directory or something.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
2

An alternative for R CMD BATCH is Rscript. I think for problems where C++ and R are not tightly integrated, i.e. there are distinct phases where R and C++ are used, nor large volumes or frequency of data exchange, using system calls can be very simple and robust.

An alternative is to run R and C++ alongside each other and exchange info between them. This can be done using the RInside pacakge, which is available on CRAN.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149