replicate() function in R

The replicate() function can be used for creating simulations as it can repeat an expression a specific number of times. We can also control the type of the final result as an array or list using the simplify parameter.

One simple example of the replicate() function is shown below:

replicate(5,1)
[1] 1 1 1 1 1

As you can see in the above example, 1 is the expression that is repeated 5 times. Note that the final result here is an array. If we add the simplify parameter to the function (which is TRUE by default) and set it to FALSE, we will get a list instead of an array. For example:

typeof(replicate(5,1,simplify = FALSE))
[1] "list"

We can also use the replicate() for more complex simulations, like creating a 2-D array. The following code snippet will show how we do it.

replicate(5, seq(1,10,1))
      [,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
 [6,]    6    6    6    6    6
 [7,]    7    7    7    7    7
 [8,]    8    8    8    8    8
 [9,]    9    9    9    9    9
[10,]   10   10   10   10   10

In this example, we use the seq() function to create a simple sequence. It creates a sequence from 1 to 10 with an increment of 1. replicate() repeats the sequence 5 times to generate a 2-D array.

We can also use the for() loop for such a situation. For example:

n <- numeric(5)
arr2d <- replicate(5, { 
   for(i in 1:5){n[i] <- print(i)};n} )
print(arr2d)
     [,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

Note that we have to use a numeric vector as an extra statement outside of the curly bracket; otherwise, the replicate() function will get NULL value as the value gets dumped as garbage and is not stored since we are using the for() loop.

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

Output:

[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

Related Article - R Function

  • Apply Function With Multiple Arguments in R