[EDIT: The issue prompting this workaround has been fixed since R 3.1.0.]
I was asked elsewhere to post this as a self-answered question.
When an R function accepts an arbitrary number of parameters through the ellipsis arguments, the common way to access them is using list(...)
:
f <- function(...) {
dots <- list(...)
# Let's print them out.
for (i in seq_along(dots)) {
cat(i, ": name=", names(dots)[i], "\n", sep="")
print(dots[[i]])
}
}
> f(10, a=20)
1: name=
[1] 10
2: name=a
[1] 20
However, R (as of v3.0.2) deep-copies all list
elements:
> x <- 10
> .Internal(inspect(x))
@10d85ca68 14 REALSXP g0c1 [MARK,NAM(2),TR] (len=1, tl=0) 10
> x2 <- x
> .Internal(inspect(x2)) # Not copied.
@10d85ca68 14 REALSXP g0c1 [MARK,NAM(2),TR] (len=1, tl=0) 10
> y <- list(x)
> .Internal(inspect(y[[1]])) # x was copied to a different address:
@10dd45e88 14 REALSXP g0c1 [MARK,NAM(1),TR] (len=1, tl=0) 10
> z <- list(y)
> .Internal(inspect(z)) # y was deep-copied:
@10d889ed8 19 VECSXP g0c1 [MARK,NAM(1)] (len=1, tl=0)
@10d889f38 19 VECSXP g0c1 [MARK,TR] (len=1, tl=0)
@10d889f68 14 REALSXP g0c1 [MARK] (len=1, tl=0) 10
You can verify this with tracemem
as well, if you have memory profiling enabled.
So you've been storing large objects in a list
? Copied. Passing them into any function that calls list(...)
inside? Copied:
> g <- function(...) for (x in list(...)) .Internal(inspect(x))
> g(z) # Copied.
@10dd45e58 19 VECSXP g0c1 [] (len=1, tl=0)
@10dd35fa8 19 VECSXP g0c1 [] (len=1, tl=0)
@10dd36068 19 VECSXP g0c1 [] (len=1, tl=0)
@10dd36158 14 REALSXP g0c1 [] (len=1, tl=0) 10
> g(z) # ...copied again.
@10dd32268 19 VECSXP g0c1 [] (len=1, tl=0)
@10d854c68 19 VECSXP g0c1 [] (len=1, tl=0)
@10d8548d8 19 VECSXP g0c1 [] (len=1, tl=0)
@10d8548a8 14 REALSXP g0c1 [] (len=1, tl=0) 10
Not horrified yet? Try grep -l "list(\.\.\.)" *.R
in R library sources. My favorite is mapply
/Map
, which I was routinely calling on GBs of data and wondering why memory was running out. At least lapply
is fine.
So, how can I write a variadic function with ...
arguments and avoid copying them?