问题描述
我该如何在R中执行增量循环。例如,我在下面有一个示例数据:
%lf
输出如下:
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)
}
现在我要做的是添加另一个for循环,该循环遍历[1] 6
[1] 13
[1] 21
[1] 26
的值。例如:
index
但这并没有给我想要的输出,因为每次我运行它都从1开始。
我期望的输出是:
length=0
cnt<-c(6,5)
for(i in 1:length(cnt))
{
for(j in 1:cnt[i])
{
length=length+1
}
for(inner in 1:length)
{
print(inner)
}
}
长度基本上是for the first iteration:
1,2,3,4,5,6
second iteration:
7,9,10,11,12,13
third iteration:
14,15,16,17,18,19,20,21
fourth iteration:
22,23,24,25,26
变量的迭代次数,但应从inner
的最后一个值开始。
有人可以帮我吗?
解决方法
我们可以使用Map
cnt1 <- cumsum(cnt)
Map(`:`,c(1,cnt1[-length(cnt1)]+1),cnt1)
#[[1]]
#[1] 1 2 3 4 5 6
#[[2]]
#[1] 7 8 9 10 11 12 13
#[[3]]
#[1] 14 15 16 17 18 19 20 21
#[[4]]
#[1] 22 23 24 25 26
还可以通过for
循环
cnt <- c(6,7,8,5)
tmp_prev <- 1
tmp <- cnt[1]
for(i in seq_along(cnt)) {
if(i == 1) {
tmp_prev <- tmp_prev
tmp <- cnt[i]
} else {
tmp_prev <- tmp_prev + cnt[i-1]
tmp <- tmp + cnt[i]
}
for(i in seq_along(tmp)) {
print(tmp_prev[i]:tmp[i])
}
}
#[1] 1 2 3 4 5 6
#[1] 7 8 9 10 11 12 13
#[1] 14 15 16 17 18 19 20 21
#[1] 22 23 24 25 26
,
我们可以创建从1到最大值到cumsum
的{{1}}值的序列。使用inds
,我们可以创建中断以拆分数据。
findInterval