replicate function in R returns NULL

A for loop returns NULL. So in the second case, the replicate function is executing for(i in 1:5){print(i)} five times, which is why you see all those numbers printed out.

Then it is putting the return values in a list, so the return value of the replicate call is a list of five NULLs, which gets printed out. Executing

x<-replicate(5, for(i in 1:5){print(i)})
x

should clarify.


As @mrip says a for-loop returns NULL so you need to assign to an object within the loop, and return that object to replicate so it can be output. However, mrip's code still results in NULLs from each iteration of the replicate evaluation.

You also need to assign the output of replicate to a name, so it doesn't just evaporate, er, get garbage collected. That means you need to add the d as a separate statement so that the evaluation of the whole expression inside the curley-braces will return 'something' rather than NULL.

d <- numeric(5); res <- replicate(5, { 
                            for(i in 1:5){d[i] <- print(i)} ; d}
                                  )
[1] 1
[1] 2

snipped
[1] 4
[1] 5
> res
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

Tags:

R

Replicate