当前环境中存在同名变量时如何访问类的字段?

时间:2014-06-16 18:27:10

标签: r oop

以下是一个例子:

x = matrix("fromRData", 4, 4)
save(x, file="/tmp/x.RData")

TestClass = setRefClass("TestClass", fields = c("x"))
TestClass$methods(
    testfun = function(s) {
        load("/tmp/x.RData")
        print(x)
    }
)
TestClass$methods(
    initialize = function() {
        x <<- matrix("fromObj", 4, 4)
    }
)


myobj = TestClass()
myobj$testfun()

##      [,1]        [,2]        [,3]        [,4]       
## [1,] "fromRData" "fromRData" "fromRData" "fromRData"
## [2,] "fromRData" "fromRData" "fromRData" "fromRData"
## [3,] "fromRData" "fromRData" "fromRData" "fromRData"
## [4,] "fromRData" "fromRData" "fromRData" "fromRData"

显然,对象中的xx中的/tmp/x.RData遮蔽。

2 个答案:

答案 0 :(得分:2)

在方法

中将x引用为.self$x
x = matrix("fromRData", 4, 4)
save(x, file="/tmp/x.RData")

TestClass = setRefClass("TestClass", fields = c("x"))
TestClass$methods(
  testfun = function(s) {
    load("/tmp/x.RData")
    print(.self$x)
  }
)
TestClass$methods(
  initialize = function() {
    x <<- matrix("fromObj", 4, 4)
  }
)


> myobj = TestClass()
> myobj$testfun()
     [,1]      [,2]      [,3]      [,4]     
[1,] "fromObj" "fromObj" "fromObj" "fromObj"
[2,] "fromObj" "fromObj" "fromObj" "fromObj"
[3,] "fromObj" "fromObj" "fromObj" "fromObj"
[4,] "fromObj" "fromObj" "fromObj" "fromObj"

答案 1 :(得分:1)

只是为了保持记录, 如果你想使用“&lt; - ”或“=”从x.RData更改x, R会发出警告。在这种情况下,您可以明确指定 当前环境中的x:

e = environment()
e$x[2, 2] = "changed"