也许我把R类看作是C或Java中的类,但我似乎不能修改值:
test <- function() {
inc <- function() {
x <- attr( obj, "x" )
x <- x + 1
print(x)
attr( obj, "x" ) <- x
return( obj )
}
obj <- list(inc=inc)
attr( obj, "x" ) <- 1
class(obj) <- c('test')
return( obj )
}
当我运行这个:
> t <- test()
> t <- t$inc()
[1] 2
> t <- t$inc()
[1] 2
就好像原始的类对象不能被修改一样。
发布于 2018-11-08 12:52:26
可以使用R的词法作用域机制来实现类似于C或Java的对象定向。使用<<-
在父环境中分配值。
下面是示例的简化版本。
test <- function() {
inc <- function() {
x <<- x + 1
print(x)
}
x <- 1
list(inc=inc)
}
obj <- test()
obj$inc()
[1] 2
obj$inc()
[1] 3
参见?refClass-class
中所谓的“引用类”。
https://stackoverflow.com/questions/53214873
复制相似问题