Open In App

How to Use the replicate() Function in R?

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

replicate() function in R Programming Language is used to evaluate an expression N number of times repeatedly.

Syntax:

replicate(n, expression)

where

  • expression is a statement to evaluate
  • n is the number of times to evaluate the expression

Method 1: Replicate a value n times

Here we will replicate some values n times.

Example:

R




# replicate 3 value 5 times
print(replicate(5, 3))
 
# replicate  akash 5 times
print(replicate(5, "akash"))
 
# replicate  TRUE 5 times
print(replicate(5, TRUE))


Output:

[1] 3 3 3 3 3
[1] "akash" "akash" "akash" "akash" "akash"
[1] TRUE TRUE TRUE TRUE TRUE

Method 2: Replicate a Function Multiple Times

Here we are passing the function to replicate() to get them multiple times. We are using rnorm() function which will get the normal distribution using the mean as the value.

Syntax:

replicate(n, rnorm(value, mean))

where,

  • value is the normal distribution value
  • mean is the mean of the normal distribution

Example:

R




# replicate normal distribution with mean
replicate(6, rnorm(3, mean=4))


Output:

         [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
[1,] 4.236647 4.626099 5.450712 3.724129 1.867676 3.344033
[2,] 2.841519 1.978552 4.267868 5.519327 4.147135 2.322976
[3,] 5.620265 4.575099 2.929690 3.417897 4.565281 3.827686

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads