Data changes for taking taking sample from it in a loop

set.seed(11)
for(i in 1:4){
dat1<- rnorm(10, 0, 1)
dat2<- sample(dat1, 6, replace = T)
print(dat1)

}
If dat2 is run in the loop, then the result for dat1 is different from the output of dat1 if we don't run dat2. How can I fix dat1 while taking a sample within a loop?

Does this do what you want?

set.seed(11)
dat1<- rnorm(10, 0, 1)
dat2 <- vector(mode = "list", length = 4)
for(i in 1:4){
  dat2[[i]] <- sample(dat1, 6, replace = T)
}
dat2
#> [[1]]
#> [1]  1.32360565  0.02659437 -0.59103110  0.62491779  1.32360565 -0.93415132
#> 
#> [[2]]
#> [1] -1.51655310 -1.51655310  0.02659437  0.02659437 -1.51655310 -1.00412058
#> 
#> [[3]]
#> [1] -1.00412058  0.02659437 -0.04572296  0.62491779  1.32360565  0.62491779
#> 
#> [[4]]
#> [1]  0.62491779 -0.04572296  1.32360565 -1.36265335 -0.59103110  1.17848916

Created on 2023-09-20 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.