Home > OS >  How can I use loops in R to create a series of values
How can I use loops in R to create a series of values

Time:08-09

I wanted to perform the following task with just a few lines of codes using loop functions available in R.

set.seed(1)
a1 <- sample(1:6, size = 1000, replace = TRUE)
set.seed(2)
a2 <- sample(1:6, size = 1000, replace = TRUE)
set.seed(3)
a3 <- sample(1:6, size = 1000, replace = TRUE)
set.seed(4)
a4 <- sample(1:6, size = 1000, replace = TRUE)

I wanted to repeat this process (say) 15 times with just a few lines of code. Use of for loop is appreciated. Thank you all in advance.

CodePudding user response:

Here is a for loop way. The results are stored in a matrix a, not in objects named a* lying about the global environment.

total_rows <- 1000L
total_cols <- 15L
a <- matrix(nrow = total_rows, ncol = total_cols,
            dimnames = list(NULL, paste0("a", seq_len(total_cols))))

for(i in seq_len(total_cols)) {
  set.seed(i)
  a[, i] <- sample(1:6, size = 1000, replace = TRUE)
}
head(a)
#>      a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15
#> [1,]  1  5  5  3  2  5  2  4  3   3   2   2   3   1   5
#> [2,]  4  6  2  3  3  2  3  2  5   1   2   2   5   1   2
#> [3,]  1  6  4  3  1  5  4  4  6   2   1   3   2   3   2
#> [4,]  2  1  4  4  3  6  2  2  3   4   1   6   5   4   1
#> [5,]  5  5  2  3  1  4  2  6  3   6   5   5   6   3   6
#> [6,]  3  1  3  6  1  4  6  1  3   3   4   5   6   6   1

Created on 2022-08-08 by the reprex package (v2.0.1)

  • Related