【问题标题】:Error in `*tmp*`[[k]] : subscript out of bounds in R`*tmp*`[[k]] 中的错误:R 中的下标超出范围
【发布时间】:2012-12-29 07:16:25
【问题描述】:

我想问一下为什么在初始化例如向量或其他类型的列表时出现此错误,我该如何解决?

> l <- list()
> l[[1]][1] <- 1
Error in `*tmp*`[[1]] : subscript out of bounds

这是我需要的全部代码,实际上我想要一个这样的向量列表:

mcorrelation <- list()
for(k in 1:7){
    for (ind in 1:7){
        mcorrelation[[k]][ind] <- co$estimate
    }
}

我应该提前初始化整个列表还是有其他方法可以避免出现此错误?

【问题讨论】:

    标签: r subscript


    【解决方案1】:

    “[”函数允许在没有循环的情况下进行多次赋值:

    > y <- NULL
    > y
    NULL
    > y[cbind(1:2, 1:2)] <- list( list(1,2), list(2,3))
    > y
    [[1]]
    [[1]][[1]]
    [1] 1
    
    [[1]][[2]]
    [1] 2
    
    
    [[2]]
    [[2]][[1]]
    [1] 2
    
    [[2]][[2]]
    [1] 3
    

    【讨论】:

      【解决方案2】:

      由于l 还没有a 向量,因此您不想在列表的第一个元素中指定位置。试试:

      l <- list()
      l[[1]] <- 1
      

      要在这个新向量中的特定位置添加附加值,最好将向量设置为要归档的值的已知长度(出于速度原因;请参阅为什么here)。这是一个示例循环:

      n <- 100
      l <- list()
      l[[1]] <- NaN*seq(n)
      for(i in seq(n)){
          l[[1]][i] <- i
      }
      

      关于你的具体例子:

      k <- 7
      ind <- 7
      mcorrelation <- vector(mode="list", k)
      for(i in seq(k)){
          mcorrelation[[i]] <- NaN*seq(ind)
          for (j in seq(ind)){
              mcorrelation[[i]][j] <- rnorm(1)
          }
      }
      mcorrelation 
      

      【讨论】:

      • 我想要一个在 for 循环中初始化的长向量列表。所以接下来的步骤是 l[[1]][2]
      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多