Are these two code snippets equivalent, ie are they doing the same thing?
For what I understand from the help of sample
they should do the same thing, ie 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])
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.