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

喜你入骨 提交于 2019-11-28 07:46:32

问题


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?


回答1:


Since l does not already have a a vector, you don't want to specify a position in the first element of the list. 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 



回答2:


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


来源:https://stackoverflow.com/questions/14333525/error-in-tmpk-subscript-out-of-bounds-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!