Why does “vectorizing” this simple R loop give a different result?

前端 未结 4 922
故里飘歌
故里飘歌 2021-02-12 21:54

Perhaps a very dumb question.

I am trying to \"vectorize\" the following loop:

set.seed(0)
x <- round(runif(10), 2)
# [1] 0.90 0.27 0.37 0.57 0.91 0.2         


        
4条回答
  •  庸人自扰
    2021-02-12 22:18

    There is a simpler explanation. With your loop, you are overwriting one element of x at every step, replacing its former value by one of the other elements of x. So you get what you asked for. Essentially, it is a complicated form of sampling with replacement (sample(x, replace=TRUE)) -- whether you need such a complication, depends on what you want to achieve.

    With your vectorized code, you are just asking for a certain permutation of x (without replacement), and that is what you get. The vectorized code is not doing the same thing as your loop. If you want to achieve the same result with a loop, you would first need to make a copy of x:

    set.seed(0)
    x <- x2 <- round(runif(10), 2)
    # [1] 0.90 0.27 0.37 0.57 0.91 0.20 0.90 0.94 0.66 0.63
    sig <- sample.int(10)
    # [1]  1  2  9  5  3  4  8  6  7 10
    for (i in seq_along(sig)) x2[i] <- x[sig[i]]
    identical(x2, x[sig])
    #TRUE
    

    No danger of aliasing here: x and x2 refer initially to the same memory location but his will change as soon as you change the first element of x2.

提交回复
热议问题