【问题标题】:Loop and create list using R使用 R 循环并创建列表
【发布时间】:2019-12-05 21:36:35
【问题描述】:

使用 R studio 我想使用循环创建一个动态列表。循环由 a 和 b 索引,包括循环中的另一个规范,该结构不再工作,因此我只进入列表中的最后一个值。代码下方。有什么建议吗?

mylist <- list()

vec_a <- c(1,2)
vec_b <- c(5,6)

for (a in vec_a) for (b in vec_b) {
  print(a)
  print(b)
  multp <- a*b
  print(multp)
  #mylist[i] <- multp
}

#solution not working
for (a in vec_a) for (b in vec_b) for (i in 1:dim(expand.grid(tau_c,HoR_c))[1]) {
  #print(a)
  #print(b)
  multp <- a*b
  #print(multp)
  mylist[i] <- multp #the list should contain the output for each iteration
}

【问题讨论】:

  • 在第一个循环中,您有mylist[i],但没有为该循环定义i。第二种,tau_cHoR_c 没有定义。
  • 尝试使用 ``` multp [i]

标签: r loops


【解决方案1】:

我假设列表的长度应该是length(vec_a) * length(vec_b)。我建议简单地使用如下迭代器:

i <- 0
for (a in vec_a) {
    for (b in vec_b) {
        i <- i + 1
        # i <- i + 0 before edit
        multp <- a * b
        mylist[i] <- multp
    }
}

【讨论】:

  • 好主意,在循环中用 i
  • 哈哈,我会改的。
猜你喜欢
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
相关资源
最近更新 更多