【问题标题】:Complex for loop in R?R中的复杂for循环?
【发布时间】: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 的最后一个值开始。

谁能帮我解决这个问题?

【问题讨论】:

    标签: r for-loop iteration


    【解决方案1】:

    我们可以通过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
    

    【讨论】:

      【解决方案2】:

      我们可以创建从 1 到最大值到 cumsum 值的序列 inds。使用findInterval,我们可以创建中断来拆分数据。

      inds <- cumsum(cnt)
      inds1 <- seq(max(inds))
      split(inds1, findInterval(inds1, inds, left.open = TRUE))
      
      #$`0`
      #[1] 1 2 3 4 5 6
      
      #$`1`
      #[1]  7  8  9 10 11 12 13
      
      #$`2`
      #[1] 14 15 16 17 18 19 20 21
      
      #$`3`
      #[1] 22 23 24 25 26
      

      【讨论】:

        猜你喜欢
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2019-01-23
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多