如何通过引用修改R6class对象列表?

时间:2017-05-01 03:04:03

标签: r oop r6

见这个简短的例子:

library(R6)
library(pryr)

Person <- R6Class("Person", public = list(name = NA, hair = NA, initialize = function(name, 
  hair) {
  if (!missing(name)) self$name <- name
  if (!missing(hair)) self$hair <- hair
}, set_hair = function(val) {
  self$hair <- val
}))
ann <- Person$new("Ann", "black")
address(ann)
#> [1] "0x27e01f0"

ann$name <- "NewName"
address(ann)
#> [1] "0x27e01f0"


ann2 <- Person$new("Ann", "white")

g <- c(ann, ann2)
address(g)
#> [1] "0x32cc2d0"

g[[1]]$hair <- "red"
address(g)
#> [1] "0x34459b8"

我希望操作g[[1]]$hair <- "red"会像g一样通过引用更改ann$name <- "NewName"。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

g只是一个向量,因此它没有引用语义。 即便如此,您获得了一个新对象g,它引用了相同的对象annann2。 您可以通过address(g[[1]])

进行验证

如果您不想更改g,则必须从g中提取对象,然后调用分配方法。

address(g)
##[1] "0000000019782340"

# Extract the object and assign
temp <- g[[1]]
temp$hair <- "New red"

address(g)
[1] "0000000019782340"
#Verify the value on g
g[[1]]$hair
##[1] "New red"

address(g)
#[1] "0000000019782340"