1

我正在尝试实现一种宏,以使用RCall@Rinclude Julia 包在 Julia 的文件中包含编写的 R 代码,但我无法让字符串宏识别我已阅读的字符串中编码的代码:R"..."

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

问题是 R"..." 字符串宏不适用于$rCodeString. 返回的对象是 aRObject{StrSxp}而不是 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
4

1 回答 1

5

啊……张贴到如此鼓舞人心。

也许不是最好的解决方案,但它适用于我的情况,只需reval(string)在宏中使用:

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
于 2022-02-04T16:12:42.987 回答