Conor
Conor

Reputation: 1527

What should I use instead of pass-by-reference in R?

I wrote a function in R that, if I could pass by reference, would work as I intend. It involves nesting sapply calls and performing assignment inside them. Since R does not use pass by reference, the functions don't work.

I am aware that there are packages available such as R.oo to bring pass by reference-y aspects to R, but I would like to learn if there is a better way. What is the 'R' way of passing data if pass by reference is not available?

Upvotes: 1

Views: 124

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269854

If you don't modify an argument then it won't actually copy it so it may be pointless to do anything special:

> gc() # using 6.2 MB of Vcells
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 560642 15.0     984024 26.3   984024 26.3
Vcells 809878  6.2    2670432 20.4  2310055 17.7
> x <- as.numeric(1:1000000)
> gc() # now we are using 13.9 MB
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560640 15.0     984024 26.3   984024 26.3
Vcells 1809867 13.9    2883953 22.1  2310055 17.7
> f0 <- function(x) { s <- sum(x); print(gc()); s }
> f0(x) # f0 did not use appreciably more despite using a huge vector
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560655 15.0     984024 26.3   984024 26.3
Vcells 1809872 13.9    2883953 22.1  2310055 17.7
[1] 500000500000

EDIT: minor changes to example

Upvotes: 1

Related Questions