R中函数外部的对象范围
下面,我将试图以一种简单的方式解释我所面临的问题R中函数外部的对象范围,r,scope,global-variables,getter-setter,rscript,R,Scope,Global Variables,Getter Setter,Rscript,下面,我将试图以一种简单的方式解释我所面临的问题 我在两个文件中有两个R脚本-file1.R和file2.R。file1.R包含函数function1() file2.R中包含多个构造函数定义-constructor1(p1,p2),constructor2(p3,p4)等。这些构造函数的实例在file1.R中的function1()中使用。因此,我使用source(“file2.R”)作为file1.R中的第一行 在file2.R中,构造函数2(p1=rep(1,length(object1
- 我在两个文件中有两个R脚本-
和file1.R
。file2.R
包含函数file1.R
function1()
中包含多个构造函数定义-file2.R
,constructor1(p1,p2)
等。这些构造函数的实例在constructor2(p3,p4)
中的file1.R
中使用。因此,我使用function1()
作为source(“file2.R”)
中的第一行file1.R
- 在
中,构造函数2(p1=rep(1,length(object1)),p2)使用由file2.R
中的file1.R
function1()创建的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)
}
# 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)
source(“file2.R”)
函数1问题与object1
的范围无关,它与无限循环有关
source("function1.R") > source("function2.R") > source("function1.R") > etc
第一个示例再现了错误
错误:节点堆栈溢出
现在从第二个文件function2.R中删除source(“function1.R”)
# new file: function2.R
function2 <- function(p1, p2){
p1 + p2
}
在function1
范围内创建的对象可以毫无问题地传递到function2
。两个文件中是否都有源代码?看来你把事情复杂化了。这是可复制的。我建议您只在一个文件中使用source
(文件function1.R)。getter setter函数在文件function1.R中,getter函数在文件function2.R中使用。那么这是如何工作的呢?只需构建一个包…@Roland不确定这会有什么帮助您可以在一个名称空间中自然地提供所有内容…谢谢这个示例。这里看起来很简单,但当我在我的R项目中尝试这样做时,我得到了objectnotfound
错误。我将编辑问题函数以添加更多细节。@新手极客发布一个复制错误的最小示例。很多时候,问题中有太多不需要重现问题的代码,这可能会分散注意力并吓跑回答者。我已经编辑了问题。抱歉,我在最初的描述中使用了术语function(),而它是一个构造函数。我希望现在更清楚了。如果没有,我将尝试生成一个最小的示例。
# file: function2.R
source("function1.R")
function2 <- function(p1, p2){
p1 + p2
}
source("function1.R")
# new file: function2.R
function2 <- function(p1, p2){
p1 + p2
}
source("function1.R")
function1()
#[1] 3 4 5 6 7 8 9 10 11 12