Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

subscript

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?

like image 407
hora Avatar asked Jan 15 '13 08:01

hora


People also ask

How do you solve a subscript out of bounds in R?

The subscript out of limits error occurs because the fourth column of the matrix does not exist. If we don't know how many columns the matrix has, we can use the ncol() function to figure it out.

What does error subscript out of bounds mean in R?

Then the R programming language returns the error message “subscript out of bounds”. In other words: If you are receiving the error message “subscript out of bounds” you should check whether you are trying to use a data element that does not exist in your data.


2 Answers

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 
like image 73
Marc in the box Avatar answered Sep 22 '22 04:09

Marc in the box


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
like image 28
IRTFM Avatar answered Sep 25 '22 04:09

IRTFM