Loop and create list using R

安稳与你 提交于 2021-01-29 14:31:11

问题


Using R studio I would like to create a dynamic list using a loop. The loop is indexed by a and b, including another specification in the loop the structure is not anymore working and as result I get into the list only the last value. Below the code. Any suggestion?

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
}

回答1:


I'm assuming the list should be of length length(vec_a) * length(vec_b). I would suggest simply using an iterator like:

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


来源:https://stackoverflow.com/questions/59195787/loop-and-create-list-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!