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

  • Thread starter Thread starter user366312
  • Start date Start date
  • Tags Tags
    Difference
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 5K views
user366312
Gold Member
Messages
88
Reaction score
3
TL;DR
What is the basic difference between `rep()` and `replicate()` in R?
[CODE title="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[/CODE]

Why is this difference?
 
Physics news on Phys.org
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: