1

See this short example:

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"

I was expecting the operation g[[1]]$hair <- "red" will change g by reference like ann$name <- "NewName". Is there a way to achieve this?

mt1022
  • 16,834
  • 5
  • 48
  • 71

1 Answers1

1

g is just a vector so it does not have reference semantics. Even so, you get a new object g, it refers to same objects ann and ann2. You cam verify by address(g[[1]])

If you do not want to change g, you have to extract the object from g and then call the assignment method.

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"
Marcelo
  • 4,234
  • 1
  • 18
  • 18
  • So when I change `g`, the change will also take place on `ann`. Does that mean `g` stores the reference to `ann` and `ann2`, not the whole object? – mt1022 May 01 '17 at 13:18