Travis
Travis

Reputation: 1241

Replacement functions in R

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?

Upvotes: 5

Views: 334

Answers (1)

MrFlick
MrFlick

Reputation: 206197

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.

Upvotes: 4

Related Questions