[Rd] Understanding modification in place

Simon Urbanek simon.urbanek at r-project.org
Wed Jul 24 18:02:17 CEST 2013


On Jul 24, 2013, at 10:35 AM, Hadley Wickham wrote:

> Hi all,
> 
> Take this simple script, which I'm trying to use to understand when
> modification in-place occurs, and when a new object is created:
> 
> message("Global")
> x <- 1:3
> .Internal(inspect(x))
> x[2] <- 1L
> .Internal(inspect(x))
> 
> message("In function")
> (function() {
>  x <- 1:3
>  .Internal(inspect(x))
>  x[2] <- 1L
>  .Internal(inspect(x))
> })()
> 
> If I run it from the command line, I get:
> 
> Global
> @1050bb840 13 INTSXP g0c2 [MARK,NAM(1)] (len=3, tl=0) 1,2,3
> @1050bb840 13 INTSXP g0c2 [MARK,NAM(1)] (len=3, tl=0) 1,1,3
> In function
> @1050bb190 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,2,3
> @1050bb190 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,1,3
> 
> i.e. both modifications occur in place.
> 
> If I put it in a file and source() it, I get:
> 
> Global
> @1050bb318 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 1,2,3
> @1050bb698 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,1,3
> In function
> @1050b8958 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,2,3
> @1050b8958 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,1,3
> 
> i.e. in the global environment a copy is created.
> 
> Why is there a difference?
> 

Did you look at source()? ;)
It has to do with all the additional processing there which assigns the result of every line locally thus producing extra copies. If you just eval it, you'll get the same behavior as in the console:

> p=parse("test.R")
> eval(p)
Global
@100816498 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,2,3
@100816498 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,1,3
In function
@102c42378 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,2,3
@102c42378 13 INTSXP g0c2 [NAM(1)] (len=3, tl=0) 1,1,3

The same is true is you just put { } around it and source it so it becomes a single expression.

Cheers,
Simon



More information about the R-devel mailing list