C call R Using .R file in C T. B. Chen in NCTU 2019/5/29
Why Using “BATCH” file runs R functions. Fast : Without using R’s GUI. Easy : Only including a .R file in C. Combination advantages of R and C. Avoid looping control in R. Text file, I/O in C, could share with R. Easy handling user’s sub-routines. 2019/5/29
Principle R GUI Packages .R File DLL I/O Text File .c File System library User’s library External library 2019/5/29
.R File Simulation a model using R. Codes Y = u + Bx + error, error~N(0,1) Codes u = 10; B=3.5; N=10000; error=rnorm(N); x=rpois(N,10); Y=u+B*x+error Xx=cbind(x,Y) write.csv(Xx, file='d:/XYdata.txt‘,row.names = FALSE) 2019/5/29
.C File Using .R Codes: #include <stdio.h> #include <stdlib.h> FILE *in; void main(){ Expr………. system(“C:/progra~1/R/R-2.3.1/bin/R CMD BATCH D:/RunR/Test.R”); in = fopen(“d:/XYdata.txt”,”r”); fclose(in); } 2019/5/29
.C File Using .R (2) Codes: #include <stdio.h> #include <stdlib.h> FILE *in, *out; void main(int argc, char** argv){ Expr………. out = fopen(“d:/Runr/Ch14.R”,”w”); fprintf(out,” error=rnorm(%d)\n”,N); ……………………… fprintf(out,” write.csv(Xx, file=‘%s', row.names = FALSE)\n”,argv[1]); fclose(out); system(“C:/progra~1/R/R-2.3.1/bin/R CMD BATCH D:/RunR/Ch14.R”); in = fopen(“d:/XYdata.txt”,”r”); fclose(in); } 2019/5/29