[R] Scope and sapply

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jun 13 04:30:09 CEST 2010


On Sat, Jun 12, 2010 at 9:22 PM, Worik R <worikr at gmail.com> wrote:
> I am puzzled by the scope rules that apply with sapply.
>
> If I want to modify a vector with sapply I tried...
>
> N <- 10
> vec <- vector(mode="numeric", length=N)
> test <- function(i){
>  vec[i] <- i
> }
> sapply(1:N, test)
> vec
>
> but it not work.
>

If we modify a variable inside a function R makes a local copy of that
variable rather than modifying the original one.  Try this instead.
The first one uses <<- to tell it to search into parent environments
for vec and the second one tells it explicitly which environment to
use.

vec <- rep(0, 10)
test2 <- function(i) vec[i] <<- i
junk <- sapply(1:N, test2)
vec

vec <- rep(0, 10)
test3 <- function(i, env) env$vec[i] <- i
junk <- sapply(1:N, test3, env = environment())
vec



More information about the R-help mailing list