【发布时间】:2019-07-07 07:48:45
【问题描述】:
下面我将尝试以简单的方式解释我面临的问题。
我在两个文件中有两个 R 脚本 -
file1.R和file2.R。file1.R包含函数function1()。file2.R在其中包含多个构造函数定义 -constructor1(p1, p2)、constructor2(p3, p4)等。这些构造函数的实例在function1()中使用,存在于file1.R中。所以,我使用source("file2.R")作为file1.R的第一行。在
file2.R中,constructor2(p1 = rep(1,length(object1)), p2)使用由function1()在file1.R中创建的object1。
file1.R的整体结构如下:
source("file2.R")
function1 <- function()
{
#Read data
data <- readData()
# Second parameter for this function is a instance of constructor1 that is present in file2.R
object1 <- somefunction1(data, listObject$constructor1)
# Second parameter for this function is a instance of a constructor2 that is present in file2.R
# Constructor 2 uses object1 as an input parameter (shown in file2.R)
object2 <- somefunction2(object1, listObject$constructor2)
}
file2.R的整体结构如下:
# List object
listObject <- list()
#Instance of constructor 1
listObject$constructor1 <- constructor1(p1 = someValue, p2 = someValue)
#Instance of constructor 2
# This is where problem lies. How do I access object1 here?
listObject$constructor2 <- constructor2(p3 = rep(1,length(object1)), p4 = someValue)
我应该如何定义object1在function1()之外的范围?我尝试在 R 中使用 getter 和 setter 来实现这一点,但我得到了 node stack overflow 错误。我想这个错误源于我在file1.R 和file2.R 中的function1() 和source("file1.R") 之前source("file2.R")。没有这个,只要 R 读取 source("file2.R"),我就会收到 object1 not found 错误。
【问题讨论】:
-
两个文件中都有
source?看来你很复杂。这是可重现的。我建议你source只在一个文件中(文件 function1.R)。 -
getter-setter 函数在文件 function1.R 中,getter 函数在文件 function2.R 中使用。那么这是如何工作的呢?
-
只需构建一个包...
-
@Roland 不确定这会有什么帮助
-
你会在一个命名空间中自然地提供所有东西......
标签: r scope global-variables getter-setter rscript