Search code examples
rlistfor-loopnested-for-loop

Nested for-loop with lists


So I was trying to
(1) Use the vector function to create a list of size 3, name these as x,y,z
(2): Write a nested for loop, the outer loop iterating through the list (n=1:N), the inner from t=1:4
(3): Assign to the n−th list in each of the t−th positions in the vector, the value 10n+t

What I currently get is

N = 3
N_list <- vector(mode = "list", length = N) 
list_names <- c('x', 'y', 'z')
names(N_list) <- list_names
inner <- NULL
for (n in 1:N) {
    for (t in 1:4) {
        inner[[t]] <- t  
    }
    N_list[[n]] <- (10*n+inner[[t]]) 
}

Though I expect the list to be like:

$x  
[1] 11, 12, 13, 14  
$y    
[1] 21, 22, 23, 24  
$z  
[1] 31, 32, 33, 34  

I actually only get 14, 24, 34 for each list.

Though I searched a lot of articles to learn about the logic of nested for-loop, I'm still not sure how to do it. Could somebody help me with this? Thank you in advance.


Solution

  • you are almost correct. check this out:

    N = 3
    N_list <- vector(mode = "list", length = N) 
    list_names <- c('x', 'y', 'z')
    names(N_list) <- list_names
    
    for (n in 1:N) {
        inner <- NULL # You should define inner here.
        for (t in 1:4) {
            inner[t] <- t  
        }
        N_list[[n]] <- (10 * n + inner) 
    }
    
    N_list
    $x
    [1] 11 12 13 14
    
    $y
    [1] 21 22 23 24
    
    $z
    [1] 31 32 33 34