Reputation: 18665
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
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