首页 > 解决方案 > 在 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

就好像原始类对象无法修改一样。

标签: rclassoop

解决方案


可以使用 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-classR 中所谓的“参考类”。


推荐阅读