x defined in the global environment, not in your function.
If you try to change a non-local object, for example x in a function, then R creates a copy of the object and modifies the copy, so every time you run an anonymous function, a copy of x is created and its i-th component is set to 4. When the function completes the executed copy, she disappears forever. Original x does not change.
If we were to write x[i] <<- i , or if we were to write x[i] <- 4; assign("x", x, .GlobalEnv) x[i] <- 4; assign("x", x, .GlobalEnv) , then R will write it back. Another way to write it is to set e , say, in the environment in which x is stored, and do this:
e <- environment() sapply(1:10, function(i) e$x[i] <- 4)
or perhaps this:
sapply(1:10, function(i, e) e$x[i] <- 4, e = environment())
Typically, this code is not written to R. Rather, it produces the result as an output of a function like this:
x <- sapply(1:10, function(i) 4)
(Actually, in this case, you can write x[] <- 4 )
ADDED:
Using a flow package, you can do this when the f method sets the ith component of property x to 4.
library(proto) p <- proto(x = 1:10, f = function(., i) .$x[i] <- 4) for(i in seq_along(p$x)) p$f(i) p$x
ADDED:
Added another parameter above, in which we explicitly pass the environment in which x is stored.