简体   繁体   English

`* tmp *`[[k]]中的错误:下标超出R的范围

[英]Error in `*tmp*`[[k]] : subscript out of bounds in R

I wanted to ask why I get this error while initializing a list of for example vectors or some other type and how can I fix it? 我想问一下为什么我在初始化例如矢量或其他类型的列表时会出现此错误,我该如何解决?

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

This is the whole code I need, in fact I want a list of vectors like this: 这是我需要的整个代码,实际上我想要一个这样的向量列表:

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

Should I initialize the whole list in advance or is there any other way for not getting this error? 我应该提前初始化整个列表还是有其他方法可以避免出现此错误?

Since l does not already have aa vector, you don't want to specify a position in the first element of the list. 由于l还没有矢量,因此您不希望在列表的第一个元素中指定位置。 Try: 尝试:

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

For adding additional values to specific places in this new vector, it is best to set the vector up with the known length of values to be filed in (for speed reasons; see why here ). 为了向此新向量中的特定位置添加其他值,最好将向量设置为要记录的已知值的长度(出于速度原因;请参阅此处的原因)。 Here is an example loop: 这是一个示例循环:

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

Regarding your specific example: 关于你的具体例子:

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 

The "[" function allows multiple assignments without loops: “[”函数允许多个赋值而没有循环:

> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM