[R] R copies for no apparent reason
Jiucang Hao
jiucang at goraltrading.com
Thu Mar 2 16:35:49 CET 2017
Hi Everyone,
Some R function will make R copy the object AFTER the function call, like
nrow, while some others don't, like sum. For example the following code:
x = as.double(1:1e8)
system.time(x[1] <- 100)
y = sum(x)
system.time(x[1] <- 200) ## Fast (takes 0s), after calling sum
foo = function(x) {
return(sum(x))
}
y = foo(x)
system.time(x[1] <- 300) ## Slow (takes 0.35s), after calling foo
Calling foo is NOT slow, because x isn't copied. However, changing x again
is very slow, as x is copied. My guess is that calling foo will leave a
reference to x, so when changing it after, R makes another copy.
Any one knows why R does this? Even when the function doesn't change x at
all? Thanks.
Regards,
JiuCang Hao
[[alternative HTML version deleted]]
More information about the R-help
mailing list