使用R循环并创建列表 [英] Loop and create list using R
本文介绍了使用R循环并创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用R studio我想使用循环创建一个动态列表.循环由a和b索引,包括循环中的另一个规范,该结构不再起作用,结果,我仅进入列表的最后一个值.代码下方.有什么建议吗?
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
}
推荐答案
我假设列表的长度应为 length(vec_a)* length(vec_b)
.我建议仅使用类似以下的迭代器:
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
}
}
这篇关于使用R循环并创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文