在R中的新脚本中实现一个类

时间:2013-04-05 04:52:34

标签: r class

我一直在寻找多个来源,试图找出如何在R中正确实现类,但我还没有找到我正在寻找的答案。我学会了用java编写代码,所以我对面向对象程序的理解是通过使用编译语言,我可以在.java文档中创建一个类定义,然后将该类导入到同一个包中的另一个.java文档中,然后我可以在那里创建对象并调用类方法。 R有类似的协议吗?我试图找出如何创建一个类对象,并在不同的.R文档中使用它的方法,而不是我在类中定义的那个。

基本上,我正在构建一个脚本来将文件导入R,然后进行大量的数据操作以获得我想要的数据帧。我创建了一个处理数据操作的类。此代码位于ImportClass.R文件中:

# Class definition for data importing
DataImport <- setRefClass("DataImport", fields = c("startDate"), where = Sys.getenv("dataImportClassEnv") # See the setEnvironment.R file for the value of dataImportClassEnv

# -----------------------------------------------------------------------------
# Example method
# -----------------------------------------------------------------------------
DataImport$methods(fileImport = function(FilePath)
    {
       Method code here
    }
)

我还有一个脚本,其中设置了我的环境变量。此代码的用户将在其本地计算机上拥有数据,但我不希望在类定义或调用类方法的脚本中引用本地文件路径。我的首选是创建一个脚本,以一种可以在我的其他脚本中使用它们的方式设置文件路径。这是setEnvironment.R

的目的
# Sets environment variables
# Input below the location of the .R files on your local machine corresponding to this model. This variable is used to specify the 'location' attribute for the DataImport class.
Sys.setenv(dataImportClassEnv = "/Users/Nel/Documents/Project/Working Docs")

最后,我有一个脚本,我想用它来实际构建我的数据框。这个脚本需要从DataImport类创建一个对象,所以我需要source()ImportClass.R文件。 ImportClass.R还依赖于setEnvironment.R文件来运行,因此它也必须是源代码。这是我的脚本的大纲,dataScript.R:

library(XML)
source("setEnvironment.R", local = TRUE)
source("ImportClass.R", local = TRUE)

# Create instance of DataImport class
importer <- DataImport$new(startDate = "2012-01-01")

# Go on to call methods on 'importer'

问题是我在这里调用源函数时遇到以下错误。

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'setEnvironment.R': No such file or directory

所有这些文件都保存在同一个地方,“/ Users / Nel / Documents / Project / Working Docs”,我不想在我的dataScript.R代码中使用该文件路径。有没有办法让这个工作?

1 个答案:

答案 0 :(得分:0)

这是一个最小的示例,使用最简单的S3类型的class,也许已经足够开始了:

首先创建file1.Rsource

writeLines('
setClass("myClass")
f1 <- function(x) cat(rep(x,2))
setMethod("print", signature="myClass", definition = f1)
' 
,con="file1.R") 
### note use of alternating apostrophes ' then "
source("file1.R")

a2 <- c(4,5,6)
class(a2) <- "myClass"
print(a2)

给出:

4 5 6 4 5 6>

请注意,要在printsetMethod中使用isGeneric("print") == TRUE

有关自定义方法,请参阅?setGeneric