Some function R will make R copy the object AFTER calling the function, for example, nrow, while some others will not, for example, sum. For example, the following code:
x = as.double(1:1e8)
system.time(x[1] <- 100)
y = sum(x)
system.time(x[1] <- 200)
foo = function(x) {
return(sum(x))
}
y = foo(x)
system.time(x[1] <- 300)
The call to foo is NOT slow because x is not copied. However, changing x again happens very slowly, as x is copied. I assume that calling foo will leave a link to x, so by changing it, R will make another copy.
Does anyone know why R does this? Even if the function does not change x at all? Thanks.
source
share