How to use the R".." string macro with R code encoded in a String

99 views Asked by At

I am trying to implement a sort of @Rinclude macro to include R code written in a file in Julia using the RCall Julia package, but I have trouble making the R"..." string macro recognise the code encoded in the string that I have read:

RCode = """
sumMyArgs <- function(i, j, z) i+j+z
"""

open(f->write(f,RCode),"RScript.R","w")

macro Rinclude(fname)
    quote
        rCodeString = read($fname,String)
        R"$rCodeString"
        nothing
    end
end

@Rinclude("RScript.R")

a = rcopy(R"sumMyArgs"(3,4,5)) # Error as it can't find sumMyArgs

The problem is that the R"..." string macro doesn't work on the interpolated string out of $rCodeString. The object returned is a RObject{StrSxp} instead of a RObject{ClosSxp}:

julia> a = R"""$(rCodeString)"""
RObject{StrSxp}
[1] "sumMyArgs <- function(i, j, z) i+j+z\n"

julia> R"""sumMyArgs3 <- function(i, j, z) i+j+z"""
RObject{ClosSxp}
function (i, j, z) 
i + j + z
1

There are 1 answers

0
Antonello On

Ahh... posting to SO inspires.

Perhaps not the best solution, but it works for my case, just use reval(string) in the macro:

RCode = """
sumMyArgs <- function(i, j, z) i+j+z
"""
open(f->write(f,RCode),"RScript.R","w")
macro Rinclude(fname)
    quote
        rCodeString = read($fname,String)
        reveal(rCodeString)
        nothing
    end
end
@Rinclude("RScript.R")
a = rcopy(R"sumMyArgs"(3,4,5)) #12