5

I read Advanced R by Hadley Wickham on his book's website. I found a question about replacement functions in R. The following result is given according to his book.

library(pryr)
x <- 1:10
address(x)
#> [1] "0x103945110"

x[2] <- 7L
address(x)
#> [1] "0x103945110"

He supposed that the address of x won't change if we just replace the second element of x. However, when I do this, the physical address of x actually changed. So, anybody tell me why?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Travis
  • 1,152
  • 9
  • 25
  • 1
    Did you run that exact code? – Dason Jul 02 '18 at 15:11
  • 1
    Note that if you used `7` instead of `7L` that is a change to the code. – Dason Jul 02 '18 at 15:12
  • 1
    I can replicate the issue. I get an address change, running 64-bit R 3.4.0 on macOS Sierra, `pryr` version 0.1.3. – Gregor Thomas Jul 02 '18 at 15:15
  • Here too, x86_64-w64-mingw32, R 3.5.0, pryr 0.1.4, found source here: http://adv-r.had.co.nz/Functions.html#replacement-functions – jay.sf Jul 02 '18 at 15:18
  • I can replicate the issue too. I'm running `R 3.5.0 (2018-04-23) 64-bit`, SO: `Windows 10 pro` – Random Cotija Jul 02 '18 at 15:31
  • 1
    Are you running in Rstudio vs the basic R GUI? If so, Rstudio makes references to variables. Possible duplicate: https://stackoverflow.com/questions/48230311/copy-on-modify-semantic-on-a-vector-does-not-append-in-a-loop-why/48230836#48230836 – MrFlick Jul 02 '18 at 15:32
  • @MrFlick I am using Rstudio. But now I tested on the R console and I can replicate the issue here too. – Random Cotija Jul 02 '18 at 16:38
  • I can only replicate in RStudio. In R console the address stays the same – Gregor Thomas Jul 02 '18 at 16:42

1 Answers1

4

There was a change in how R 3.5 stores values in the form a:b. If you try the same example with

library(pryr)
x <- c(1,2,3,4,5,6,7,8,9,10)
address(x)
x[2] <- 7L
address(x)

You should get the same address. Now the 1:10 isn't full expanded until it has to be. And changing an element inside the vector will cause it to expand.

MrFlick
  • 195,160
  • 17
  • 277
  • 295