Question

I am confused about the output from the replicate function in R, I am trying to use it in two different ways, that (in my mind) should give a matrix as output!

so, if I use

replicate(5, seq(1,5,1))

I get a matrix 5x5

    [,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

..and that's ok, I get that...

but, if I instead use:

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

I get the following:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

can anyone explain me why does this happen? thanks :)

Was it helpful?

Solution 2

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

OTHER TIPS

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.

The for loop is giving a list back, while the seq() call is giving a vector back. This should give you the same as the seq() using a for loop

foo <- function(){
  b = list()
  for(i in 1:5) b[i] <- i
  do.call(c, b)
}

replicate(5, foo())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top