What is the basic difference between rep() and replicate in R?

  • Thread starter user366312
  • Start date


Gold Member
What is the basic difference between `rep()` and `replicate()` in R?
R code:
    random <- function()
      sample(1:10, size=1)
    > rep(random(), 4)
    [1] 8 8 8 8
    > rep(random(), 4)
    [1] 2 2 2 2

    > replicate(4, random())
    [1]  3  6 10  3
Why is this difference?


Homework Helper
First, a word of caution: I have never coded in R. That said:

See https://www.quora.com/Why-and-when-do-we-use-a-replicate-function-in-R

In your first case, "random()" is evaluated to produce a random number that is replicated 4 times. The result from random() is passed to "rep" as a single value.
In the second case, "random()" is evaluated 4 times to produce 4 random numbers. The expression "random()" is passed to replicate so that it can be used as many times as needed.

"replicate" takes an "expression" as an argument - so that it can evaluate it multiple times.
"rep" takes a vector.

Each of these functions has its own variations.
They are detailed in the full manual: https://cran.r-project.org/doc/manuals/r-release/fullrefman.pdf
Last edited:

Want to reply to this thread?

"What is the basic difference between rep() and replicate in R?" You must log in or register to reply here.

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving