Вопрос

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 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 

Другие советы

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 с атрибуция
Не связан с StackOverflow
scroll top