带列表的嵌套 for 循环

Nested for-loop with lists

所以我想
(1) 使用向量函数创建一个大小为 3 的列表,将它们命名为 x,y,z
(2):写一个嵌套的for循环,外层循环遍历列表(n=1:N),内层从t=1:4
(3):赋值给向量中第t个位置的第n个列表,取值10n+t

我目前得到的是

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]]) 
}

尽管我希望列表如下:

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

我实际上每个列表只得到 14、24、34。

虽然我搜索了很多文章来了解嵌套for循环的逻辑,但我仍然不知道该怎么做。有人可以帮我吗?提前谢谢你。

你可以用一个 for 循环来做到这一点:

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

您也可以使用 lapply :

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

你几乎是正确的。检查一下:

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