【问题标题】:R error type "Subscript out of bounds"R错误类型“下标越界”
【发布时间】:2014-01-14 13:29:30
【问题描述】:

我正在模拟一个相关矩阵,其中 60 个变量以下列方式相关:

  • 每两个变量(1-2、3-4...59-60)更高(0.6)
  • 对于每组 12 个变量 (1-12,13-24...),中等 (0.3)

    mc <- matrix(0,60,60)   
    diag(mc) <- 1
    
    for (c in seq(1,59,2)){    # every pair of variables in order are given 0.6 correlation
    mc[c,c+1] <- 0.6
    mc[c+1,c] <- 0.6
    }
    
    
    for (n in seq(1,51,10)){        # every group of 12 are given correlation of 0.3 
      for (w in seq(12,60,12)){     # these are variables 11-12, 21-22 and such.
        mc[n:n+1,c(n+2,w)] <- 0.2
        mc[c(n+2,w),n:n+1] <- 0.2
      }
    }
    
    for (m in seq(3,9,2)){               # every group of 12 are given correlation of 0.3
       for (w in seq(12,60,12)){          # these variables are the rest.
         mc[m:m+1,c(1:m-1,m+2:w)] <- 0.2
         mc[c(1:m-1,m+2:w),m:m+1] <- 0.2
       }
    }
    

第一个循环运行良好,但第二个和第三个循环不行。我收到此错误消息:

Error in `[<-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : 
  subscript out of bounds

Error in `[<-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : 
  subscript out of bounds

我非常感谢任何提示,因为我没有看到循环命令超出矩阵维度。提前非常感谢!

【问题讨论】:

标签: r loops


【解决方案1】:

请注意,: 优先于 +。例如,n:n+1n+1 相同。我猜你想要n:(n+1)

w的最大值为60:

w <- 60
m <- 1
m+2:w
#[1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#[49] 51 52 53 54 55 56 57 58 59 60 61

61 超出范围。你需要添加很多括号。

【讨论】:

  • 感谢 Roland 抽出宝贵时间 =)
猜你喜欢
  • 2015-04-03
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
相关资源
最近更新 更多