R参考课程问题 [英] R Reference Class issue
问题描述
我正在尝试在R中创建一个简单的引用类.这是我的代码(R初学者):
I am trying to create a simple reference class in R. Here is my code (R beginner):
MyClass <- setRefClass("MyClass",
fields = list(a = "numeric",
b = "numeric"),
methods = list(
initialize <- function(){
print("Initializing")
a <<- 1
b <<- 2
},
printValues <- function(){
print(a)
print(b)
}
)
)
a <- MyClass$new()
a$printValues()
这会在最后一行a $ printValues中产生以下错误:
This produces the following error for the last line, a$printValues:
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
"printValues" is not a valid field or method name for reference class "MyClass"
此外,未调用初始化方法吗?
Also, the initializer method is not being called ?
有人可以指出我的问题所在吗?预先非常感谢.
Can someone point me to where the issue lies here ? Many thanks in advance.
推荐答案
setRefClass
的methods
参数必须是一个命名列表.问题是在定义列表时,您使用的是赋值运算符<-
而不是=
.看看两者之间的区别
The methods
argument to setRefClass
needs to be a named list. The problem is you are using the assign operator <-
instead of =
when defining your list. See the difference between
list(a = 1, b = 2)
# $a
# [1] 1
#
# $b
# [1] 2
返回命名列表和
list(a <- 1, b <- 2)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 2
在您的环境中创建a
和b
并返回未命名列表.
which creates a
and b
in your environment and returns an unnamed list.
因此,在传递方法时,您需要使用=
:
So when passing your methods, you need to use =
:
methods = list(initialize = function [...],
printValues = function [...]
这篇关于R参考课程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!