0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Just for sure, suppose the "inner" is used in the outer for-loop, should I define this "inner" before the whole for-loop code?
then it wont be changing as expected. You should not define it out of the outer loop.
Oh I got it thank you so much! Sorry I'm new to Stack Overflow, will the question automatically be closed if I accept the solution? I cannot find the close button on the page.
Once the an answer is accepted, it shows that the question has been solved.
1

You can do this with one for loop :

N = 3
N_list <- vector(mode = "list", length = N) 
list_names <- c('x', 'y', 'z')
names(N_list) <- list_names
inner <- 1:4

for (n in 1:N) {
   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

You can also use lapply :

lapply(seq_len(N), function(x) 10 * x + inner)

1 Comment

Thank you for the comment! lapply seems a better and simpler method in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.