Alessandro Jacopson
Alessandro Jacopson

Reputation: 18665

function `sample` in R, are these two code snippets equivalent?

Are these two code snippets equivalent, i.e. are they doing the same thing?

For what I understand from the help of sample they should do the same thing, i.e. both s1 and s2 are a random subset of x.

First snippet:

sz <- 5
x <- 1:10
s1 <- sample(x,size=sz,replace=F)

Second snippet:

sz <- 5
x <- 1:10
s2 <- c()
idx <- sample(1:length(x),size=sz,replace=F)
for ( i in idx ) {
    s2 <- c(s2,x[i])
}

Upvotes: 1

Views: 155

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176688

Yes.

> sz <- 5
> x <- 1:10
> set.seed(21); s1 <- sample(x,size=sz,replace=F)
> sz <- 5
> x <- 1:10
> s2 <- c()
> set.seed(21); idx <- sample(1:length(x),size=sz,replace=F)
> for ( i in idx ) {
+     s2 <- c(s2,x[i])
+ }
> identical(s1,s2)
[1] TRUE

Upvotes: 5

Related Questions