Hello everyone,

I am trying to run some R-code through STATA but I am experiencing some issues and I was hoping to find help here.

First I was using the Rsource user written code, but I think it was slower than what I am doing now, and in particular, it gave me an r(198) error if trying to loop over it.
I was doing something like this:
Code:
levelsof region, local(regionlevel)
foreach l of local regionlevel {
preserve
keep if regione=="`l'"
rsource, terminator(END_OF_R) roptions(--vanilla) rpath(C:\Program Files\R\R-3.5.2\bin\R.exe)
RCODE here
END_OF_R
save "$path/myfolder/`l'_Rcoded.dta", replace
restore
}
But as soon as the loop start I get the following error

Code:
> 
End of R output
invalid 'list' 
r(198);
The R code itself is correct because it works without the loop, so I think that the rsoruce has some issue when it is inside a loop.

As a workaround I found out that I can call R from shell and make it launch an Rscript with the following code:
Code:
levelsof region, local(regionlevel)
foreach l of local regionlevel {
preserve
keep if regione=="`l'"
shell "C:/Program Files/R/R-3.5.2/bin/R.exe" --vanilla <"C:/myfolder/Rscript.R"
save "$path/myfolder/`l'_Rcoded.dta", replace
restore
In this way everything works good but I am annoyed by the fact that to change the Rscript I have to open the script with R, while with the Rsource I could modify it directly in the dofile.

Do any of you know if there is a way to make the rsource work within the loop or if there is a way to make the shell recognize the script directly inside the do-file?
maybe something like
Code:
shell "C:/Program Files/R/R-3.5.2/bin/R.exe" --vanilla <"Rcode_here"
I hope to find help here,
and thank you in advance for your time