I have background of Java and Python and I’m learning R recently.
Today I found that R seems to handle objects quite differently from Java and Python.
For example, the following code:
x <- c(1:10)
print(x)
sapply(1:10,function(i){
x[i] = 4
})
print(x)
The code gives the following result:
[1] 1 2 3 4 5 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10
But I expect the second line of output to be all ‘4’ since I modified the vector in the sapply function.
So does this mean that R make copies of objects in function call instead of reference to the objects?
xis defined in the global environment, not in your function.If you try to modify a non-local object such as
xin a function then R makes a copy of the object and modifies the copy so each time you run your anonymous function a copy ofxis made and its ith component is set to 4. When the function exits the copy that was made disappears forever. The originalxis not modified.If we were to write
x[i] <<- ior if we were to writex[i] <- 4; assign("x", x, .GlobalEnv)then R would write it back. Another way to write it back would be to sete, say, to the environment thatxis stored in and do this:or possibly this:
Normally one does not write such code in R. Rather one produces the result as the output of the function like this:
(Actually in this case one could write
x[] <- 4.)ADDED:
Using the proto package one could do this where method
fsets the ith component of thexproperty to 4.ADDED:
Added above another option in which we explicitly pass the environment that
xis stored in.