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

#### user366312

Gold Member
Summary
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?

Related Programming and Computer Science News on Phys.org

#### .Scott

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:

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

### 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