【发布时间】:2020-08-30 23:53:39
【问题描述】:
我如何在 R 中执行增量 for 循环。例如,我有以下示例数据:
index=0
cnt<-c(6,7,8,5)
for(i in 1:length(cnt))
{
for(j in 1:cnt[i])
{
index=index+1
}
print(index)
}
输出如下:
[1] 6
[1] 13
[1] 21
[1] 26
现在我想做的是添加另一个循环遍历index 的值。例如:
length=0
cnt<-c(6,7,8,5)
for(i in 1:length(cnt))
{
for(j in 1:cnt[i])
{
length=length+1
}
for(inner in 1:length)
{
print(inner)
}
}
但这并没有给我想要的输出,因为每次我运行它时它都是从 1 开始的。
我期望的输出是:
for the first iteration:
1,2,3,4,5,6
second iteration:
7,8,9,10,11,12,13
third iteration:
14,15,16,17,18,19,20,21
fourth iteration:
22,23,24,25,26
基本上,长度是inner 变量的迭代次数,但它应该从length 的最后一个值开始。
谁能帮我解决这个问题?
【问题讨论】: