[Rd] different type of modification when code is sourced and pasted

Krzysztof Bartoszek b@rto@zekkj @ending from gm@il@com
Sun May 13 18:59:32 CEST 2018


Dear all,
I have a question about R's modification in place and replacement functions.
I was working through Hadley Wickham's Advanced R section on
Replacement Functions and
in a file (say test.R) I wrote:

`second<-` <- function(x, value) {
   x[2] <- value
   x
}
x <- 1:10
second(x) <- 5L
print(x)

library(pryr)
x <- 1:10
print(address(x))
second(x) <- 6L
print(address(x))
x <- 1:10
print(address(x))
x[2] <- 7L
print(address(x))

When I copy-paste the code the effect is as expected:
> `second<-` <- function(x, value) {
+    x[2] <- value
+    x
+ }
> x <- 1:10
> second(x) <- 5L
> print(x)
 [1]  1  5  3  4  5  6  7  8  9 10
>
> library(pryr)
> x <- 1:10
> print(address(x))
[1] "0x1b44ef40"
> second(x) <- 6L
> print(address(x))
[1] "0x1f955a38"
> x <- 1:10
> print(address(x))
[1] "0x1b447090"
> x[2] <- 7L
> print(address(x))
[1] "0x1b447090"

However, when I source the code the effect is a bit surprising:
> source("test.R")
 [1]  1  5  3  4  5  6  7  8  9 10
[1] "0x2f372320"
[1] "0x2f394888"
[1] "0x1b446ef0"
[1] "0x1f960f30"
Notice, that the last two addresses are different.
I would be grateful if somebody could point me to an explanation for this.
I have tried this on: R version 3.1.2 running on openSUSE 12.1, R
version 3.4.2 running on openSUSE Leap 42.3
and on R running on a friend's Mac.

Thank you
Best wishes
Krzysztof Bartoszek



More information about the R-devel mailing list