creating list with for loop

Hello I am trying to create a list by appending to list element using for loops. Here is my code
list_additive <- list(alpha_a = c(),
beta_a = c(),
gamma_a = c())
for(a in 0.1:1){
for(b in 0.1:1){
for(g in 0.1:1){
append(list_additive$alpha_a, a)
append(list_additive$beta_a,b)
append(list_additive$gamma_a,g)
g = g + 0.1
}
b = b +0.1
}
a = a + 0.1
}

list_additive

my final result I want to create a data frame like the following
aplha beta gamma
0.1 0.1 0.1
0.1 0.1 0.2
0.1 0.1 0.3
.
.
0.1 0.2 0.1
0.1 0.2 0.2

Not sure what am I doing wrong

Hi @pikud1990,
Welcome to the RStudio Community Forum.

Nested for() loops are usually a suboptimal approach in R and are often a paradigm hangover from other languages. However, assuming you intended to produce 10^3 combinations, this example will work (see below), but also illustrates a simpler and safer way to achieve the same result:

list_additive <- list(alpha_a = c(),
                      beta_a = c(),
                      gamma_a = c())
for(a in seq(0.1, 1, 0.1)) {
  for (b in seq(0.1, 1, 0.1)) {
    for (g in seq(0.1, 1, 0.1)) {
      list_additive$alpha_a <- append(list_additive$alpha_a, a)
      list_additive$beta_a <- append(list_additive$beta_a, b)
      list_additive$gamma_a <- append(list_additive$gamma_a, g)
    }
  }
}

head(as.data.frame(list_additive), n=10)
#>    alpha_a beta_a gamma_a
#> 1      0.1    0.1     0.1
#> 2      0.1    0.1     0.2
#> 3      0.1    0.1     0.3
#> 4      0.1    0.1     0.4
#> 5      0.1    0.1     0.5
#> 6      0.1    0.1     0.6
#> 7      0.1    0.1     0.7
#> 8      0.1    0.1     0.8
#> 9      0.1    0.1     0.9
#> 10     0.1    0.1     1.0
tail(as.data.frame(list_additive), n=10)
#>      alpha_a beta_a gamma_a
#> 991        1      1     0.1
#> 992        1      1     0.2
#> 993        1      1     0.3
#> 994        1      1     0.4
#> 995        1      1     0.5
#> 996        1      1     0.6
#> 997        1      1     0.7
#> 998        1      1     0.8
#> 999        1      1     0.9
#> 1000       1      1     1.0

# Much easier way!
alpha <- seq(0.1, 1, 0.1)
beta <- seq(0.1, 1, 0.1)
gamma <- seq(0.1, 1, 0.1)

res <- data.frame(expand.grid(alpha, beta, gamma))[, c(3,2,1)] # Put columns in same order
head(res)
#>   Var3 Var2 Var1
#> 1  0.1  0.1  0.1
#> 2  0.1  0.1  0.2
#> 3  0.1  0.1  0.3
#> 4  0.1  0.1  0.4
#> 5  0.1  0.1  0.5
#> 6  0.1  0.1  0.6
tail(res)
#>      Var3 Var2 Var1
#> 995     1    1  0.5
#> 996     1    1  0.6
#> 997     1    1  0.7
#> 998     1    1  0.8
#> 999     1    1  0.9
#> 1000    1    1  1.0

Created on 2021-06-17 by the reprex package (v2.0.0)

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.