r - 在 R 中,修改类中的值
问题描述
也许我将 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
就好像原始类对象无法修改一样。
解决方案
可以使用 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
R 中所谓的“参考类”。
推荐阅读
- python - TypeError: expected string or bytes-like object 如何解决
- google-cloud-platform - 将数据从 Hive 迁移到 BigQuery
- c++ - 在结构中初始化给定大小的向量
- flutter - 未定义函数 setState
- python - 如何从基于 tkinter 类的小部件中获取变量
- python - 如何在python中制作一个正方形
- string - 伪随机字符串洗牌
- sql - 在 Liquibase 中可以在 splitstatements 上有一个空行吗?
- python - 从旋转或方向矩阵中获取单应矩阵
- r - 如何使用 R 中的计算在数据框中添加新列?