是否可以在 r 中为循环生成 seq() 列表?

is it possible to generate a list of seq() for loop in r?

我是 R 的新手,在使用 seq() 和列表执行循环时遇到了一些问题。我在 SO 中搜索了 QnA,但我必须找到与此相同的问题。如果有重复的 QnA,我深表歉意。 我知道如何生成数字序列和使用列表生成的基础知识,但是我想知道我们是否可以为每个循环生成一个序列列表。

这是我的代码示例

J <- seq(50,200,50) # (I actually wanted to use 1: J to generate a sequence of each combinations . i.e: 1:50, 1:100 etc)

K <- seq(10,100,10) #(same as the above)

set.seed(1234)

for (i in J) {

    for (j in K){
        f <- rnorm(i + 1) # the f value I would like it to be generate in terms of list, since the j have 4 sequence value, if possible, could it adhere to that?

    }

}

我尝试同时使用序列和列表函数,但我不断收到消息:

if print(i)

产出

[1]1

.
.
.

[1]50

警告信息:

In 1:(seq(50, 200, 50)) : numerical expression has 6 elements: only the first used

for (i in 1:list(seq(50,200,50)))

Error in 1:list(seq(50, 200, 50)) : NA/NaN argument

请问这样的循环组合是否可以执行?你能指导我吗?非常感谢。

还不确定你在问什么,但这就是你要找的吗?很难post将此作为评论

J <- seq(50,200,50)
l1 <- vector(length = length(J), mode = "list")
for (i in seq_along(J)){    # you know of seq_along() right?
  l1[[i]] = rnorm(J[i])
}

对于第二个问题,你想要矩阵的列表(J)列表(K):请注意帽子<<-从来都不是一个好的做法,但现在这是我能想到的与!

注意:要了解实际发生的情况,请进入 debug 模式:即在定义 func 之后,还要传递 debug(func),然后将进入 step-by-step执行。

l1 <- vector(length = length(J), mode = "list")
l2 <- vector(length = length(K), mode = "list")

func <- function(x){
  l1[[x]] <- l2
  func1 <- function(y) {
    l1[[x]][[y]] <<- matrix(rnorm(J[x]*K[y]), 
                          ncol = J[x], 
                          nrow = K[y])
  }
  lapply(seq_along(l1[[x]]),func1)
}

lapply(seq_along(l1), func)