[英]Having trouble with nested loops (R)
I've wrote this nested loop so that, in the inner loop, the code runs through the first row;我编写了这个嵌套循环,以便在内部循环中,代码贯穿第一行; then, the outer one updates the loop so as to allow the inner one to run though the second row (and so on).
然后,外层更新循环以允许内层运行通过第二行(依此类推)。 The data comes from 'supergerador', a matrix.
数据来自矩阵“supergerador”。 "rodadas" is the row size and "n" is the column size.
“rodadas”是行大小,“n”是列大小。 "vec" is the vector of interest.
“vec”是感兴趣的向量。 Thank you in advance!
先感谢您!
Edit: i, j were initially assigned i = 1, j = 2编辑: i, j 最初被分配 i = 1, j = 2
for(e in 1:rodadas) {
for(f in 1:(n-1)) {
if(j >= 10) {
vec[f] = min(supergerador[i, j] - supergerador[i, j - 1], 1 - supergerador[i, j])
}
else {
vec[f] = func(i, j)
}
j = j + 1
}
i = i + 1
}
func
is defined as func
定义为
func = function(i, j) {
minf = min(supergerador[i, j] - supergerador[i, j - 1], supergerador[i, j + 1] - supergerador[i, j])
return(minf)
}
For reference, this is what the nested loop returns.作为参考,这是嵌套循环返回的内容。 You can tell that it only went through a single row.
你可以说它只经过了一行。
> vec
[1] 0.127387378 0.068119707 0.043472981 0.043472981 0.027431603 0.027431603
[7] 0.015739046 0.008010766 0.008010766
I'm not quite sure what you are intending to do here, but here is a few suggestions and code edits:我不太确定您打算在这里做什么,但这里有一些建议和代码编辑:
Suggestions:建议:
x[i, j]
, store this in a variable and then use this variable in your result.x[i, j]
,请将其存储在一个变量中,然后在您的结果中使用此变量。 Incorporating these into your code I beliieve you are looking for将这些合并到您的代码中,我相信您正在寻找
for(i in 1:rodadas) {
for(j in 2:n) {
x1 = supergerador[i, j]
x2 = supergerador[i, j - 1]
if(j >= 10) {
vec[f] = min(x1 - x2, 1 - x1)
}
else {
vec[f] = min(x1 - x2, supergerador[i, j + 1] - x1)
}
}
}
Here i am making the assumption that you wish to loop over columns for every row up to rodadas
.在这里,我假设您希望将每一行的列循环到
rodadas
。
Once you get a bit more familiarized with R you should look into vectorization.一旦您对 R 更加熟悉,您应该研究一下矢量化。 With a bit more knowledge of your problem, we should be very easily able to vectorize your second for loop, removing your
if
statement and performing the calculation in 1 fast sweep.对您的问题有了更多了解,我们应该可以很容易地向量化您的第二个 for 循环,删除您的
if
语句并在 1 次快速扫描中执行计算。 But until then this is a good place to start your programming experience and having a strong understanding of for-loops
is vital in any language.但在那之前,这是一个开始您的编程体验的好地方,并且对
for-loops
有深刻的理解对于任何语言都至关重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.