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

2019-01-28 02:53发布

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?

标签: r subscript
2条回答
相关推荐>>
2楼-- · 2019-01-28 03:30

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
查看更多
老娘就宠你
3楼-- · 2019-01-28 03:44

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 
查看更多
登录 后发表回答