Short answer: R
is call by value
. Long answer: it can do both.
Call By Value, Lazy Evaluation, and Scoping
You'll want to read through: the R language definition for more details.
R
mostly uses call by value
but this is complicated by its lazy evaluation:
So you can have a function:
f <- function(x, y) {
x * 3
}
If you pass in two big matrixes to x
and y
, only x
will be copied into the callee environment of f
, because y
is never used.
But you can also access variables in parent environments of f
:
y <- 5
f <- function(x) {
x * y
}
f(3) # 15
Or even:
y <- 5
f <- function() {
x <- 3
g <- function() {
x * y
}
}
f() # returns function g()
f()() # returns 15
Call By Reference
There are two ways for doing call by reference
in R that I know of.
One is by using Reference Classes, one of the three object oriented paradigms of R (see also: Advanced R programming: Object Oriented Field Guide)
The other is to use the bigmemory
and bigmatrix
packages (see The bigmemory project). This allows you to create matrices in memory (underlying data is stored in C), returning a pointer to the R
session. This allows you to do fun things like accessing the same matrix from multiple R sessions.