问题
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