1

I'm exploring the use of tracemem, and starting with a brand new R session, I type

x <- 1:3
tracemem(x)
#[1] "<000002ACC3C51E80"

y <- 4:6
y <- x
y[1] <- 1
#tracemem[0x000002acc3c51e80 - 0x000002acbff1e038]: 
#tracemem[0x000002acbff1e038 - 0x000002acc75a7358]: 

y[2] <- 2
#tracemem[0x000002acc75a7358 - 0x000002acc75ab0f8]: 

y[2] <- 3
#tracemem[0x000002acc75ab0f8 - 0x000002acc75b0bb8]: 

z <- 9:10
z <- 1:2
y <- z

I can see why tracemem prints a change in address when I type y[1] <- 1 (an entirely new copy of y is made), but why does it print a change in address when I then type y[2] <- 2 and y[2] <- 3? Isn't y completely divorced from x at this point? It does not print anything when I later type y=z, and this is what I expect, but I don't have a clear understanding of why it printed traces for y[2] <- 2 and y[2] <- 3. What am I missing here?

user20650
  • 24,654
  • 5
  • 56
  • 91
Thomas Philips
  • 935
  • 2
  • 11
  • 22
  • 2
    Are you using Rstudio not plain R? This is typically Rstudio behavior in my experience. – Zheyuan Li Aug 30 '22 at 14:51
  • I am indeed using Rstudio, as I have never used plain R. Further experiments with lobstr::ref() suggest that some of the traces refer to y, and not to x - tracemem seems to remember that x and y were once the same, and even though they have been separated, it continues to trace both of them even though only x was traced. Do you know what causes this strange behavior? – Thomas Philips Aug 30 '22 at 15:00
  • 2
    What version of R (and RStudio) are you using? I cannot replicate this behavior using `R 4.2.0` and `RStudio 2022.07.1+554` – MrFlick Aug 30 '22 at 15:00
  • I am using R 4.2.1 and RStudio 2022.07.1+554. I was intrigued by Zheyuan's suggestion, so for the first time ever, I opened RGui 4.2.1 and typed in the same sequence of commands. Sure enough, once x and y are separated further changes to x or y do not induce further tracemem outputs. Not sure what causes my problem, but it certainly is both instructional and confusing! – Thomas Philips Aug 30 '22 at 15:08
  • 1
    The RStudio IDE will create references to variables in order to show them in the Environment browser. Basically that extra reference will trigger a copy rather than modify. A longer discussion already exists here: https://stackoverflow.com/questions/15559387/operator-in-rstudio-and-r – MrFlick Aug 30 '22 at 15:18

0 Answers0