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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With